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

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.29      crook      14: @comment .. would be useful to have a word that identified all deferred words
                     15: @comment should semantics stuff in intro be moved to another section
                     16: 
1.28      crook      17: 
1.1       anton      18: @comment %**start of header (This is for running Texinfo on a region.)
                     19: @setfilename gforth.info
                     20: @settitle Gforth Manual
                     21: @dircategory GNU programming tools
                     22: @direntry
                     23: * Gforth: (gforth).             A fast interpreter for the Forth language.
                     24: @end direntry
1.49      anton      25: @c The Texinfo manual also recommends doing this, but for Gforth it may
                     26: @c  not make much sense
                     27: @c @dircategory Individual utilities
                     28: @c @direntry
                     29: @c * Gforth: (gforth)Invoking Gforth.      gforth, gforth-fast, gforthmi
                     30: @c @end direntry
                     31: 
1.1       anton      32: @comment @setchapternewpage odd
1.29      crook      33: @comment TODO this gets left in by HTML converter
1.12      anton      34: @macro progstyle {}
                     35: Programming style note:
1.3       anton      36: @end macro
1.48      anton      37: 
                     38: @macro assignment {}
                     39: @table @i
                     40: @item Assignment:
                     41: @end macro
                     42: @macro endassignment {}
                     43: @end table
                     44: @end macro
                     45: 
1.1       anton      46: @comment %**end of header (This is for running Texinfo on a region.)
                     47: 
1.29      crook      48: 
                     49: @comment ----------------------------------------------------------
                     50: @comment macros for beautifying glossary entries
                     51: @comment if these are used, need to strip them out for HTML converter
                     52: @comment else they get repeated verbatim in HTML output.
                     53: @comment .. not working yet.
                     54: 
                     55: @macro GLOSS-START {}
                     56: @iftex
                     57: @ninerm
                     58: @end iftex
                     59: @end macro
                     60: 
                     61: @macro GLOSS-END {}
                     62: @iftex
                     63: @rm
                     64: @end iftex
                     65: @end macro
                     66: 
                     67: @comment ----------------------------------------------------------
                     68: 
                     69: 
1.10      anton      70: @include version.texi
                     71: 
1.49      anton      72: @ifnottex
1.11      anton      73: This file documents Gforth @value{VERSION}
1.1       anton      74: 
1.26      crook      75: Copyright @copyright{} 1995-1999 Free Software Foundation, Inc.
1.1       anton      76: 
                     77:      Permission is granted to make and distribute verbatim copies of
                     78:      this manual provided the copyright notice and this permission notice
                     79:      are preserved on all copies.
                     80:      
                     81: @ignore
                     82:      Permission is granted to process this file through TeX and print the
                     83:      results, provided the printed document carries a copying permission
                     84:      notice identical to this one except for the removal of this paragraph
                     85:      (this paragraph not being relevant to the printed manual).
                     86:      
                     87: @end ignore
                     88:      Permission is granted to copy and distribute modified versions of this
                     89:      manual under the conditions for verbatim copying, provided also that the
                     90:      sections entitled "Distribution" and "General Public License" are
                     91:      included exactly as in the original, and provided that the entire
                     92:      resulting derived work is distributed under the terms of a permission
                     93:      notice identical to this one.
                     94:      
                     95:      Permission is granted to copy and distribute translations of this manual
                     96:      into another language, under the above conditions for modified versions,
                     97:      except that the sections entitled "Distribution" and "General Public
                     98:      License" may be included in a translation approved by the author instead
                     99:      of in the original English.
1.49      anton     100: @end ifnottex
1.1       anton     101: 
                    102: @finalout
                    103: @titlepage
                    104: @sp 10
                    105: @center @titlefont{Gforth Manual}
                    106: @sp 2
1.11      anton     107: @center for version @value{VERSION}
1.1       anton     108: @sp 2
1.34      anton     109: @center Neal Crook
1.1       anton     110: @center Anton Ertl
1.6       pazsan    111: @center Bernd Paysan
1.5       anton     112: @center Jens Wilke
1.1       anton     113: @sp 3
1.47      crook     114: @center This manual is permanently under construction and was last updated on 15-Mar-2000
1.1       anton     115: 
                    116: @comment  The following two commands start the copyright page.
                    117: @page
                    118: @vskip 0pt plus 1filll
1.29      crook     119: Copyright @copyright{} 1995--1999 Free Software Foundation, Inc.
1.1       anton     120: 
                    121: @comment !! Published by ... or You can get a copy of this manual ...
                    122: 
                    123:      Permission is granted to make and distribute verbatim copies of
                    124:      this manual provided the copyright notice and this permission notice
                    125:      are preserved on all copies.
                    126:      
                    127:      Permission is granted to copy and distribute modified versions of this
                    128:      manual under the conditions for verbatim copying, provided also that the
                    129:      sections entitled "Distribution" and "General Public License" are
                    130:      included exactly as in the original, and provided that the entire
                    131:      resulting derived work is distributed under the terms of a permission
                    132:      notice identical to this one.
                    133:      
                    134:      Permission is granted to copy and distribute translations of this manual
                    135:      into another language, under the above conditions for modified versions,
                    136:      except that the sections entitled "Distribution" and "General Public
                    137:      License" may be included in a translation approved by the author instead
                    138:      of in the original English.
                    139: @end titlepage
                    140: 
                    141: @node Top, License, (dir), (dir)
1.49      anton     142: @ifnottex
1.1       anton     143: Gforth is a free implementation of ANS Forth available on many
1.11      anton     144: personal machines. This manual corresponds to version @value{VERSION}.
1.49      anton     145: @end ifnottex
1.1       anton     146: 
                    147: @menu
1.21      crook     148: * License::                     The GPL
1.26      crook     149: * Goals::                       About the Gforth Project
1.29      crook     150: * Gforth Environment::          Starting (and exiting) Gforth
1.48      anton     151: * Tutorial::                    Hands-on Forth Tutorial
1.21      crook     152: * Introduction::                An introduction to ANS Forth
1.1       anton     153: * Words::                       Forth words available in Gforth
1.24      anton     154: * Error messages::              How to interpret them
1.1       anton     155: * Tools::                       Programming tools
                    156: * ANS conformance::             Implementation-defined options etc.
                    157: * Model::                       The abstract machine of Gforth
                    158: * Integrating Gforth::          Forth as scripting language for applications
                    159: * Emacs and Gforth::            The Gforth Mode
                    160: * Image Files::                 @code{.fi} files contain compiled code
                    161: * Engine::                      The inner interpreter and the primitives
1.24      anton     162: * Binding to System Library::   
1.13      pazsan    163: * Cross Compiler::              The Cross Compiler
1.1       anton     164: * Bugs::                        How to report them
                    165: * Origin::                      Authors and ancestors of Gforth
1.21      crook     166: * Forth-related information::   Books and places to look on the WWW
1.1       anton     167: * Word Index::                  An item for each Forth word
1.41      anton     168: * Name Index::                  Forth words, only names listed
1.1       anton     169: * Concept Index::               A menu covering many topics
1.12      anton     170: 
1.48      anton     171: @detailmenu --- The Detailed Node Listing ---
1.12      anton     172: 
1.26      crook     173: Goals of Gforth
                    174: 
                    175: * Gforth Extensions Sinful?::
                    176: 
1.29      crook     177: Gforth Environment
                    178: 
1.32      anton     179: * Invoking Gforth::             Getting in
                    180: * Leaving Gforth::              Getting out
                    181: * Command-line editing::        
1.48      anton     182: * Upper and lower case::        
                    183: * Environment variables::       that affect how Gforth starts up
1.32      anton     184: * Gforth Files::                What gets installed and where
1.48      anton     185: * Startup speed::               When 35ms is not fast enough ...
                    186: 
                    187: Forth Tutorial
                    188: 
                    189: * Starting Gforth Tutorial::    
                    190: * Syntax Tutorial::             
                    191: * Crash Course Tutorial::       
                    192: * Stack Tutorial::              
                    193: * Arithmetics Tutorial::        
                    194: * Stack Manipulation Tutorial::  
                    195: * Using files for Forth code Tutorial::  
                    196: * Comments Tutorial::           
                    197: * Colon Definitions Tutorial::  
                    198: * Decompilation Tutorial::      
                    199: * Stack-Effect Comments Tutorial::  
                    200: * Types Tutorial::              
                    201: * Factoring Tutorial::          
                    202: * Designing the stack effect Tutorial::  
                    203: * Local Variables Tutorial::    
                    204: * Conditional execution Tutorial::  
                    205: * Flags and Comparisons Tutorial::  
                    206: * General Loops Tutorial::      
                    207: * Counted loops Tutorial::      
                    208: * Recursion Tutorial::          
                    209: * Leaving definitions or loops Tutorial::  
                    210: * Return Stack Tutorial::       
                    211: * Memory Tutorial::             
                    212: * Characters and Strings Tutorial::  
                    213: * Alignment Tutorial::          
                    214: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                    215: * Execution Tokens Tutorial::   
                    216: * Exceptions Tutorial::         
                    217: * Defining Words Tutorial::     
                    218: * Arrays and Records Tutorial::  
                    219: * POSTPONE Tutorial::           
                    220: * Literal Tutorial::            
                    221: * Advanced macros Tutorial::    
                    222: * Compilation Tokens Tutorial::  
                    223: * Wordlists and Search Order Tutorial::  
1.29      crook     224: 
1.24      anton     225: An Introduction to ANS Forth
                    226: 
                    227: * Introducing the Text Interpreter::
                    228: * Stacks and Postfix notation::
                    229: * Your first definition::
                    230: * How does that work?::
                    231: * Forth is written in Forth::
                    232: * Review - elements of a Forth system::
1.29      crook     233: * Where to go next::
1.24      anton     234: * Exercises::
                    235: 
1.12      anton     236: Forth Words
                    237: 
                    238: * Notation::                    
1.21      crook     239: * Comments::
                    240: * Boolean Flags::
1.12      anton     241: * Arithmetic::                  
                    242: * Stack Manipulation::          
                    243: * Memory::                      
                    244: * Control Structures::          
                    245: * Defining Words::              
1.47      crook     246: * Interpretation and Compilation Semantics::
                    247: * Tokens for Words::            
1.21      crook     248: * The Text Interpreter::
                    249: * Word Lists::                   
                    250: * Environmental Queries::
1.12      anton     251: * Files::                       
                    252: * Blocks::                      
                    253: * Other I/O::                   
                    254: * Programming Tools::           
                    255: * Assembler and Code Words::    
                    256: * Threading Words::             
1.26      crook     257: * Locals::                      
                    258: * Structures::                  
                    259: * Object-oriented Forth::       
1.21      crook     260: * Passing Commands to the OS::
1.47      crook     261: * Keeping track of Time::
1.21      crook     262: * Miscellaneous Words::
1.12      anton     263: 
                    264: Arithmetic
                    265: 
                    266: * Single precision::            
                    267: * Bitwise operations::          
1.21      crook     268: * Double precision::            Double-cell integer arithmetic
                    269: * Numeric comparison::
1.32      anton     270: * Mixed precision::             Operations with single and double-cell integers
1.12      anton     271: * Floating Point::              
                    272: 
                    273: Stack Manipulation
                    274: 
                    275: * Data stack::                  
                    276: * Floating point stack::        
                    277: * Return stack::                
                    278: * Locals stack::                
                    279: * Stack pointer manipulation::  
                    280: 
                    281: Memory
                    282: 
1.32      anton     283: * Memory model::                
                    284: * Dictionary allocation::       
                    285: * Heap Allocation::             
                    286: * Memory Access::               
                    287: * Address arithmetic::          
                    288: * Memory Blocks::               
1.12      anton     289: 
                    290: Control Structures
                    291: 
1.41      anton     292: * Selection::                   IF ... ELSE ... ENDIF
                    293: * Simple Loops::                BEGIN ...
1.32      anton     294: * Counted Loops::               DO
                    295: * Arbitrary control structures::
                    296: * Calls and returns::
1.12      anton     297: * Exception Handling::          
                    298: 
                    299: Defining Words
                    300: 
1.45      crook     301: * CREATE::
1.44      crook     302: * Variables::                   Variables and user variables
                    303: * Constants::
                    304: * Values::                      Initialised variables
1.32      anton     305: * Colon Definitions::
1.44      crook     306: * Anonymous Definitions::       Definitions without names
1.32      anton     307: * User-defined Defining Words::
1.44      crook     308: * Deferred words::              Allow forward references
                    309: * Aliases::
1.32      anton     310: * Supplying names::
1.47      crook     311: 
1.59      anton     312: User-defined Defining Words
                    313: 
                    314: * CREATE..DOES> applications::  
                    315: * CREATE..DOES> details::       
                    316: * Advanced does> usage example::  
                    317: 
1.47      crook     318: Interpretation and Compilation Semantics
                    319: 
1.44      crook     320: * Combined words::
1.12      anton     321: 
1.21      crook     322: The Text Interpreter
                    323: 
1.29      crook     324: * Input Sources::
1.21      crook     325: * Number Conversion::
                    326: * Interpret/Compile states::
                    327: * Literals::
                    328: * Interpreter Directives::
                    329: 
1.26      crook     330: Word Lists
                    331: 
                    332: * Why use word lists?::
                    333: * Word list examples::
                    334: 
                    335: Files
                    336: 
1.48      anton     337: * Forth source files::          
                    338: * General files::               
                    339: * Search Paths::                
                    340: 
                    341: Search Paths
                    342: 
                    343: * Forth Search Paths::          
1.26      crook     344: * General Search Paths::        
                    345: 
                    346: Other I/O
                    347: 
1.32      anton     348: * Simple numeric output::       Predefined formats
                    349: * Formatted numeric output::    Formatted (pictured) output
                    350: * String Formats::              How Forth stores strings in memory
                    351: * Displaying characters and strings:: Other stuff
                    352: * Input::                       Input
1.26      crook     353: 
                    354: Programming Tools
                    355: 
                    356: * Debugging::                   Simple and quick.
                    357: * Assertions::                  Making your programs self-checking.
1.46      pazsan    358: * Singlestep Debugger::         Executing your program word by word.
1.26      crook     359: 
1.59      anton     360: Assembler and Code Words
                    361: 
                    362: * Code and ;code::              
                    363: * Common Assembler::            Assembler Syntax
                    364: * Common Disassembler::         
                    365: * 386 Assembler::               Deviations and special cases
                    366: * Alpha Assembler::             Deviations and special cases
                    367: * MIPS assembler::              Deviations and special cases
                    368: * Other assemblers::            How to write them
                    369: 
1.26      crook     370: Locals
                    371: 
                    372: * Gforth locals::               
                    373: * ANS Forth locals::            
                    374: 
                    375: Gforth locals
                    376: 
                    377: * Where are locals visible by name?::  
                    378: * How long do locals live?::    
                    379: * Programming Style::           
                    380: * Implementation::              
                    381: 
1.12      anton     382: Structures
                    383: 
                    384: * Why explicit structure support?::  
                    385: * Structure Usage::             
                    386: * Structure Naming Convention::  
                    387: * Structure Implementation::    
                    388: * Structure Glossary::          
                    389: 
                    390: Object-oriented Forth
                    391: 
1.48      anton     392: * Why object-oriented programming?::  
                    393: * Object-Oriented Terminology::  
                    394: * Objects::                     
                    395: * OOF::                         
                    396: * Mini-OOF::                    
1.23      crook     397: * Comparison with other object models::  
1.12      anton     398: 
1.24      anton     399: The @file{objects.fs} model
1.12      anton     400: 
                    401: * Properties of the Objects model::  
                    402: * Basic Objects Usage::         
1.41      anton     403: * The Objects base class::      
1.12      anton     404: * Creating objects::            
                    405: * Object-Oriented Programming Style::  
                    406: * Class Binding::               
                    407: * Method conveniences::         
                    408: * Classes and Scoping::         
1.41      anton     409: * Dividing classes::            
1.12      anton     410: * Object Interfaces::           
                    411: * Objects Implementation::      
                    412: * Objects Glossary::            
                    413: 
1.24      anton     414: The @file{oof.fs} model
1.12      anton     415: 
                    416: * Properties of the OOF model::
                    417: * Basic OOF Usage::
1.23      crook     418: * The OOF base class::
1.12      anton     419: * Class Declaration::
                    420: * Class Implementation::
                    421: 
1.24      anton     422: The @file{mini-oof.fs} model
1.23      crook     423: 
1.48      anton     424: * Basic Mini-OOF Usage::        
                    425: * Mini-OOF Example::            
                    426: * Mini-OOF Implementation::     
                    427: * Comparison with other object models::  
1.23      crook     428: 
1.12      anton     429: Tools
                    430: 
                    431: * ANS Report::                  Report the words used, sorted by wordset.
                    432: 
                    433: ANS conformance
                    434: 
                    435: * The Core Words::              
                    436: * The optional Block word set::  
                    437: * The optional Double Number word set::  
                    438: * The optional Exception word set::  
                    439: * The optional Facility word set::  
                    440: * The optional File-Access word set::  
                    441: * The optional Floating-Point word set::  
                    442: * The optional Locals word set::  
                    443: * The optional Memory-Allocation word set::  
                    444: * The optional Programming-Tools word set::  
                    445: * The optional Search-Order word set::  
                    446: 
                    447: The Core Words
                    448: 
                    449: * core-idef::                   Implementation Defined Options                   
                    450: * core-ambcond::                Ambiguous Conditions                
                    451: * core-other::                  Other System Documentation                  
                    452: 
                    453: The optional Block word set
                    454: 
                    455: * block-idef::                  Implementation Defined Options
                    456: * block-ambcond::               Ambiguous Conditions               
                    457: * block-other::                 Other System Documentation                 
                    458: 
                    459: The optional Double Number word set
                    460: 
                    461: * double-ambcond::              Ambiguous Conditions              
                    462: 
                    463: The optional Exception word set
                    464: 
                    465: * exception-idef::              Implementation Defined Options              
                    466: 
                    467: The optional Facility word set
                    468: 
                    469: * facility-idef::               Implementation Defined Options               
                    470: * facility-ambcond::            Ambiguous Conditions            
                    471: 
                    472: The optional File-Access word set
                    473: 
                    474: * file-idef::                   Implementation Defined Options
                    475: * file-ambcond::                Ambiguous Conditions                
                    476: 
                    477: The optional Floating-Point word set
                    478: 
                    479: * floating-idef::               Implementation Defined Options
                    480: * floating-ambcond::            Ambiguous Conditions            
                    481: 
                    482: The optional Locals word set
                    483: 
                    484: * locals-idef::                 Implementation Defined Options                 
                    485: * locals-ambcond::              Ambiguous Conditions              
                    486: 
                    487: The optional Memory-Allocation word set
                    488: 
                    489: * memory-idef::                 Implementation Defined Options                 
                    490: 
                    491: The optional Programming-Tools word set
                    492: 
                    493: * programming-idef::            Implementation Defined Options            
                    494: * programming-ambcond::         Ambiguous Conditions         
                    495: 
                    496: The optional Search-Order word set
                    497: 
                    498: * search-idef::                 Implementation Defined Options                 
                    499: * search-ambcond::              Ambiguous Conditions              
                    500: 
                    501: Image Files
                    502: 
1.24      anton     503: * Image Licensing Issues::      Distribution terms for images.
                    504: * Image File Background::       Why have image files?
1.32      anton     505: * Non-Relocatable Image Files::   don't always work.
1.24      anton     506: * Data-Relocatable Image Files::  are better.
1.32      anton     507: * Fully Relocatable Image Files:: better yet.
1.24      anton     508: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.32      anton     509: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.24      anton     510: * Modifying the Startup Sequence::  and turnkey applications.
1.12      anton     511: 
                    512: Fully Relocatable Image Files
                    513: 
1.27      crook     514: * gforthmi::                    The normal way
1.12      anton     515: * cross.fs::                    The hard way
                    516: 
                    517: Engine
                    518: 
                    519: * Portability::                 
                    520: * Threading::                   
                    521: * Primitives::                  
                    522: * Performance::                 
                    523: 
                    524: Threading
                    525: 
                    526: * Scheduling::                  
                    527: * Direct or Indirect Threaded?::  
                    528: * DOES>::                       
                    529: 
                    530: Primitives
                    531: 
                    532: * Automatic Generation::        
                    533: * TOS Optimization::            
                    534: * Produced code::               
1.13      pazsan    535: 
                    536: Cross Compiler
                    537: 
                    538: * Using the Cross Compiler::
                    539: * How the Cross Compiler Works::
                    540: 
1.24      anton     541: Other Forth-related information
1.21      crook     542: 
                    543: * Internet resources::
                    544: * Books::
                    545: * The Forth Interest Group::
                    546: * Conferences::
                    547: 
1.24      anton     548: @end detailmenu
1.1       anton     549: @end menu
                    550: 
1.26      crook     551: @node License, Goals, Top, Top
1.1       anton     552: @unnumbered GNU GENERAL PUBLIC LICENSE
                    553: @center Version 2, June 1991
                    554: 
                    555: @display
                    556: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
                    557: 675 Mass Ave, Cambridge, MA 02139, USA
                    558: 
                    559: Everyone is permitted to copy and distribute verbatim copies
                    560: of this license document, but changing it is not allowed.
                    561: @end display
                    562: 
                    563: @unnumberedsec Preamble
                    564: 
                    565:   The licenses for most software are designed to take away your
                    566: freedom to share and change it.  By contrast, the GNU General Public
                    567: License is intended to guarantee your freedom to share and change free
                    568: software---to make sure the software is free for all its users.  This
                    569: General Public License applies to most of the Free Software
                    570: Foundation's software and to any other program whose authors commit to
                    571: using it.  (Some other Free Software Foundation software is covered by
                    572: the GNU Library General Public License instead.)  You can apply it to
                    573: your programs, too.
                    574: 
                    575:   When we speak of free software, we are referring to freedom, not
                    576: price.  Our General Public Licenses are designed to make sure that you
                    577: have the freedom to distribute copies of free software (and charge for
                    578: this service if you wish), that you receive source code or can get it
                    579: if you want it, that you can change the software or use pieces of it
                    580: in new free programs; and that you know you can do these things.
                    581: 
                    582:   To protect your rights, we need to make restrictions that forbid
                    583: anyone to deny you these rights or to ask you to surrender the rights.
                    584: These restrictions translate to certain responsibilities for you if you
                    585: distribute copies of the software, or if you modify it.
                    586: 
                    587:   For example, if you distribute copies of such a program, whether
                    588: gratis or for a fee, you must give the recipients all the rights that
                    589: you have.  You must make sure that they, too, receive or can get the
                    590: source code.  And you must show them these terms so they know their
                    591: rights.
                    592: 
                    593:   We protect your rights with two steps: (1) copyright the software, and
                    594: (2) offer you this license which gives you legal permission to copy,
                    595: distribute and/or modify the software.
                    596: 
                    597:   Also, for each author's protection and ours, we want to make certain
                    598: that everyone understands that there is no warranty for this free
                    599: software.  If the software is modified by someone else and passed on, we
                    600: want its recipients to know that what they have is not the original, so
                    601: that any problems introduced by others will not reflect on the original
                    602: authors' reputations.
                    603: 
                    604:   Finally, any free program is threatened constantly by software
                    605: patents.  We wish to avoid the danger that redistributors of a free
                    606: program will individually obtain patent licenses, in effect making the
                    607: program proprietary.  To prevent this, we have made it clear that any
                    608: patent must be licensed for everyone's free use or not licensed at all.
                    609: 
                    610:   The precise terms and conditions for copying, distribution and
                    611: modification follow.
                    612: 
                    613: @iftex
                    614: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
                    615: @end iftex
1.49      anton     616: @ifnottex
1.1       anton     617: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
1.49      anton     618: @end ifnottex
1.1       anton     619: 
                    620: @enumerate 0
                    621: @item
                    622: This License applies to any program or other work which contains
                    623: a notice placed by the copyright holder saying it may be distributed
                    624: under the terms of this General Public License.  The ``Program'', below,
                    625: refers to any such program or work, and a ``work based on the Program''
                    626: means either the Program or any derivative work under copyright law:
                    627: that is to say, a work containing the Program or a portion of it,
                    628: either verbatim or with modifications and/or translated into another
                    629: language.  (Hereinafter, translation is included without limitation in
                    630: the term ``modification''.)  Each licensee is addressed as ``you''.
                    631: 
                    632: Activities other than copying, distribution and modification are not
                    633: covered by this License; they are outside its scope.  The act of
                    634: running the Program is not restricted, and the output from the Program
                    635: is covered only if its contents constitute a work based on the
                    636: Program (independent of having been made by running the Program).
                    637: Whether that is true depends on what the Program does.
                    638: 
                    639: @item
                    640: You may copy and distribute verbatim copies of the Program's
                    641: source code as you receive it, in any medium, provided that you
                    642: conspicuously and appropriately publish on each copy an appropriate
                    643: copyright notice and disclaimer of warranty; keep intact all the
                    644: notices that refer to this License and to the absence of any warranty;
                    645: and give any other recipients of the Program a copy of this License
                    646: along with the Program.
                    647: 
                    648: You may charge a fee for the physical act of transferring a copy, and
                    649: you may at your option offer warranty protection in exchange for a fee.
                    650: 
                    651: @item
                    652: You may modify your copy or copies of the Program or any portion
                    653: of it, thus forming a work based on the Program, and copy and
                    654: distribute such modifications or work under the terms of Section 1
                    655: above, provided that you also meet all of these conditions:
                    656: 
                    657: @enumerate a
                    658: @item
                    659: You must cause the modified files to carry prominent notices
                    660: stating that you changed the files and the date of any change.
                    661: 
                    662: @item
                    663: You must cause any work that you distribute or publish, that in
                    664: whole or in part contains or is derived from the Program or any
                    665: part thereof, to be licensed as a whole at no charge to all third
                    666: parties under the terms of this License.
                    667: 
                    668: @item
                    669: If the modified program normally reads commands interactively
                    670: when run, you must cause it, when started running for such
                    671: interactive use in the most ordinary way, to print or display an
                    672: announcement including an appropriate copyright notice and a
                    673: notice that there is no warranty (or else, saying that you provide
                    674: a warranty) and that users may redistribute the program under
                    675: these conditions, and telling the user how to view a copy of this
                    676: License.  (Exception: if the Program itself is interactive but
                    677: does not normally print such an announcement, your work based on
                    678: the Program is not required to print an announcement.)
                    679: @end enumerate
                    680: 
                    681: These requirements apply to the modified work as a whole.  If
                    682: identifiable sections of that work are not derived from the Program,
                    683: and can be reasonably considered independent and separate works in
                    684: themselves, then this License, and its terms, do not apply to those
                    685: sections when you distribute them as separate works.  But when you
                    686: distribute the same sections as part of a whole which is a work based
                    687: on the Program, the distribution of the whole must be on the terms of
                    688: this License, whose permissions for other licensees extend to the
                    689: entire whole, and thus to each and every part regardless of who wrote it.
                    690: 
                    691: Thus, it is not the intent of this section to claim rights or contest
                    692: your rights to work written entirely by you; rather, the intent is to
                    693: exercise the right to control the distribution of derivative or
                    694: collective works based on the Program.
                    695: 
                    696: In addition, mere aggregation of another work not based on the Program
                    697: with the Program (or with a work based on the Program) on a volume of
                    698: a storage or distribution medium does not bring the other work under
                    699: the scope of this License.
                    700: 
                    701: @item
                    702: You may copy and distribute the Program (or a work based on it,
                    703: under Section 2) in object code or executable form under the terms of
                    704: Sections 1 and 2 above provided that you also do one of the following:
                    705: 
                    706: @enumerate a
                    707: @item
                    708: Accompany it with the complete corresponding machine-readable
                    709: source code, which must be distributed under the terms of Sections
                    710: 1 and 2 above on a medium customarily used for software interchange; or,
                    711: 
                    712: @item
                    713: Accompany it with a written offer, valid for at least three
                    714: years, to give any third party, for a charge no more than your
                    715: cost of physically performing source distribution, a complete
                    716: machine-readable copy of the corresponding source code, to be
                    717: distributed under the terms of Sections 1 and 2 above on a medium
                    718: customarily used for software interchange; or,
                    719: 
                    720: @item
                    721: Accompany it with the information you received as to the offer
                    722: to distribute corresponding source code.  (This alternative is
                    723: allowed only for noncommercial distribution and only if you
                    724: received the program in object code or executable form with such
                    725: an offer, in accord with Subsection b above.)
                    726: @end enumerate
                    727: 
                    728: The source code for a work means the preferred form of the work for
                    729: making modifications to it.  For an executable work, complete source
                    730: code means all the source code for all modules it contains, plus any
                    731: associated interface definition files, plus the scripts used to
                    732: control compilation and installation of the executable.  However, as a
                    733: special exception, the source code distributed need not include
                    734: anything that is normally distributed (in either source or binary
                    735: form) with the major components (compiler, kernel, and so on) of the
                    736: operating system on which the executable runs, unless that component
                    737: itself accompanies the executable.
                    738: 
                    739: If distribution of executable or object code is made by offering
                    740: access to copy from a designated place, then offering equivalent
                    741: access to copy the source code from the same place counts as
                    742: distribution of the source code, even though third parties are not
                    743: compelled to copy the source along with the object code.
                    744: 
                    745: @item
                    746: You may not copy, modify, sublicense, or distribute the Program
                    747: except as expressly provided under this License.  Any attempt
                    748: otherwise to copy, modify, sublicense or distribute the Program is
                    749: void, and will automatically terminate your rights under this License.
                    750: However, parties who have received copies, or rights, from you under
                    751: this License will not have their licenses terminated so long as such
                    752: parties remain in full compliance.
                    753: 
                    754: @item
                    755: You are not required to accept this License, since you have not
                    756: signed it.  However, nothing else grants you permission to modify or
                    757: distribute the Program or its derivative works.  These actions are
                    758: prohibited by law if you do not accept this License.  Therefore, by
                    759: modifying or distributing the Program (or any work based on the
                    760: Program), you indicate your acceptance of this License to do so, and
                    761: all its terms and conditions for copying, distributing or modifying
                    762: the Program or works based on it.
                    763: 
                    764: @item
                    765: Each time you redistribute the Program (or any work based on the
                    766: Program), the recipient automatically receives a license from the
                    767: original licensor to copy, distribute or modify the Program subject to
                    768: these terms and conditions.  You may not impose any further
                    769: restrictions on the recipients' exercise of the rights granted herein.
                    770: You are not responsible for enforcing compliance by third parties to
                    771: this License.
                    772: 
                    773: @item
                    774: If, as a consequence of a court judgment or allegation of patent
                    775: infringement or for any other reason (not limited to patent issues),
                    776: conditions are imposed on you (whether by court order, agreement or
                    777: otherwise) that contradict the conditions of this License, they do not
                    778: excuse you from the conditions of this License.  If you cannot
                    779: distribute so as to satisfy simultaneously your obligations under this
                    780: License and any other pertinent obligations, then as a consequence you
                    781: may not distribute the Program at all.  For example, if a patent
                    782: license would not permit royalty-free redistribution of the Program by
                    783: all those who receive copies directly or indirectly through you, then
                    784: the only way you could satisfy both it and this License would be to
                    785: refrain entirely from distribution of the Program.
                    786: 
                    787: If any portion of this section is held invalid or unenforceable under
                    788: any particular circumstance, the balance of the section is intended to
                    789: apply and the section as a whole is intended to apply in other
                    790: circumstances.
                    791: 
                    792: It is not the purpose of this section to induce you to infringe any
                    793: patents or other property right claims or to contest validity of any
                    794: such claims; this section has the sole purpose of protecting the
                    795: integrity of the free software distribution system, which is
                    796: implemented by public license practices.  Many people have made
                    797: generous contributions to the wide range of software distributed
                    798: through that system in reliance on consistent application of that
                    799: system; it is up to the author/donor to decide if he or she is willing
                    800: to distribute software through any other system and a licensee cannot
                    801: impose that choice.
                    802: 
                    803: This section is intended to make thoroughly clear what is believed to
                    804: be a consequence of the rest of this License.
                    805: 
                    806: @item
                    807: If the distribution and/or use of the Program is restricted in
                    808: certain countries either by patents or by copyrighted interfaces, the
                    809: original copyright holder who places the Program under this License
                    810: may add an explicit geographical distribution limitation excluding
                    811: those countries, so that distribution is permitted only in or among
                    812: countries not thus excluded.  In such case, this License incorporates
                    813: the limitation as if written in the body of this License.
                    814: 
                    815: @item
                    816: The Free Software Foundation may publish revised and/or new versions
                    817: of the General Public License from time to time.  Such new versions will
                    818: be similar in spirit to the present version, but may differ in detail to
                    819: address new problems or concerns.
                    820: 
                    821: Each version is given a distinguishing version number.  If the Program
                    822: specifies a version number of this License which applies to it and ``any
                    823: later version'', you have the option of following the terms and conditions
                    824: either of that version or of any later version published by the Free
                    825: Software Foundation.  If the Program does not specify a version number of
                    826: this License, you may choose any version ever published by the Free Software
                    827: Foundation.
                    828: 
                    829: @item
                    830: If you wish to incorporate parts of the Program into other free
                    831: programs whose distribution conditions are different, write to the author
                    832: to ask for permission.  For software which is copyrighted by the Free
                    833: Software Foundation, write to the Free Software Foundation; we sometimes
                    834: make exceptions for this.  Our decision will be guided by the two goals
                    835: of preserving the free status of all derivatives of our free software and
                    836: of promoting the sharing and reuse of software generally.
                    837: 
                    838: @iftex
                    839: @heading NO WARRANTY
                    840: @end iftex
1.49      anton     841: @ifnottex
1.1       anton     842: @center NO WARRANTY
1.49      anton     843: @end ifnottex
1.1       anton     844: 
                    845: @item
                    846: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
                    847: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
                    848: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
                    849: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
                    850: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
                    851: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
                    852: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
                    853: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
                    854: REPAIR OR CORRECTION.
                    855: 
                    856: @item
                    857: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
                    858: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
                    859: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
                    860: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
                    861: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
                    862: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
                    863: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
                    864: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
                    865: POSSIBILITY OF SUCH DAMAGES.
                    866: @end enumerate
                    867: 
                    868: @iftex
                    869: @heading END OF TERMS AND CONDITIONS
                    870: @end iftex
1.49      anton     871: @ifnottex
1.1       anton     872: @center END OF TERMS AND CONDITIONS
1.49      anton     873: @end ifnottex
1.1       anton     874: 
                    875: @page
                    876: @unnumberedsec How to Apply These Terms to Your New Programs
                    877: 
                    878:   If you develop a new program, and you want it to be of the greatest
                    879: possible use to the public, the best way to achieve this is to make it
                    880: free software which everyone can redistribute and change under these terms.
                    881: 
                    882:   To do so, attach the following notices to the program.  It is safest
                    883: to attach them to the start of each source file to most effectively
                    884: convey the exclusion of warranty; and each file should have at least
                    885: the ``copyright'' line and a pointer to where the full notice is found.
                    886: 
                    887: @smallexample
                    888: @var{one line to give the program's name and a brief idea of what it does.}
                    889: Copyright (C) 19@var{yy}  @var{name of author}
                    890: 
                    891: This program is free software; you can redistribute it and/or modify 
                    892: it under the terms of the GNU General Public License as published by 
                    893: the Free Software Foundation; either version 2 of the License, or 
                    894: (at your option) any later version.
                    895: 
                    896: This program is distributed in the hope that it will be useful,
                    897: but WITHOUT ANY WARRANTY; without even the implied warranty of
                    898: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                    899: GNU General Public License for more details.
                    900: 
                    901: You should have received a copy of the GNU General Public License
                    902: along with this program; if not, write to the Free Software
                    903: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
                    904: @end smallexample
                    905: 
                    906: Also add information on how to contact you by electronic and paper mail.
                    907: 
                    908: If the program is interactive, make it output a short notice like this
                    909: when it starts in an interactive mode:
                    910: 
                    911: @smallexample
                    912: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
                    913: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
                    914: type `show w'.  
                    915: This is free software, and you are welcome to redistribute it 
                    916: under certain conditions; type `show c' for details.
                    917: @end smallexample
                    918: 
                    919: The hypothetical commands @samp{show w} and @samp{show c} should show
                    920: the appropriate parts of the General Public License.  Of course, the
                    921: commands you use may be called something other than @samp{show w} and
                    922: @samp{show c}; they could even be mouse-clicks or menu items---whatever
                    923: suits your program.
                    924: 
                    925: You should also get your employer (if you work as a programmer) or your
                    926: school, if any, to sign a ``copyright disclaimer'' for the program, if
                    927: necessary.  Here is a sample; alter the names:
                    928: 
                    929: @smallexample
                    930: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
                    931: `Gnomovision' (which makes passes at compilers) written by James Hacker.
                    932: 
                    933: @var{signature of Ty Coon}, 1 April 1989
                    934: Ty Coon, President of Vice
                    935: @end smallexample
                    936: 
                    937: This General Public License does not permit incorporating your program into
                    938: proprietary programs.  If your program is a subroutine library, you may
                    939: consider it more useful to permit linking proprietary applications with the
                    940: library.  If this is what you want to do, use the GNU Library General
                    941: Public License instead of this License.
                    942: 
                    943: @iftex
                    944: @unnumbered Preface
                    945: @cindex Preface
1.21      crook     946: This manual documents Gforth. Some introductory material is provided for
                    947: readers who are unfamiliar with Forth or who are migrating to Gforth
                    948: from other Forth compilers. However, this manual is primarily a
                    949: reference manual.
1.1       anton     950: @end iftex
                    951: 
1.28      crook     952: @comment TODO much more blurb here.
1.26      crook     953: 
                    954: @c ******************************************************************
1.29      crook     955: @node Goals, Gforth Environment, License, Top
1.26      crook     956: @comment node-name,     next,           previous, up
                    957: @chapter Goals of Gforth
                    958: @cindex goals of the Gforth project
                    959: The goal of the Gforth Project is to develop a standard model for
                    960: ANS Forth. This can be split into several subgoals:
                    961: 
                    962: @itemize @bullet
                    963: @item
                    964: Gforth should conform to the ANS Forth Standard.
                    965: @item
                    966: It should be a model, i.e. it should define all the
                    967: implementation-dependent things.
                    968: @item
                    969: It should become standard, i.e. widely accepted and used. This goal
                    970: is the most difficult one.
                    971: @end itemize
                    972: 
                    973: To achieve these goals Gforth should be
                    974: @itemize @bullet
                    975: @item
                    976: Similar to previous models (fig-Forth, F83)
                    977: @item
                    978: Powerful. It should provide for all the things that are considered
                    979: necessary today and even some that are not yet considered necessary.
                    980: @item
                    981: Efficient. It should not get the reputation of being exceptionally
                    982: slow.
                    983: @item
                    984: Free.
                    985: @item
                    986: Available on many machines/easy to port.
                    987: @end itemize
                    988: 
                    989: Have we achieved these goals? Gforth conforms to the ANS Forth
                    990: standard. It may be considered a model, but we have not yet documented
                    991: which parts of the model are stable and which parts we are likely to
                    992: change. It certainly has not yet become a de facto standard, but it
                    993: appears to be quite popular. It has some similarities to and some
                    994: differences from previous models. It has some powerful features, but not
                    995: yet everything that we envisioned. We certainly have achieved our
                    996: execution speed goals (@pxref{Performance}).  It is free and available
                    997: on many machines.
                    998: 
                    999: @menu
                   1000: * Gforth Extensions Sinful?::
                   1001: @end menu
                   1002: 
1.48      anton    1003: @node Gforth Extensions Sinful?,  , Goals, Goals
1.26      crook    1004: @comment node-name,     next,           previous, up
                   1005: @section Is it a Sin to use Gforth Extensions?
                   1006: @cindex Gforth extensions
                   1007: 
                   1008: If you've been paying attention, you will have realised that there is an
                   1009: ANS (American National Standard) for Forth. As you read through the rest
1.29      crook    1010: of this manual, you will see documentation for @i{Standard} words, and
                   1011: documentation for some appealing Gforth @i{extensions}. You might ask
                   1012: yourself the question: @i{``Given that there is a standard, would I be
1.45      crook    1013: committing a sin if I use (non-Standard) Gforth extensions?''}
1.26      crook    1014: 
                   1015: The answer to that question is somewhat pragmatic and somewhat
                   1016: philosophical. Consider these points:
                   1017: 
                   1018: @itemize @bullet
                   1019: @item
                   1020: A number of the Gforth extensions can be implemented in ANS Forth using
                   1021: files provided in the @file{compat/} directory. These are mentioned in
                   1022: the text in passing.
                   1023: @item
                   1024: Forth has a rich historical precedent for programmers taking advantage
                   1025: of implementation-dependent features of their tools (for example,
                   1026: relying on a knowledge of the dictionary structure). Sometimes these
                   1027: techniques are necessary to extract every last bit of performance from
                   1028: the hardware, sometimes they are just a programming shorthand.
                   1029: @item
                   1030: The best way to break the rules is to know what the rules are. To learn
                   1031: the rules, there is no substitute for studying the text of the Standard
                   1032: itself. In particular, Appendix A of the Standard (@var{Rationale})
                   1033: provides a valuable insight into the thought processes of the technical
                   1034: committee.
                   1035: @item
                   1036: The best reason to break a rule is because you have to; because it's
                   1037: more productive to do that, because it makes your code run fast enough
                   1038: or because you can see no Standard way to achieve what you want to
                   1039: achieve.
                   1040: @end itemize
                   1041: 
                   1042: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
                   1043: analyse your program and determine what non-Standard definitions it
                   1044: relies upon.
                   1045: 
1.29      crook    1046: 
1.26      crook    1047: @c ******************************************************************
1.48      anton    1048: @node Gforth Environment, Tutorial, Goals, Top
1.29      crook    1049: @chapter Gforth Environment
                   1050: @cindex Gforth environment
1.21      crook    1051: 
1.45      crook    1052: Note: ultimately, the Gforth man page will be auto-generated from the
1.29      crook    1053: material in this chapter.
1.21      crook    1054: 
                   1055: @menu
1.29      crook    1056: * Invoking Gforth::             Getting in
                   1057: * Leaving Gforth::              Getting out
                   1058: * Command-line editing::        
1.48      anton    1059: * Upper and lower case::        
                   1060: * Environment variables::       that affect how Gforth starts up
1.29      crook    1061: * Gforth Files::                What gets installed and where
1.48      anton    1062: * Startup speed::               When 35ms is not fast enough ...
1.21      crook    1063: @end menu
                   1064: 
1.49      anton    1065: For related information about the creation of images see @ref{Image Files}.
1.29      crook    1066: 
1.21      crook    1067: @comment ----------------------------------------------
1.48      anton    1068: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29      crook    1069: @section Invoking Gforth
                   1070: @cindex invoking Gforth
                   1071: @cindex running Gforth
                   1072: @cindex command-line options
                   1073: @cindex options on the command line
                   1074: @cindex flags on the command line
1.21      crook    1075: 
1.30      anton    1076: Gforth is made up of two parts; an executable ``engine'' (named
                   1077: @file{gforth} or @file{gforth-fast}) and an image file. To start it, you
                   1078: will usually just say @code{gforth} -- this automatically loads the
                   1079: default image file @file{gforth.fi}. In many other cases the default
                   1080: Gforth image will be invoked like this:
1.21      crook    1081: @example
1.30      anton    1082: gforth [file | -e forth-code] ...
1.21      crook    1083: @end example
1.29      crook    1084: @noindent
                   1085: This interprets the contents of the files and the Forth code in the order they
                   1086: are given.
1.21      crook    1087: 
1.30      anton    1088: In addition to the @file{gforth} engine, there is also an engine called
                   1089: @file{gforth-fast}, which is faster, but gives less informative error
                   1090: messages (@pxref{Error messages}).
                   1091: 
1.29      crook    1092: In general, the command line looks like this:
1.21      crook    1093: 
                   1094: @example
1.30      anton    1095: gforth[-fast] [engine options] [image options]
1.21      crook    1096: @end example
                   1097: 
1.30      anton    1098: The engine options must come before the rest of the command
1.29      crook    1099: line. They are:
1.26      crook    1100: 
1.29      crook    1101: @table @code
                   1102: @cindex -i, command-line option
                   1103: @cindex --image-file, command-line option
                   1104: @item --image-file @i{file}
                   1105: @itemx -i @i{file}
                   1106: Loads the Forth image @i{file} instead of the default
                   1107: @file{gforth.fi} (@pxref{Image Files}).
1.21      crook    1108: 
1.39      anton    1109: @cindex --appl-image, command-line option
                   1110: @item --appl-image @i{file}
                   1111: Loads the image @i{file} and leaves all further command-line arguments
                   1112: to the image (instead of processing them as options).  This is useful
                   1113: for building executable application images on Unix, built with
                   1114: @code{gforthmi --application ...}.
                   1115: 
1.29      crook    1116: @cindex --path, command-line option
                   1117: @cindex -p, command-line option
                   1118: @item --path @i{path}
                   1119: @itemx -p @i{path}
                   1120: Uses @i{path} for searching the image file and Forth source code files
                   1121: instead of the default in the environment variable @code{GFORTHPATH} or
                   1122: the path specified at installation time (e.g.,
                   1123: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
                   1124: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21      crook    1125: 
1.29      crook    1126: @cindex --dictionary-size, command-line option
                   1127: @cindex -m, command-line option
                   1128: @cindex @i{size} parameters for command-line options
                   1129: @cindex size of the dictionary and the stacks
                   1130: @item --dictionary-size @i{size}
                   1131: @itemx -m @i{size}
                   1132: Allocate @i{size} space for the Forth dictionary space instead of
                   1133: using the default specified in the image (typically 256K). The
                   1134: @i{size} specification for this and subsequent options consists of
                   1135: an integer and a unit (e.g.,
                   1136: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
                   1137: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
                   1138: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
                   1139: @code{e} is used.
1.21      crook    1140: 
1.29      crook    1141: @cindex --data-stack-size, command-line option
                   1142: @cindex -d, command-line option
                   1143: @item --data-stack-size @i{size}
                   1144: @itemx -d @i{size}
                   1145: Allocate @i{size} space for the data stack instead of using the
                   1146: default specified in the image (typically 16K).
1.21      crook    1147: 
1.29      crook    1148: @cindex --return-stack-size, command-line option
                   1149: @cindex -r, command-line option
                   1150: @item --return-stack-size @i{size}
                   1151: @itemx -r @i{size}
                   1152: Allocate @i{size} space for the return stack instead of using the
                   1153: default specified in the image (typically 15K).
1.21      crook    1154: 
1.29      crook    1155: @cindex --fp-stack-size, command-line option
                   1156: @cindex -f, command-line option
                   1157: @item --fp-stack-size @i{size}
                   1158: @itemx -f @i{size}
                   1159: Allocate @i{size} space for the floating point stack instead of
                   1160: using the default specified in the image (typically 15.5K). In this case
                   1161: the unit specifier @code{e} refers to floating point numbers.
1.21      crook    1162: 
1.48      anton    1163: @cindex --locals-stack-size, command-line option
                   1164: @cindex -l, command-line option
                   1165: @item --locals-stack-size @i{size}
                   1166: @itemx -l @i{size}
                   1167: Allocate @i{size} space for the locals stack instead of using the
                   1168: default specified in the image (typically 14.5K).
                   1169: 
                   1170: @cindex -h, command-line option
                   1171: @cindex --help, command-line option
                   1172: @item --help
                   1173: @itemx -h
                   1174: Print a message about the command-line options
                   1175: 
                   1176: @cindex -v, command-line option
                   1177: @cindex --version, command-line option
                   1178: @item --version
                   1179: @itemx -v
                   1180: Print version and exit
                   1181: 
                   1182: @cindex --debug, command-line option
                   1183: @item --debug
                   1184: Print some information useful for debugging on startup.
                   1185: 
                   1186: @cindex --offset-image, command-line option
                   1187: @item --offset-image
                   1188: Start the dictionary at a slightly different position than would be used
                   1189: otherwise (useful for creating data-relocatable images,
                   1190: @pxref{Data-Relocatable Image Files}).
                   1191: 
                   1192: @cindex --no-offset-im, command-line option
                   1193: @item --no-offset-im
                   1194: Start the dictionary at the normal position.
                   1195: 
                   1196: @cindex --clear-dictionary, command-line option
                   1197: @item --clear-dictionary
                   1198: Initialize all bytes in the dictionary to 0 before loading the image
                   1199: (@pxref{Data-Relocatable Image Files}).
                   1200: 
                   1201: @cindex --die-on-signal, command-line-option
                   1202: @item --die-on-signal
                   1203: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
                   1204: or the segmentation violation SIGSEGV) by translating it into a Forth
                   1205: @code{THROW}. With this option, Gforth exits if it receives such a
                   1206: signal. This option is useful when the engine and/or the image might be
                   1207: severely broken (such that it causes another signal before recovering
                   1208: from the first); this option avoids endless loops in such cases.
                   1209: @end table
                   1210: 
                   1211: @cindex loading files at startup
                   1212: @cindex executing code on startup
                   1213: @cindex batch processing with Gforth
                   1214: As explained above, the image-specific command-line arguments for the
                   1215: default image @file{gforth.fi} consist of a sequence of filenames and
                   1216: @code{-e @var{forth-code}} options that are interpreted in the sequence
                   1217: in which they are given. The @code{-e @var{forth-code}} or
                   1218: @code{--evaluate @var{forth-code}} option evaluates the Forth
                   1219: code. This option takes only one argument; if you want to evaluate more
                   1220: Forth words, you have to quote them or use @code{-e} several times. To exit
                   1221: after processing the command line (instead of entering interactive mode)
                   1222: append @code{-e bye} to the command line.
                   1223: 
                   1224: @cindex versions, invoking other versions of Gforth
                   1225: If you have several versions of Gforth installed, @code{gforth} will
                   1226: invoke the version that was installed last. @code{gforth-@i{version}}
                   1227: invokes a specific version. If your environment contains the variable
                   1228: @code{GFORTHPATH}, you may want to override it by using the
                   1229: @code{--path} option.
                   1230: 
                   1231: Not yet implemented:
                   1232: On startup the system first executes the system initialization file
                   1233: (unless the option @code{--no-init-file} is given; note that the system
                   1234: resulting from using this option may not be ANS Forth conformant). Then
                   1235: the user initialization file @file{.gforth.fs} is executed, unless the
                   1236: option @code{--no-rc} is given; this file is first searched in @file{.},
                   1237: then in @file{~}, then in the normal path (see above).
                   1238: 
                   1239: 
                   1240: 
                   1241: @comment ----------------------------------------------
                   1242: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
                   1243: @section Leaving Gforth
                   1244: @cindex Gforth - leaving
                   1245: @cindex leaving Gforth
                   1246: 
                   1247: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
                   1248: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
                   1249: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49      anton    1250: data are discarded.  For ways of saving the state of the system before
                   1251: leaving Gforth see @ref{Image Files}.
1.48      anton    1252: 
                   1253: doc-bye
                   1254: 
                   1255: 
                   1256: @comment ----------------------------------------------
                   1257: @node Command-line editing, Upper and lower case, Leaving Gforth, Gforth Environment
                   1258: @section Command-line editing
                   1259: @cindex command-line editing
                   1260: 
                   1261: Gforth maintains a history file that records every line that you type to
                   1262: the text interpreter. This file is preserved between sessions, and is
                   1263: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
                   1264: repeatedly you can recall successively older commands from this (or
                   1265: previous) session(s). The full list of command-line editing facilities is:
                   1266: 
                   1267: @itemize @bullet
                   1268: @item
                   1269: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
                   1270: commands from the history buffer.
                   1271: @item
                   1272: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
                   1273: from the history buffer.
                   1274: @item
                   1275: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
                   1276: @item
                   1277: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
                   1278: @item
                   1279: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
                   1280: closing up the line.
                   1281: @item
                   1282: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
                   1283: @item
                   1284: @kbd{Ctrl-a} to move the cursor to the start of the line.
                   1285: @item
                   1286: @kbd{Ctrl-e} to move the cursor to the end of the line.
                   1287: @item
                   1288: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
                   1289: line.
                   1290: @item
                   1291: @key{TAB} to step through all possible full-word completions of the word
                   1292: currently being typed.
                   1293: @item
                   1294: @kbd{Ctrl-d} at the start of the line to terminate Gforth (gracefully,
                   1295: using @code{bye}).
                   1296: @end itemize
                   1297: 
                   1298: When editing, displayable characters are inserted to the left of the
                   1299: cursor position; the line is always in ``insert'' (as opposed to
                   1300: ``overstrike'') mode.
                   1301: 
                   1302: @cindex history file
                   1303: @cindex @file{.gforth-history}
                   1304: On Unix systems, the history file is @file{~/.gforth-history} by
                   1305: default@footnote{i.e. it is stored in the user's home directory.}. You
                   1306: can find out the name and location of your history file using:
                   1307: 
                   1308: @example 
                   1309: history-file type \ Unix-class systems
                   1310: 
                   1311: history-file type \ Other systems
                   1312: history-dir  type
                   1313: @end example
                   1314: 
                   1315: If you enter long definitions by hand, you can use a text editor to
                   1316: paste them out of the history file into a Forth source file for reuse at
                   1317: a later time.
                   1318: 
                   1319: Gforth never trims the size of the history file, so you should do this
                   1320: periodically, if necessary.
                   1321: 
                   1322: @comment this is all defined in history.fs
                   1323: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
                   1324: @comment chosen?
                   1325: 
                   1326: 
                   1327: 
                   1328: @comment ----------------------------------------------
                   1329: @node Upper and lower case, Environment variables, Command-line editing, Gforth Environment
                   1330: @section Upper and lower case
                   1331: @cindex case-sensitivity
                   1332: @cindex upper and lower case
                   1333: 
                   1334: Gforth is case-insensitive; you can enter definitions and invoke
                   1335: Standard words using upper, lower or mixed case (however,
                   1336: @pxref{core-idef, Implementation-defined options, Implementation-defined
                   1337: options}).
                   1338: 
                   1339: ANS Forth only @i{requires} implementations to recognise Standard words
                   1340: when they are typed entirely in upper case. Therefore, a Standard
                   1341: program must use upper case for all Standard words. You can use whatever
                   1342: case you like for words that you define, but in a standard program you
                   1343: have to use the words in the same case that you defined them.
                   1344: 
                   1345: Gforth supports case sensitivity through @code{table}s (case-sensitive
                   1346: wordlists, @pxref{Word Lists}).
                   1347: 
                   1348: Two people have asked how to convert Gforth to case sensitivity; while
                   1349: we think this is a bad idea, you can change all wordlists into tables
                   1350: like this:
                   1351: 
                   1352: @example
                   1353: ' table-find forth-wordlist wordlist-map @ !
                   1354: @end example
                   1355: 
                   1356: Note that you now have to type the predefined words in the same case
                   1357: that we defined them, which are varying.  You may want to convert them
                   1358: to your favourite case before doing this operation (I won't explain how,
                   1359: because if you are even contemplating to do this, you'd better have
                   1360: enough knowledge of Forth systems to know this already).
                   1361: 
                   1362: @comment ----------------------------------------------
                   1363: @node Environment variables, Gforth Files, Upper and lower case, Gforth Environment
                   1364: @section Environment variables
                   1365: @cindex environment variables
                   1366: 
                   1367: Gforth uses these environment variables:
                   1368: 
                   1369: @itemize @bullet
                   1370: @item
                   1371: @cindex @code{GFORTHHIST} -- environment variable
                   1372: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
                   1373: open/create the history file, @file{.gforth-history}. Default:
                   1374: @code{$HOME}.
                   1375: 
                   1376: @item
                   1377: @cindex @code{GFORTHPATH} -- environment variable
                   1378: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
                   1379: for Forth source-code files.
                   1380: 
                   1381: @item
                   1382: @cindex @code{GFORTH} -- environment variable
1.49      anton    1383: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton    1384: 
                   1385: @item
                   1386: @cindex @code{GFORTHD} -- environment variable
                   1387: @code{GFORTHD} -- used by @file{gforthmi} @xref{gforthmi}.
                   1388: 
                   1389: @item
                   1390: @cindex @code{TMP}, @code{TEMP} - environment variable
                   1391: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
                   1392: location for the history file.
                   1393: @end itemize
                   1394: 
                   1395: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
                   1396: @comment mentioning these.
                   1397: 
                   1398: All the Gforth environment variables default to sensible values if they
                   1399: are not set.
                   1400: 
                   1401: 
                   1402: @comment ----------------------------------------------
                   1403: @node Gforth Files, Startup speed, Environment variables, Gforth Environment
                   1404: @section Gforth files
                   1405: @cindex Gforth files
                   1406: 
                   1407: When you install Gforth on a Unix system, it installs files in these
                   1408: locations by default:
                   1409: 
                   1410: @itemize @bullet
                   1411: @item
                   1412: @file{/usr/local/bin/gforth}
                   1413: @item
                   1414: @file{/usr/local/bin/gforthmi}
                   1415: @item
                   1416: @file{/usr/local/man/man1/gforth.1} - man page.
                   1417: @item
                   1418: @file{/usr/local/info} - the Info version of this manual.
                   1419: @item
                   1420: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
                   1421: @item
                   1422: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
                   1423: @item
                   1424: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
                   1425: @item
                   1426: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
                   1427: @end itemize
                   1428: 
                   1429: You can select different places for installation by using
                   1430: @code{configure} options (listed with @code{configure --help}).
                   1431: 
                   1432: @comment ----------------------------------------------
                   1433: @node Startup speed,  , Gforth Files, Gforth Environment
                   1434: @section Startup speed
                   1435: @cindex Startup speed
                   1436: @cindex speed, startup
                   1437: 
                   1438: If Gforth is used for CGI scripts or in shell scripts, its startup
                   1439: speed may become a problem.  On a 300MHz 21064a under Linux-2.2.13 with
                   1440: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
                   1441: system time.
                   1442: 
                   1443: If startup speed is a problem, you may consider the following ways to
                   1444: improve it; or you may consider ways to reduce the number of startups
                   1445: (e.g., Fast-CGI).
                   1446: 
                   1447: The first step to improve startup speed is to statically link Gforth, by
                   1448: building it with @code{XLDFLAGS=-static}.  This requires more memory for
                   1449: the code and will therefore slow down the first invocation, but
                   1450: subsequent invocations avoid the dynamic linking overhead.  Another
                   1451: disadvantage is that Gforth won't profit from library upgrades.  As a
                   1452: result, @code{gforth-static -e bye} takes about 17.1ms user and
                   1453: 8.2ms system time.
                   1454: 
                   1455: The next step to improve startup speed is to use a non-relocatable image
                   1456: @ref{Non-Relocatable Image Files}.  You can create this image with
                   1457: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
                   1458: @code{gforth -i gforthnr.fi ...}.  This avoids the relocation overhead
                   1459: and a part of the copy-on-write overhead.  The disadvantage is that the
                   1460: nonrelocatable image does not work if the OS gives Gforth a different
                   1461: address for the dictionary, for whatever reason; so you better provide a
                   1462: fallback on a relocatable image.  @code{gforth-static -i gforthnr.fi -e
                   1463: bye} takes about 15.3ms user and 7.5ms system time.
                   1464: 
                   1465: The final step is to disable dictionary hashing in Gforth.  Gforth
                   1466: builds the hash table on startup, which takes much of the startup
                   1467: overhead. You can do this by commenting out the @code{include hash.fs}
                   1468: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
                   1469: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
                   1470: The disadvantages are that functionality like @code{table} and
                   1471: @code{ekey} is missing and that text interpretation (e.g., compiling)
                   1472: now takes much longer. So, you should only use this method if there is
                   1473: no significant text interpretation to perform (the script should be
                   1474: compiled into the image, among other things).  @code{gforth-static -i
                   1475: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
                   1476: 
                   1477: @c ******************************************************************
                   1478: @node Tutorial, Introduction, Gforth Environment, Top
                   1479: @chapter Forth Tutorial
                   1480: @cindex Tutorial
                   1481: @cindex Forth Tutorial
                   1482: 
                   1483: This tutorial can be used with any ANS-compliant Forth; any places that
                   1484: mention features specific to Gforth are marked as such and you can skip
                   1485: them, if you work with another Forth.  This tutorial does not explain
                   1486: all features of Forth, just enough to get you started and give you some
                   1487: ideas about the facilities available in Forth.  Read the rest of the
                   1488: manual and the standard when you are through this.
                   1489: 
                   1490: The intended way to use this tutorial is that you work through it while
                   1491: sitting in front of the console, take a look at the examples and predict
                   1492: what they will do, then try them out; if the outcome is not as expected,
                   1493: find out why (e.g., by trying out variations of the example), so you
                   1494: understand what's going on.  There are also some assignments that you
                   1495: should solve.
                   1496: 
                   1497: This tutorial assumes that you have programmed before and know what,
                   1498: e.g., a loop is.
                   1499: 
                   1500: @c !! explain compat library
                   1501: 
                   1502: @menu
                   1503: * Starting Gforth Tutorial::    
                   1504: * Syntax Tutorial::             
                   1505: * Crash Course Tutorial::       
                   1506: * Stack Tutorial::              
                   1507: * Arithmetics Tutorial::        
                   1508: * Stack Manipulation Tutorial::  
                   1509: * Using files for Forth code Tutorial::  
                   1510: * Comments Tutorial::           
                   1511: * Colon Definitions Tutorial::  
                   1512: * Decompilation Tutorial::      
                   1513: * Stack-Effect Comments Tutorial::  
                   1514: * Types Tutorial::              
                   1515: * Factoring Tutorial::          
                   1516: * Designing the stack effect Tutorial::  
                   1517: * Local Variables Tutorial::    
                   1518: * Conditional execution Tutorial::  
                   1519: * Flags and Comparisons Tutorial::  
                   1520: * General Loops Tutorial::      
                   1521: * Counted loops Tutorial::      
                   1522: * Recursion Tutorial::          
                   1523: * Leaving definitions or loops Tutorial::  
                   1524: * Return Stack Tutorial::       
                   1525: * Memory Tutorial::             
                   1526: * Characters and Strings Tutorial::  
                   1527: * Alignment Tutorial::          
                   1528: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                   1529: * Execution Tokens Tutorial::   
                   1530: * Exceptions Tutorial::         
                   1531: * Defining Words Tutorial::     
                   1532: * Arrays and Records Tutorial::  
                   1533: * POSTPONE Tutorial::           
                   1534: * Literal Tutorial::            
                   1535: * Advanced macros Tutorial::    
                   1536: * Compilation Tokens Tutorial::  
                   1537: * Wordlists and Search Order Tutorial::  
                   1538: @end menu
                   1539: 
                   1540: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
                   1541: @section Starting Gforth
                   1542: 
                   1543: You can start Gforth by typing its name:
                   1544: 
                   1545: @example
                   1546: gforth
                   1547: @end example
                   1548: 
                   1549: That puts you into interactive mode; you can leave Gforth by typing
                   1550: @code{bye}.  While in Gforth, you can edit the command line and access
                   1551: the command line history with cursor keys, similar to bash.
                   1552: 
                   1553: 
                   1554: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
                   1555: @section Syntax
                   1556: 
                   1557: A @dfn{word} is a sequence of arbitrary characters (expcept white
                   1558: space).  Words are separated by white space.  E.g., each of the
                   1559: following lines contains exactly one word:
                   1560: 
                   1561: @example
                   1562: word
                   1563: !@@#$%^&*()
                   1564: 1234567890
                   1565: 5!a
                   1566: @end example
                   1567: 
                   1568: A frequent beginner's error is to leave away necessary white space,
                   1569: resulting in an error like @samp{Undefined word}; so if you see such an
                   1570: error, check if you have put spaces wherever necessary.
                   1571: 
                   1572: @example
                   1573: ." hello, world" \ correct
                   1574: ."hello, world"  \ gives an "Undefined word" error
                   1575: @end example
                   1576: 
                   1577: Gforth and most other Forth systems ignores differences in case (it is
                   1578: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
                   1579: your system is case-sensitive, you may have to type all the examples
                   1580: given here in upper case.
                   1581: 
                   1582: 
                   1583: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
                   1584: @section Crash Course
                   1585: 
                   1586: Type
                   1587: 
                   1588: @example
                   1589: 0 0 !
                   1590: here execute
                   1591: ' catch >body 20 erase abort
                   1592: ' (quit) >body 20 erase
                   1593: @end example
                   1594: 
                   1595: The last two examples are guaranteed to destroy parts of Gforth (and
                   1596: most other systems), so you better leave Gforth afterwards (if it has
                   1597: not finished by itself).  On some systems you may have to kill gforth
                   1598: from outside (e.g., in Unix with @code{kill}).
                   1599: 
                   1600: Now that you know how to produce crashes (and that there's not much to
                   1601: them), let's learn how to produce meaningful programs.
                   1602: 
                   1603: 
                   1604: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
                   1605: @section Stack
                   1606: 
                   1607: The most obvious feature of Forth is the stack.  When you type in a
                   1608: number, it is pushed on the stack.  You can display the content of the
                   1609: stack with @code{.s}.
                   1610: 
                   1611: @example
                   1612: 1 2 .s
                   1613: 3 .s
                   1614: @end example
                   1615: 
                   1616: @code{.s} displays the top-of-stack to the right, i.e., the numbers
                   1617: appear in @code{.s} output as they appeared in the input.
                   1618: 
                   1619: You can print the top of stack element with @code{.}.
                   1620: 
                   1621: @example
                   1622: 1 2 3 . . .
                   1623: @end example
                   1624: 
                   1625: In general, words consume their stack arguments (@code{.s} is an
                   1626: exception).
                   1627: 
                   1628: @assignment
                   1629: What does the stack contain after @code{5 6 7 .}?
                   1630: @endassignment
                   1631: 
                   1632: 
                   1633: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
                   1634: @section Arithmetics
                   1635: 
                   1636: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
                   1637: operate on the top two stack items:
                   1638: 
                   1639: @example
                   1640: 2 2 + .
                   1641: 2 1 - .
                   1642: 7 3 mod .
                   1643: @end example
                   1644: 
                   1645: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
                   1646: as in the corresponding infix expression (this is generally the case in
                   1647: Forth).
                   1648: 
                   1649: Parentheses are superfluous (and not available), because the order of
                   1650: the words unambiguously determines the order of evaluation and the
                   1651: operands:
                   1652: 
                   1653: @example
                   1654: 3 4 + 5 * .
                   1655: 3 4 5 * + .
                   1656: @end example
                   1657: 
                   1658: @assignment
                   1659: What are the infix expressions corresponding to the Forth code above?
                   1660: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
                   1661: known as Postfix or RPN (Reverse Polish Notation).}.
                   1662: @endassignment
                   1663: 
                   1664: To change the sign, use @code{negate}:
                   1665: 
                   1666: @example
                   1667: 2 negate .
                   1668: @end example
                   1669: 
                   1670: @assignment
                   1671: Convert -(-3)*4-5 to Forth.
                   1672: @endassignment
                   1673: 
                   1674: @code{/mod} performs both @code{/} and @code{mod}.
                   1675: 
                   1676: @example
                   1677: 7 3 /mod . .
                   1678: @end example
                   1679: 
                   1680: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
                   1681: @section Stack Manipulation
                   1682: 
                   1683: Stack manipulation words rearrange the data on the stack.
                   1684: 
                   1685: @example
                   1686: 1 .s drop .s
                   1687: 1 .s dup .s drop drop .s
                   1688: 1 2 .s over .s drop drop drop
                   1689: 1 2 .s swap .s drop drop
                   1690: 1 2 3 .s rot .s drop drop drop
                   1691: @end example
                   1692: 
                   1693: These are the most important stack manipulation words.  There are also
                   1694: variants that manipulate twice as many stack items:
                   1695: 
                   1696: @example
                   1697: 1 2 3 4 .s 2swap .s 2drop 2drop
                   1698: @end example
                   1699: 
                   1700: Two more stack manipulation words are:
                   1701: 
                   1702: @example
                   1703: 1 2 .s nip .s drop
                   1704: 1 2 .s tuck .s 2drop drop
                   1705: @end example
                   1706: 
                   1707: @assignment
                   1708: Replace @code{nip} and @code{tuck} with combinations of other stack
                   1709: manipulation words.
                   1710: 
                   1711: @example
                   1712: Given:          How do you get:
                   1713: 1 2 3           3 2 1           
                   1714: 1 2 3           1 2 3 2                 
                   1715: 1 2 3           1 2 3 3                 
                   1716: 1 2 3           1 3 3           
                   1717: 1 2 3           2 1 3           
                   1718: 1 2 3 4         4 3 2 1         
                   1719: 1 2 3           1 2 3 1 2 3             
                   1720: 1 2 3 4         1 2 3 4 1 2             
                   1721: 1 2 3
                   1722: 1 2 3           1 2 3 4                 
                   1723: 1 2 3           1 3             
                   1724: @end example
                   1725: @endassignment
                   1726: 
                   1727: @example
                   1728: 5 dup * .
                   1729: @end example
                   1730: 
                   1731: @assignment
                   1732: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
                   1733: Write a piece of Forth code that expects two numbers on the stack
                   1734: (@var{a} and @var{b}, with @var{b} on top) and computes
                   1735: @code{(a-b)(a+1)}.
                   1736: @endassignment
                   1737: 
                   1738: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
                   1739: @section Using files for Forth code
                   1740: 
                   1741: While working at the Forth command line is convenient for one-line
                   1742: examples and short one-off code, you probably want to store your source
                   1743: code in files for convenient editing and persistence.  You can use your
                   1744: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
                   1745: Gforth}) to create @var{file} and use
                   1746: 
                   1747: @example
                   1748: s" @var{file}" included
                   1749: @end example
                   1750: 
                   1751: to load it into your Forth system.  The file name extension I use for
                   1752: Forth files is @samp{.fs}.
                   1753: 
                   1754: You can easily start Gforth with some files loaded like this:
                   1755: 
                   1756: @example
                   1757: gforth @var{file1} @var{file2}
                   1758: @end example
                   1759: 
                   1760: If an error occurs during loading these files, Gforth terminates,
                   1761: whereas an error during @code{INCLUDED} within Gforth usually gives you
                   1762: a Gforth command line.  Starting the Forth system every time gives you a
                   1763: clean start every time, without interference from the results of earlier
                   1764: tries.
                   1765: 
                   1766: I often put all the tests in a file, then load the code and run the
                   1767: tests with
                   1768: 
                   1769: @example
                   1770: gforth @var{code} @var{tests} -e bye
                   1771: @end example
                   1772: 
                   1773: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
                   1774: @code{-e bye} ensures that Gforth terminates afterwards so that I can
                   1775: restart this command without ado.
                   1776: 
                   1777: The advantage of this approach is that the tests can be repeated easily
                   1778: every time the program ist changed, making it easy to catch bugs
                   1779: introduced by the change.
                   1780: 
                   1781: 
                   1782: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
                   1783: @section Comments
                   1784: 
                   1785: @example
                   1786: \ That's a comment; it ends at the end of the line
                   1787: ( Another comment; it ends here: )  .s
                   1788: @end example
                   1789: 
                   1790: @code{\} and @code{(} are ordinary Forth words and therefore have to be
                   1791: separated with white space from the following text.
                   1792: 
                   1793: @example
                   1794: \This gives an "Undefined word" error
                   1795: @end example
                   1796: 
                   1797: The first @code{)} ends a comment started with @code{(}, so you cannot
                   1798: nest @code{(}-comments; and you cannot comment out text containing a
                   1799: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
                   1800: avoid @code{)} in word names.}.
                   1801: 
                   1802: I use @code{\}-comments for descriptive text and for commenting out code
                   1803: of one or more line; I use @code{(}-comments for describing the stack
                   1804: effect, the stack contents, or for commenting out sub-line pieces of
                   1805: code.
                   1806: 
                   1807: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
                   1808: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
                   1809: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
                   1810: with @kbd{M-q}.
                   1811: 
                   1812: 
                   1813: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
                   1814: @section Colon Definitions
                   1815: 
                   1816: are similar to procedures and functions in other programming languages.
                   1817: 
                   1818: @example
                   1819: : squared ( n -- n^2 )
                   1820:    dup * ;
                   1821: 5 squared .
                   1822: 7 squared .
                   1823: @end example
                   1824: 
                   1825: @code{:} starts the colon definition; its name is @code{squared}.  The
                   1826: following comment describes its stack effect.  The words @code{dup *}
                   1827: are not executed, but compiled into the definition.  @code{;} ends the
                   1828: colon definition.
                   1829: 
                   1830: The newly-defined word can be used like any other word, including using
                   1831: it in other definitions:
                   1832: 
                   1833: @example
                   1834: : cubed ( n -- n^3 )
                   1835:    dup squared * ;
                   1836: -5 cubed .
                   1837: : fourth-power ( n -- n^4 )
                   1838:    squared squared ;
                   1839: 3 fourth-power .
                   1840: @end example
                   1841: 
                   1842: @assignment
                   1843: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
                   1844: @code{/mod} in terms of other Forth words, and check if they work (hint:
                   1845: test your tests on the originals first).  Don't let the
                   1846: @samp{redefined}-Messages spook you, they are just warnings.
                   1847: @endassignment
                   1848: 
                   1849: 
                   1850: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
                   1851: @section Decompilation
                   1852: 
                   1853: You can decompile colon definitions with @code{see}:
                   1854: 
                   1855: @example
                   1856: see squared
                   1857: see cubed
                   1858: @end example
                   1859: 
                   1860: In Gforth @code{see} shows you a reconstruction of the source code from
                   1861: the executable code.  Informations that were present in the source, but
                   1862: not in the executable code, are lost (e.g., comments).
                   1863: 
                   1864: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
                   1865: @section Stack-Effect Comments
                   1866: 
                   1867: By convention the comment after the name of a definition describes the
                   1868: stack effect: The part in from of the @samp{--} describes the state of
                   1869: the stack before the execution of the definition, i.e., the parameters
                   1870: that are passed into the colon definition; the part behind the @samp{--}
                   1871: is the state of the stack after the execution of the definition, i.e.,
                   1872: the results of the definition.  The stack comment only shows the top
                   1873: stack items that the definition accesses and/or changes.
                   1874: 
                   1875: You should put a correct stack effect on every definition, even if it is
                   1876: just @code{( -- )}.  You should also add some descriptive comment to
                   1877: more complicated words (I usually do this in the lines following
                   1878: @code{:}).  If you don't do this, your code becomes unreadable (because
                   1879: you have to work through every definition before you can undertsand
                   1880: any).
                   1881: 
                   1882: @assignment
                   1883: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
                   1884: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
                   1885: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
                   1886: are done, you can compare your stack effects to this in this manual
                   1887: (@pxref{Word Index}).
                   1888: @endassignment
                   1889: 
                   1890: Sometimes programmers put comments at various places in colon
                   1891: definitions that describe the contents of the stack at that place (stack
                   1892: comments); i.e., they are like the first part of a stack-effect
                   1893: comment. E.g.,
                   1894: 
                   1895: @example
                   1896: : cubed ( n -- n^3 )
                   1897:    dup squared  ( n n^2 ) * ;
                   1898: @end example
                   1899: 
                   1900: In this case the stack comment is pretty superfluous, because the word
                   1901: is simple enough.  If you think it would be a good idea to add such a
                   1902: comment to increase readability, you should also consider factoring the
                   1903: word into several simpler words (@pxref{Factoring Tutorial,,
1.60    ! anton    1904: Factoring}), which typically eliminates the need for the stack comment;
1.48      anton    1905: however, if you decide not to refactor it, then having such a comment is
                   1906: better than not having it.
                   1907: 
                   1908: The names of the stack items in stack-effect and stack comments in the
                   1909: standard, in this manual, and in many programs specify the type through
                   1910: a type prefix, similar to Fortran and Hungarian notation.  The most
                   1911: frequent prefixes are:
                   1912: 
                   1913: @table @code
                   1914: @item n
                   1915: signed integer
                   1916: @item u
                   1917: unsigned integer
                   1918: @item c
                   1919: character
                   1920: @item f
                   1921: Boolean flags, i.e. @code{false} or @code{true}.
                   1922: @item a-addr,a-
                   1923: Cell-aligned address
                   1924: @item c-addr,c-
                   1925: Char-aligned address (note that a Char may have two bytes in Windows NT)
                   1926: @item xt
                   1927: Execution token, same size as Cell
                   1928: @item w,x
                   1929: Cell, can contain an integer or an address.  It usually takes 32, 64 or
                   1930: 16 bits (depending on your platform and Forth system). A cell is more
                   1931: commonly known as machine word, but the term @emph{word} already means
                   1932: something different in Forth.
                   1933: @item d
                   1934: signed double-cell integer
                   1935: @item ud
                   1936: unsigned double-cell integer
                   1937: @item r
                   1938: Float (on the FP stack)
                   1939: @end table
                   1940: 
                   1941: You can find a more complete list in @ref{Notation}.
                   1942: 
                   1943: @assignment
                   1944: Write stack-effect comments for all definitions you have written up to
                   1945: now.
                   1946: @endassignment
                   1947: 
                   1948: 
                   1949: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
                   1950: @section Types
                   1951: 
                   1952: In Forth the names of the operations are not overloaded; so similar
                   1953: operations on different types need different names; e.g., @code{+} adds
                   1954: integers, and you have to use @code{f+} to add floating-point numbers.
                   1955: The following prefixes are often used for related operations on
                   1956: different types:
                   1957: 
                   1958: @table @code
                   1959: @item (none)
                   1960: signed integer
                   1961: @item u
                   1962: unsigned integer
                   1963: @item c
                   1964: character
                   1965: @item d
                   1966: signed double-cell integer
                   1967: @item ud, du
                   1968: unsigned double-cell integer
                   1969: @item 2
                   1970: two cells (not-necessarily double-cell numbers)
                   1971: @item m, um
                   1972: mixed single-cell and double-cell operations
                   1973: @item f
                   1974: floating-point (note that in stack comments @samp{f} represents flags,
                   1975: and @samp{r} represents FP number).
                   1976: @end table
                   1977: 
                   1978: If there are no differences between the signed and the unsigned variant
                   1979: (e.g., for @code{+}), there is only the prefix-less variant.
                   1980: 
                   1981: Forth does not perform type checking, neither at compile time, nor at
                   1982: run time.  If you use the wrong oeration, the data are interpreted
                   1983: incorrectly:
                   1984: 
                   1985: @example
                   1986: -1 u.
                   1987: @end example
                   1988: 
                   1989: If you have only experience with type-checked languages until now, and
                   1990: have heard how important type-checking is, don't panic!  In my
                   1991: experience (and that of other Forthers), type errors in Forth code are
                   1992: usually easy to find (once you get used to it), the increased vigilance
                   1993: of the programmer tends to catch some harder errors in addition to most
                   1994: type errors, and you never have to work around the type system, so in
                   1995: most situations the lack of type-checking seems to be a win (projects to
                   1996: add type checking to Forth have not caught on).
                   1997: 
                   1998: 
                   1999: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
                   2000: @section Factoring
                   2001: 
                   2002: If you try to write longer definitions, you will soon find it hard to
                   2003: keep track of the stack contents.  Therefore, good Forth programmers
                   2004: tend to write only short definitions (e.g., three lines).  The art of
                   2005: finding meaningful short definitions is known as factoring (as in
                   2006: factoring polynomials).
                   2007: 
                   2008: Well-factored programs offer additional advantages: smaller, more
                   2009: general words, are easier to test and debug and can be reused more and
                   2010: better than larger, specialized words.
                   2011: 
                   2012: So, if you run into difficulties with stack management, when writing
                   2013: code, try to define meaningful factors for the word, and define the word
                   2014: in terms of those.  Even if a factor contains only two words, it is
                   2015: often helpful.
                   2016: 
                   2017: Good factoring is not easy, and even experienced Forth programmers often
                   2018: don't find the right solution right away, but only when rewriting the
                   2019: program.  So, if you don't come up with a good solution immediately,
                   2020: keep trying, don't despair.
                   2021: 
                   2022: @c example !!
                   2023: 
                   2024: 
                   2025: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
                   2026: @section Designing the stack effect
                   2027: 
                   2028: In other languages you can use an arbitrary order of parameters for a
                   2029: function; and since ther is only one result, you don't have to deal with
                   2030: the order of results, either.
                   2031: 
                   2032: In Forth (and other stack-based languages, e.g., Postscript) the
                   2033: parameter and result order of a definition is important and should be
                   2034: designed well.  The general guideline is to design the stack effect such
                   2035: that the word is simple to use in most cases, even if that complicates
                   2036: the implementation of the word.  Some concrete rules are:
                   2037: 
                   2038: @itemize @bullet
                   2039: 
                   2040: @item
                   2041: Words consume all of their parameters (e.g., @code{.}).
                   2042: 
                   2043: @item
                   2044: If there is a convention on the order of parameters (e.g., from
                   2045: mathematics or another programming language), stick with it (e.g.,
                   2046: @code{-}).
                   2047: 
                   2048: @item
                   2049: If one parameter usually requires only a short computation (e.g., it is
                   2050: a constant), pass it on the top of the stack.  Conversely, parameters
                   2051: that usually require a long sequence of code to compute should be passed
                   2052: as the bottom (i.e., first) parameter.  This makes the code easier to
                   2053: read, because reader does not need to keep track of the bottom item
                   2054: through a long sequence of code (or, alternatively, through stack
1.49      anton    2055: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48      anton    2056: address on top of the stack because it is usually simpler to compute
                   2057: than the stored value (often the address is just a variable).
                   2058: 
                   2059: @item
                   2060: Similarly, results that are usually consumed quickly should be returned
                   2061: on the top of stack, whereas a result that is often used in long
                   2062: computations should be passed as bottom result.  E.g., the file words
                   2063: like @code{open-file} return the error code on the top of stack, because
                   2064: it is usually consumed quickly by @code{throw}; moreover, the error code
                   2065: has to be checked before doing anything with the other results.
                   2066: 
                   2067: @end itemize
                   2068: 
                   2069: These rules are just general guidelines, don't lose sight of the overall
                   2070: goal to make the words easy to use.  E.g., if the convention rule
                   2071: conflicts with the computation-length rule, you might decide in favour
                   2072: of the convention if the word will be used rarely, and in favour of the
                   2073: computation-length rule if the word will be used frequently (because
                   2074: with frequent use the cost of breaking the computation-length rule would
                   2075: be quite high, and frequent use makes it easier to remember an
                   2076: unconventional order).
                   2077: 
                   2078: @c example !! structure package
                   2079: 
                   2080: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
                   2081: @section Local Variables
                   2082: 
                   2083: You can define local variables (@emph{locals}) in a colon definition:
                   2084: 
                   2085: @example
                   2086: : swap @{ a b -- b a @}
                   2087:   b a ;
                   2088: 1 2 swap .s 2drop
                   2089: @end example
                   2090: 
                   2091: (If your Forth system does not support this syntax, include
                   2092: @file{compat/anslocals.fs} first).
                   2093: 
                   2094: In this example @code{@{ a b -- b a @}} is the locals definition; it
                   2095: takes two cells from the stack, puts the top of stack in @code{b} and
                   2096: the next stack element in @code{a}.  @code{--} starts a comment ending
                   2097: with @code{@}}.  After the locals definition, using the name of the
                   2098: local will push its value on the stack.  You can leave the comment
                   2099: part (@code{-- b a}) away:
                   2100: 
                   2101: @example
                   2102: : swap ( x1 x2 -- x2 x1 )
                   2103:   @{ a b @} b a ;
                   2104: @end example
                   2105: 
                   2106: In Gforth you can have several locals definitions, anywhere in a colon
                   2107: definition; in contrast, in a standard program you can have only one
                   2108: locals definition per colon definition, and that locals definition must
                   2109: be outside any controll structure.
                   2110: 
                   2111: With locals you can write slightly longer definitions without running
                   2112: into stack trouble.  However, I recommend trying to write colon
                   2113: definitions without locals for exercise purposes to help you gain the
                   2114: essential factoring skills.
                   2115: 
                   2116: @assignment
                   2117: Rewrite your definitions until now with locals
                   2118: @endassignment
                   2119: 
                   2120: 
                   2121: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
                   2122: @section Conditional execution
                   2123: 
                   2124: In Forth you can use control structures only inside colon definitions.
                   2125: An @code{if}-structure looks like this:
                   2126: 
                   2127: @example
                   2128: : abs ( n1 -- +n2 )
                   2129:     dup 0 < if
                   2130:         negate
                   2131:     endif ;
                   2132: 5 abs .
                   2133: -5 abs .
                   2134: @end example
                   2135: 
                   2136: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
                   2137: the following code is performed, otherwise execution continues after the
1.51      pazsan   2138: @code{endif} (or @code{else}).  @code{<} compares the top two stack
1.48      anton    2139: elements and prioduces a flag:
                   2140: 
                   2141: @example
                   2142: 1 2 < .
                   2143: 2 1 < .
                   2144: 1 1 < .
                   2145: @end example
                   2146: 
                   2147: Actually the standard name for @code{endif} is @code{then}.  This
                   2148: tutorial presents the examples using @code{endif}, because this is often
                   2149: less confusing for people familiar with other programming languages
                   2150: where @code{then} has a different meaning.  If your system does not have
                   2151: @code{endif}, define it with
                   2152: 
                   2153: @example
                   2154: : endif postpone then ; immediate
                   2155: @end example
                   2156: 
                   2157: You can optionally use an @code{else}-part:
                   2158: 
                   2159: @example
                   2160: : min ( n1 n2 -- n )
                   2161:   2dup < if
                   2162:     drop
                   2163:   else
                   2164:     nip
                   2165:   endif ;
                   2166: 2 3 min .
                   2167: 3 2 min .
                   2168: @end example
                   2169: 
                   2170: @assignment
                   2171: Write @code{min} without @code{else}-part (hint: what's the definition
                   2172: of @code{nip}?).
                   2173: @endassignment
                   2174: 
                   2175: 
                   2176: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
                   2177: @section Flags and Comparisons
                   2178: 
                   2179: In a false-flag all bits are clear (0 when interpreted as integer).  In
                   2180: a canonical true-flag all bits are set (-1 as a twos-complement signed
                   2181: integer); in many contexts (e.g., @code{if}) any non-zero value is
                   2182: treated as true flag.
                   2183: 
                   2184: @example
                   2185: false .
                   2186: true .
                   2187: true hex u. decimal
                   2188: @end example
                   2189: 
                   2190: Comparison words produce canonical flags:
                   2191: 
                   2192: @example
                   2193: 1 1 = .
                   2194: 1 0= .
                   2195: 0 1 < .
                   2196: 0 0 < .
                   2197: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
                   2198: -1 1 < .
                   2199: @end example
                   2200: 
                   2201: Gforth supports all combinations of the prefixes @code{0 u d d0 du} (or
                   2202: none) and the comparisons @code{= <> < > <= >=}.  Only a part of these
1.60    ! anton    2203: combinations are standard (for details see the standard or @ref{Word
        !          2204: Glossary}).
1.48      anton    2205: 
                   2206: You can use @code{and or xor invert} can be used as operations on
                   2207: canonical flags.  Actually they are bitwise operations:
                   2208: 
                   2209: @example
                   2210: 1 2 and .
                   2211: 1 2 or .
                   2212: 1 3 xor .
                   2213: 1 invert .
                   2214: @end example
                   2215: 
                   2216: You can convert a zero/non-zero flag into a canonical flag with
                   2217: @code{0<>} (and complement it on the way with @code{0=}).
                   2218: 
                   2219: @example
                   2220: 1 0= .
                   2221: 1 0<> .
                   2222: @end example
                   2223: 
                   2224: You can use the all-bits-set feature of canonicasl flags and the bitwise
                   2225: operation of the Boolean operations to avoid @code{if}s:
                   2226: 
                   2227: @example
                   2228: : foo ( n1 -- n2 )
                   2229:   0= if
                   2230:     14
                   2231:   else
                   2232:     0
                   2233:   endif ;
                   2234: 0 foo .
                   2235: 1 foo .
                   2236: 
                   2237: : foo ( n1 -- n2 )
                   2238:   0= 14 and ;
                   2239: 0 foo .
                   2240: 1 foo .
                   2241: @end example
                   2242: 
                   2243: @assignment
                   2244: Write @code{min} without @code{if}.
                   2245: @endassignment
                   2246: 
                   2247: 
                   2248: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
                   2249: @section General Loops
                   2250: 
                   2251: The endless loop is the most simple one:
                   2252: 
                   2253: @example
                   2254: : endless ( -- )
                   2255:   0 begin
                   2256:     dup . 1+
                   2257:   again ;
                   2258: endless
                   2259: @end example
                   2260: 
                   2261: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
                   2262: does nothing at run-time, @code{again} jumps back to @code{begin}.
                   2263: 
                   2264: A loop with one exit at any place looks like this:
                   2265: 
                   2266: @example
                   2267: : log2 ( +n1 -- n2 )
                   2268: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2269:   assert( dup 0> )
                   2270:   2/ 0 begin
                   2271:     over 0> while
                   2272:       1+ swap 2/ swap
                   2273:   repeat
                   2274:   nip ;
                   2275: 7 log2 .
                   2276: 8 log2 .
                   2277: @end example
                   2278: 
                   2279: At run-time @code{while} consumes a flag; if it is 0, execution
1.51      pazsan   2280: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48      anton    2281: continues behind the @code{while}.  @code{Repeat} jumps back to
                   2282: @code{begin}, just like @code{again}.
                   2283: 
                   2284: In Forth there are many combinations/abbreviations, like @code{1+}.
                   2285: However, @code{2/} is not one of them; it shifts it's argument right by
                   2286: one bit (arithmetic shift right):
                   2287: 
                   2288: @example
                   2289: -5 2 / .
                   2290: -5 2/ .
                   2291: @end example
                   2292: 
                   2293: @code{assert(} is no standard word, but you can get it on systems other
                   2294: then Gforth by including @file{compat/assert.fs}.  You can see what it
                   2295: does by trying
                   2296: 
                   2297: @example
                   2298: 0 log2 .
                   2299: @end example
                   2300: 
                   2301: Here's a loop with an exit at the end:
                   2302: 
                   2303: @example
                   2304: : log2 ( +n1 -- n2 )
                   2305: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2306:   assert( dup 0 > )
                   2307:   -1 begin
                   2308:     1+ swap 2/ swap
                   2309:     over 0 <=
                   2310:   until
                   2311:   nip ;
                   2312: @end example
                   2313: 
                   2314: @code{Until} consumes a flag; if it is non-zero, execution continues at
                   2315: the @code{begin}, otherwise after the @code{until}.
                   2316: 
                   2317: @assignment
                   2318: Write a definition for computing the greatest common divisor.
                   2319: @endassignment
                   2320: 
                   2321: 
                   2322: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
                   2323: @section Counted loops
                   2324: 
                   2325: @example
                   2326: : ^ ( n1 u -- n )
                   2327: \ n = the uth power of u1
                   2328:   1 swap 0 u+do
                   2329:     over *
                   2330:   loop
                   2331:   nip ;
                   2332: 3 2 ^ .
                   2333: 4 3 ^ .
                   2334: @end example
                   2335: 
                   2336: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
                   2337: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
                   2338: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
                   2339: times (or not at all, if @code{u3-u4<0}).
                   2340: 
                   2341: You can see the stack effect design rules at work in the stack effect of
                   2342: the loop start words: Since the start value of the loop is more
                   2343: frequently constant than the end value, the start value is passed on
                   2344: the top-of-stack.
                   2345: 
                   2346: You can access the counter of a counted loop with @code{i}:
                   2347: 
                   2348: @example
                   2349: : fac ( u -- u! )
                   2350:   1 swap 1+ 1 u+do
                   2351:     i *
                   2352:   loop ;
                   2353: 5 fac .
                   2354: 7 fac .
                   2355: @end example
                   2356: 
                   2357: There is also @code{+do}, which expects signed numbers (important for
                   2358: deciding whether to enter the loop).
                   2359: 
                   2360: @assignment
                   2361: Write a definition for computing the nth Fibonacci number.
                   2362: @endassignment
                   2363: 
                   2364: !! +DO...+LOOP
                   2365: !! -DO...-LOOP
                   2366: 
                   2367: 
                   2368: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
                   2369: @section Recursion
                   2370: 
                   2371: Usually the name of a definition is not visible in the definition; but
                   2372: earlier definitions are usually visible:
                   2373: 
                   2374: @example
                   2375: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
                   2376: : / ( n1 n2 -- n )
                   2377:   dup 0= if
                   2378:     -10 throw \ report division by zero
                   2379:   endif
                   2380:   /           \ old version
                   2381: ;
                   2382: 1 0 /
                   2383: @end example
                   2384: 
                   2385: For recursive definitions you can use @code{recursive} (non-standard) or
                   2386: @code{recurse}:
                   2387: 
                   2388: @example
                   2389: : fac1 ( n -- n! ) recursive
                   2390:  dup 0> if
                   2391:    dup 1- fac1 *
                   2392:  else
                   2393:    drop 1
                   2394:  endif ;
                   2395: 7 fac1 .
                   2396: 
                   2397: : fac2 ( n -- n! )
                   2398:  dup 0> if
                   2399:    dup 1- recurse *
                   2400:  else
                   2401:    drop 1
                   2402:  endif ;
                   2403: 8 fac2 .
                   2404: @end example
                   2405: 
                   2406: @assignment
                   2407: Write a recursive definition for computing the nth Fibonacci number.
                   2408: @endassignment
                   2409: 
                   2410: 
                   2411: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
                   2412: @section Leaving definitions or loops
                   2413: 
                   2414: @code{EXIT} exits the current definition right away.  For every counted
                   2415: loop that is left in this way, an @code{UNLOOP} has to be performed
                   2416: before the @code{EXIT}:
                   2417: 
                   2418: @c !! real examples
                   2419: @example
                   2420: : ...
                   2421:  ... u+do
                   2422:    ... if
                   2423:      ... unloop exit
                   2424:    endif
                   2425:    ...
                   2426:  loop
                   2427:  ... ;
                   2428: @end example
                   2429: 
                   2430: @code{LEAVE} leaves the innermost counted loop right away:
                   2431: 
                   2432: @example
                   2433: : ...
                   2434:  ... u+do
                   2435:    ... if
                   2436:      ... leave
                   2437:    endif
                   2438:    ...
                   2439:  loop
                   2440:  ... ;
                   2441: @end example
                   2442: 
                   2443: 
                   2444: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
                   2445: @section Return Stack
                   2446: 
                   2447: In addition to the data stack Forth also has a second stack, the return
                   2448: stack; most Forth systems store the return addresses of procedure calls
                   2449: there (thus its name).  Programmers can also use this stack:
                   2450: 
                   2451: @example
                   2452: : foo ( n1 n2 -- )
                   2453:  .s
                   2454:  >r .s
1.50      anton    2455:  r@@ .
1.48      anton    2456:  >r .s
1.50      anton    2457:  r@@ .
1.48      anton    2458:  r> .
1.50      anton    2459:  r@@ .
1.48      anton    2460:  r> . ;
                   2461: 1 2 foo
                   2462: @end example
                   2463: 
                   2464: @code{>r} takes an element from the data stack and pushes it onto the
                   2465: return stack; conversely, @code{r>} moves an elementm from the return to
                   2466: the data stack; @code{r@@} pushes a copy of the top of the return stack
                   2467: on the return stack.
                   2468: 
                   2469: Forth programmers usually use the return stack for storing data
                   2470: temporarily, if using the data stack alone would be too complex, and
                   2471: factoring and locals are not an option:
                   2472: 
                   2473: @example
                   2474: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
                   2475:  rot >r rot r> ;
                   2476: @end example
                   2477: 
                   2478: The return address of the definition and the loop control parameters of
                   2479: counted loops usually reside on the return stack, so you have to take
                   2480: all items, that you have pushed on the return stack in a colon
                   2481: definition or counted loop, from the return stack before the definition
                   2482: or loop ends.  You cannot access items that you pushed on the return
                   2483: stack outside some definition or loop within the definition of loop.
                   2484: 
                   2485: If you miscount the return stack items, this usually ends in a crash:
                   2486: 
                   2487: @example
                   2488: : crash ( n -- )
                   2489:   >r ;
                   2490: 5 crash
                   2491: @end example
                   2492: 
                   2493: You cannot mix using locals and using the return stack (according to the
                   2494: standard; Gforth has no problem).  However, they solve the same
                   2495: problems, so this shouldn't be an issue.
                   2496: 
                   2497: @assignment
                   2498: Can you rewrite any of the definitions you wrote until now in a better
                   2499: way using the return stack?
                   2500: @endassignment
                   2501: 
                   2502: 
                   2503: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
                   2504: @section Memory
                   2505: 
                   2506: You can create a global variable @code{v} with
                   2507: 
                   2508: @example
                   2509: variable v ( -- addr )
                   2510: @end example
                   2511: 
                   2512: @code{v} pushes the address of a cell in memory on the stack.  This cell
                   2513: was reserved by @code{variable}.  You can use @code{!} (store) to store
                   2514: values into this cell and @code{@@} (fetch) to load the value from the
                   2515: stack into memory:
                   2516: 
                   2517: @example
                   2518: v .
                   2519: 5 v ! .s
1.50      anton    2520: v @@ .
1.48      anton    2521: @end example
                   2522: 
                   2523: You can also reserve more memory:
                   2524: 
                   2525: @example
                   2526: create v2 20 cells allot
                   2527: @end example
                   2528: 
                   2529: creates a word @code{v2} and reserves 20 cells; the address pushed by
                   2530: @code{v2} points to the start of these 20 cells.  You can use address
                   2531: arithmetic to access these cells:
                   2532: 
                   2533: @example
                   2534: 3 v2 5 cells + !
                   2535: @end example
                   2536: 
                   2537: You can reserve and initialize memory with @code{,}:
                   2538: 
                   2539: @example
                   2540: create v3
                   2541:   5 , 4 , 3 , 2 , 1 ,
1.50      anton    2542: v3 @@ .
                   2543: v3 cell+ @@ .
                   2544: v3 2 cells + @@ .
1.48      anton    2545: @end example
                   2546: 
                   2547: @assignment
                   2548: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
                   2549: @code{u} cells, with the first of these cells at @code{addr}, the next
                   2550: one at @code{addr cell+} etc.
                   2551: @endassignment
                   2552: 
                   2553: You can also reserve memory without creating a new word:
                   2554: 
                   2555: @example
1.60    ! anton    2556: here 10 cells allot .
        !          2557: here .
1.48      anton    2558: @end example
                   2559: 
                   2560: @code{Here} pushes the start address of the memory area.  You should
                   2561: store it somewhere, or you will have a hard time finding the memory area
                   2562: again.
                   2563: 
                   2564: @code{Allot} manages dictionary memory.  The dictionary memory contains
                   2565: the system's data structures for words etc. on Gforth and most other
                   2566: Forth systems.  It is managed like a stack: You can free the memory that
                   2567: you have just @code{allot}ed with
                   2568: 
                   2569: @example
                   2570: -10 cells allot
1.60    ! anton    2571: here .
1.48      anton    2572: @end example
                   2573: 
                   2574: Note that you cannot do this if you have created a new word in the
                   2575: meantime (because then your @code{allot}ed memory is no longer on the
                   2576: top of the dictionary ``stack'').
                   2577: 
                   2578: Alternatively, you can use @code{allocate} and @code{free} which allow
                   2579: freeing memory in any order:
                   2580: 
                   2581: @example
                   2582: 10 cells allocate throw .s
                   2583: 20 cells allocate throw .s
                   2584: swap
                   2585: free throw
                   2586: free throw
                   2587: @end example
                   2588: 
                   2589: The @code{throw}s deal with errors (e.g., out of memory).
                   2590: 
1.60    ! anton    2591: And there is also a garbage collector
        !          2592: @url{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip},
        !          2593: which eliminates the need to @code{free} memory explicitly.
1.48      anton    2594: 
                   2595: 
                   2596: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
                   2597: @section Characters and Strings
                   2598: 
                   2599: On the stack characters take up a cell, like numbers.  In memory they
                   2600: have their own size (one 8-bit byte on most systems), and therefore
                   2601: require their own words for memory access:
                   2602: 
                   2603: @example
                   2604: create v4 
                   2605:   104 c, 97 c, 108 c, 108 c, 111 c,
1.50      anton    2606: v4 4 chars + c@@ .
1.48      anton    2607: @end example
                   2608: 
                   2609: The preferred representation of strings on the stack is @code{addr
                   2610: u-count}, where @code{addr} is the address of the first character and
                   2611: @code{u-count} is the number of characters in the string.
                   2612: 
                   2613: @example
                   2614: v4 5 type
                   2615: @end example
                   2616: 
                   2617: You get a string constant with
                   2618: 
                   2619: @example
                   2620: s" hello, world" .s
                   2621: type
                   2622: @end example
                   2623: 
                   2624: Make sure you have a space between @code{s"} and the string; @code{s"}
                   2625: is a normal Forth word and must be delimited with white space (try what
                   2626: happens when you remove the space).
                   2627: 
                   2628: However, this interpretive use of @code{s"} is quite restricted: the
                   2629: string exists only until the next call of @code{s"} (some Forth systems
                   2630: keep more than one of these strings, but usually they still have a
                   2631: limited lifetime.
                   2632: 
                   2633: @example
                   2634: s" hello," s" world" .s
                   2635: type
                   2636: type
                   2637: @end example
                   2638: 
                   2639: However, you can also use @code{s"} in a definition, and the resulting
                   2640: strings then live forever (well, as long as the definition):
                   2641: 
                   2642: @example
                   2643: : foo s" hello," s" world" ;
                   2644: foo .s
                   2645: type
                   2646: type
                   2647: @end example
                   2648: 
                   2649: @assignment
                   2650: @code{Emit ( c -- )} types @code{c} as character (not a number).
                   2651: Implement @code{type ( addr u -- )}.
                   2652: @endassignment
                   2653: 
                   2654: @node Alignment Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Characters and Strings Tutorial, Tutorial
                   2655: @section Alignment
                   2656: 
                   2657: On many processors cells have to be aligned in memory, if you want to
                   2658: access them with @code{@@} and @code{!} (and even if the processor does
                   2659: not require alignment, access to aligned cells are faster).
                   2660: 
                   2661: @code{Create} aligns @code{here} (i.e., the place where the next
                   2662: allocation will occur, and that the @code{create}d word points to).
                   2663: Likewise, the memory produced by @code{allocate} starts at an aligned
                   2664: address.  Adding a number of @code{cells} to an aligned address produces
                   2665: another aligned address.
                   2666: 
                   2667: However, address arithmetic involving @code{char+} and @code{chars} can
                   2668: create an address that is not cell-aligned.  @code{Aligned ( addr --
                   2669: a-addr )} produces the next aligned address:
                   2670: 
                   2671: @example
1.50      anton    2672: v3 char+ aligned .s @@ .
                   2673: v3 char+ .s @@ .
1.48      anton    2674: @end example
                   2675: 
                   2676: Similarly, @code{align} advances @code{here} to the next aligned
                   2677: address:
                   2678: 
                   2679: @example
                   2680: create v5 97 c,
                   2681: here .
                   2682: align here .
                   2683: 1000 ,
                   2684: @end example
                   2685: 
                   2686: Note that you should use aligned addresses even if your processor does
                   2687: not require them, if you want your program to be portable.
                   2688: 
                   2689: 
                   2690: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Alignment Tutorial, Tutorial
                   2691: @section Interpretation and Compilation Semantics and Immediacy
                   2692: 
                   2693: When a word is compiled, it behaves differently from being interpreted.
                   2694: E.g., consider @code{+}:
                   2695: 
                   2696: @example
                   2697: 1 2 + .
                   2698: : foo + ;
                   2699: @end example
                   2700: 
                   2701: These two behaviours are known as compilation and interpretation
                   2702: semantics.  For normal words (e.g., @code{+}), the compilation semantics
                   2703: is to append the interpretation semantics to the currently defined word
                   2704: (@code{foo} in the example above).  I.e., when @code{foo} is executed
                   2705: later, the interpretation semantics of @code{+} (i.e., adding two
                   2706: numbers) will be performed.
                   2707: 
                   2708: However, there are words with non-default compilation semantics, e.g.,
                   2709: the control-flow words like @code{if}.  You can use @code{immediate} to
                   2710: change the compilation semantics of the last defined word to be equal to
                   2711: the interpretation semantics:
                   2712: 
                   2713: @example
                   2714: : [FOO] ( -- )
                   2715:  5 . ; immediate
                   2716: 
                   2717: [FOO]
                   2718: : bar ( -- )
                   2719:   [FOO] ;
                   2720: bar
                   2721: see bar
                   2722: @end example
                   2723: 
                   2724: Two conventions to mark words with non-default compilation semnatics are
                   2725: names with brackets (more frequently used) and to write them all in
                   2726: upper case (less frequently used).
                   2727: 
                   2728: In Gforth (and many other systems) you can also remove the
                   2729: interpretation semantics with @code{compile-only} (the compilation
                   2730: semantics is derived from the original interpretation semantics):
                   2731: 
                   2732: @example
                   2733: : flip ( -- )
                   2734:  6 . ; compile-only \ but not immediate
                   2735: flip
                   2736: 
                   2737: : flop ( -- )
                   2738:  flip ;
                   2739: flop
                   2740: @end example
                   2741: 
                   2742: In this example the interpretation semantics of @code{flop} is equal to
                   2743: the original interpretation semantics of @code{flip}.
                   2744: 
                   2745: The text interpreter has two states: in interpret state, it performs the
                   2746: interpretation semantics of words it encounters; in compile state, it
                   2747: performs the compilation semantics of these words.
                   2748: 
                   2749: Among other things, @code{:} switches into compile state, and @code{;}
                   2750: switches back to interpret state.  They contain the factors @code{]}
                   2751: (switch to compile state) and @code{[} (switch to interpret state), that
                   2752: do nothing but switch the state.
                   2753: 
                   2754: @example
                   2755: : xxx ( -- )
                   2756:   [ 5 . ]
                   2757: ;
                   2758: 
                   2759: xxx
                   2760: see xxx
                   2761: @end example
                   2762: 
                   2763: These brackets are also the source of the naming convention mentioned
                   2764: above.
                   2765: 
                   2766: 
                   2767: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
                   2768: @section Execution Tokens
                   2769: 
                   2770: @code{' word} gives you the execution token (XT) of a word.  The XT is a
                   2771: cell representing the interpretation semantics of a word.  You can
                   2772: execute this semantics with @code{execute}:
                   2773: 
                   2774: @example
                   2775: ' + .s
                   2776: 1 2 rot execute .
                   2777: @end example
                   2778: 
                   2779: The XT is similar to a function pointer in C.  However, parameter
                   2780: passing through the stack makes it a little more flexible:
                   2781: 
                   2782: @example
                   2783: : map-array ( ... addr u xt -- ... )
1.50      anton    2784: \ executes xt ( ... x -- ... ) for every element of the array starting
                   2785: \ at addr and containing u elements
1.48      anton    2786:   @{ xt @}
                   2787:   cells over + swap ?do
1.50      anton    2788:     i @@ xt execute
1.48      anton    2789:   1 cells +loop ;
                   2790: 
                   2791: create a 3 , 4 , 2 , -1 , 4 ,
                   2792: a 5 ' . map-array .s
                   2793: 0 a 5 ' + map-array .
                   2794: s" max-n" environment? drop .s
                   2795: a 5 ' min map-array .
                   2796: @end example
                   2797: 
                   2798: You can use map-array with the XTs of words that consume one element
                   2799: more than they produce.  In theory you can also use it with other XTs,
                   2800: but the stack effect then depends on the size of the array, which is
                   2801: hard to understand.
                   2802: 
1.51      pazsan   2803: Since XTs are cell-sized, you can store them in memory and manipulate
                   2804: them on the stack like other cells.  You can also compile the XT into a
1.48      anton    2805: word with @code{compile,}:
                   2806: 
                   2807: @example
                   2808: : foo1 ( n1 n2 -- n )
                   2809:    [ ' + compile, ] ;
                   2810: see foo
                   2811: @end example
                   2812: 
                   2813: This is non-standard, because @code{compile,} has no compilation
                   2814: semantics in the standard, but it works in good Forth systems.  For the
                   2815: broken ones, use
                   2816: 
                   2817: @example
                   2818: : [compile,] compile, ; immediate
                   2819: 
                   2820: : foo1 ( n1 n2 -- n )
                   2821:    [ ' + ] [compile,] ;
                   2822: see foo
                   2823: @end example
                   2824: 
                   2825: @code{'} is a word with default compilation semantics; it parses the
                   2826: next word when its interpretation semantics are executed, not during
                   2827: compilation:
                   2828: 
                   2829: @example
                   2830: : foo ( -- xt )
                   2831:   ' ;
                   2832: see foo
                   2833: : bar ( ... "word" -- ... )
                   2834:   ' execute ;
                   2835: see bar
1.60    ! anton    2836: 1 2 bar + .
1.48      anton    2837: @end example
                   2838: 
                   2839: You often want to parse a word during compilation and compile its XT so
                   2840: it will be pushed on the stack at run-time.  @code{[']} does this:
                   2841: 
                   2842: @example
                   2843: : xt-+ ( -- xt )
                   2844:   ['] + ;
                   2845: see xt-+
                   2846: 1 2 xt-+ execute .
                   2847: @end example
                   2848: 
                   2849: Many programmers tend to see @code{'} and the word it parses as one
                   2850: unit, and expect it to behave like @code{[']} when compiled, and are
                   2851: confused by the actual behaviour.  If you are, just remember that the
                   2852: Forth system just takes @code{'} as one unit and has no idea that it is
                   2853: a parsing word (attempts to convenience programmers in this issue have
                   2854: usually resulted in even worse pitfalls, see
                   2855: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz}).
                   2856: 
                   2857: Note that the state of the interpreter does not come into play when
1.51      pazsan   2858: creating and executing XTs.  I.e., even when you execute @code{'} in
1.48      anton    2859: compile state, it still gives you the interpretation semantics.  And
                   2860: whatever that state is, @code{execute} performs the semantics
1.51      pazsan   2861: represented by the XT (i.e., the interpretation semantics).
1.48      anton    2862: 
                   2863: 
                   2864: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
                   2865: @section Exceptions
                   2866: 
                   2867: @code{throw ( n -- )} causes an exception unless n is zero.
                   2868: 
                   2869: @example
                   2870: 100 throw .s
                   2871: 0 throw .s
                   2872: @end example
                   2873: 
                   2874: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
                   2875: it catches exceptions and pushes the number of the exception on the
                   2876: stack (or 0, if the xt executed without exception).  If there was an
                   2877: exception, the stacks have the same depth as when entering @code{catch}:
                   2878: 
                   2879: @example
                   2880: .s
                   2881: 3 0 ' / catch .s
                   2882: 3 2 ' / catch .s
                   2883: @end example
                   2884: 
                   2885: @assignment
                   2886: Try the same with @code{execute} instead of @code{catch}.
                   2887: @endassignment
                   2888: 
                   2889: @code{Throw} always jumps to the dynamically next enclosing
                   2890: @code{catch}, even if it has to leave several call levels to achieve
                   2891: this:
                   2892: 
                   2893: @example
                   2894: : foo 100 throw ;
                   2895: : foo1 foo ." after foo" ;
1.51      pazsan   2896: : bar ['] foo1 catch ;
1.60    ! anton    2897: bar .
1.48      anton    2898: @end example
                   2899: 
                   2900: It is often important to restore a value upon leaving a definition, even
                   2901: if the definition is left through an exception.  You can ensure this
                   2902: like this:
                   2903: 
                   2904: @example
                   2905: : ...
                   2906:    save-x
1.51      pazsan   2907:    ['] word-changing-x catch ( ... n )
1.48      anton    2908:    restore-x
                   2909:    ( ... n ) throw ;
                   2910: @end example
                   2911: 
1.55      anton    2912: Gforth provides an alternative syntax in addition to @code{catch}:
1.48      anton    2913: @code{try ... recover ... endtry}.  If the code between @code{try} and
                   2914: @code{recover} has an exception, the stack depths are restored, the
                   2915: exception number is pushed on the stack, and the code between
                   2916: @code{recover} and @code{endtry} is performed.  E.g., the definition for
                   2917: @code{catch} is
                   2918: 
                   2919: @example
                   2920: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
                   2921:   try
                   2922:     execute 0
                   2923:   recover
                   2924:     nip
                   2925:   endtry ;
                   2926: @end example
                   2927: 
                   2928: The equivalent to the restoration code above is
                   2929: 
                   2930: @example
                   2931: : ...
                   2932:   save-x
                   2933:   try
                   2934:     word-changing-x
                   2935:   end-try
                   2936:   restore-x
                   2937:   throw ;
                   2938: @end example
                   2939: 
                   2940: As you can see, the @code{recover} part is optional.
                   2941: 
                   2942: 
                   2943: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
                   2944: @section Defining Words
                   2945: 
                   2946: @code{:}, @code{create}, and @code{variable} are definition words: They
                   2947: define other words.  @code{Constant} is another definition word:
                   2948: 
                   2949: @example
                   2950: 5 constant foo
                   2951: foo .
                   2952: @end example
                   2953: 
                   2954: You can also use the prefixes @code{2} (double-cell) and @code{f}
                   2955: (floating point) with @code{variable} and @code{constant}.
                   2956: 
                   2957: You can also define your own defining words.  E.g.:
                   2958: 
                   2959: @example
                   2960: : variable ( "name" -- )
                   2961:   create 0 , ;
                   2962: @end example
                   2963: 
                   2964: You can also define defining words that create words that do something
                   2965: other than just producing their address:
                   2966: 
                   2967: @example
                   2968: : constant ( n "name" -- )
                   2969:   create ,
                   2970: does> ( -- n )
1.50      anton    2971:   ( addr ) @@ ;
1.48      anton    2972: 
                   2973: 5 constant foo
                   2974: foo .
                   2975: @end example
                   2976: 
                   2977: The definition of @code{constant} above ends at the @code{does>}; i.e.,
                   2978: @code{does>} replaces @code{;}, but it also does something else: It
                   2979: changes the last defined word such that it pushes the address of the
                   2980: body of the word and then performs the code after the @code{does>}
                   2981: whenever it is called.
                   2982: 
                   2983: In the example above, @code{constant} uses @code{,} to store 5 into the
                   2984: body of @code{foo}.  When @code{foo} executes, it pushes the address of
                   2985: the body onto the stack, then (in the code after the @code{does>})
                   2986: fetches the 5 from there.
                   2987: 
                   2988: The stack comment near the @code{does>} reflects the stack effect of the
                   2989: defined word, not the stack effect of the code after the @code{does>}
                   2990: (the difference is that the code expects the address of the body that
                   2991: the stack comment does not show).
                   2992: 
                   2993: You can use these definition words to do factoring in cases that involve
                   2994: (other) definition words.  E.g., a field offset is always added to an
                   2995: address.  Instead of defining
                   2996: 
                   2997: @example
                   2998: 2 cells constant offset-field1
                   2999: @end example
                   3000: 
                   3001: and using this like
                   3002: 
                   3003: @example
                   3004: ( addr ) offset-field1 +
                   3005: @end example
                   3006: 
                   3007: you can define a definition word
                   3008: 
                   3009: @example
                   3010: : simple-field ( n "name" -- )
                   3011:   create ,
                   3012: does> ( n1 -- n1+n )
1.50      anton    3013:   ( addr ) @@ + ;
1.48      anton    3014: @end example
1.21      crook    3015: 
1.48      anton    3016: Definition and use of field offsets now look like this:
1.21      crook    3017: 
1.48      anton    3018: @example
                   3019: 2 cells simple-field field1
1.60    ! anton    3020: create mystruct 4 cells allot
        !          3021: mystruct .s field1 .s drop
1.48      anton    3022: @end example
1.21      crook    3023: 
1.48      anton    3024: If you want to do something with the word without performing the code
                   3025: after the @code{does>}, you can access the body of a @code{create}d word
                   3026: with @code{>body ( xt -- addr )}:
1.21      crook    3027: 
1.48      anton    3028: @example
                   3029: : value ( n "name" -- )
                   3030:   create ,
                   3031: does> ( -- n1 )
1.50      anton    3032:   @@ ;
1.48      anton    3033: : to ( n "name" -- )
                   3034:   ' >body ! ;
1.21      crook    3035: 
1.48      anton    3036: 5 value foo
                   3037: foo .
                   3038: 7 to foo
                   3039: foo .
                   3040: @end example
1.21      crook    3041: 
1.48      anton    3042: @assignment
                   3043: Define @code{defer ( "name" -- )}, which creates a word that stores an
                   3044: XT (at the start the XT of @code{abort}), and upon execution
                   3045: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
                   3046: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
                   3047: recursion is one application of @code{defer}.
                   3048: @endassignment
1.29      crook    3049: 
1.48      anton    3050: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
                   3051: @section Arrays and Records
1.29      crook    3052: 
1.48      anton    3053: Forth has no standard words for defining data structures such as arrays
                   3054: and records (structs in C terminology), but you can build them yourself
                   3055: based on address arithmetic.  You can also define words for defining
                   3056: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29      crook    3057: 
1.48      anton    3058: One of the first projects a Forth newcomer sets out upon when learning
                   3059: about defining words is an array defining word (possibly for
                   3060: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
                   3061: learn something from it.  However, don't be disappointed when you later
                   3062: learn that you have little use for these words (inappropriate use would
                   3063: be even worse).  I have not yet found a set of useful array words yet;
                   3064: the needs are just too diverse, and named, global arrays (the result of
                   3065: naive use of defining words) are often not flexible enough (e.g.,
                   3066: consider how to pass them as parameters).
1.29      crook    3067: 
1.48      anton    3068: On the other hand, there is a useful set of record words, and it has
                   3069: been defined in @file{compat/struct.fs}; these words are predefined in
                   3070: Gforth.  They are explained in depth elsewhere in this manual (see
                   3071: @pxref{Structures}).  The @code{simple-field} example above is
                   3072: simplified variant of fields in this package.
1.21      crook    3073: 
                   3074: 
1.48      anton    3075: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
                   3076: @section @code{POSTPONE}
1.21      crook    3077: 
1.48      anton    3078: You can compile the compilation semantics (instead of compiling the
                   3079: interpretation semantics) of a word with @code{POSTPONE}:
1.21      crook    3080: 
1.48      anton    3081: @example
                   3082: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51      pazsan   3083:  POSTPONE + ; immediate
1.48      anton    3084: : foo ( n1 n2 -- n )
                   3085:  MY-+ ;
                   3086: 1 2 foo .
                   3087: see foo
                   3088: @end example
1.21      crook    3089: 
1.48      anton    3090: During the definition of @code{foo} the text interpreter performs the
                   3091: compilation semantics of @code{MY-+}, which performs the compilation
                   3092: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
                   3093: 
                   3094: This example also displays separate stack comments for the compilation
                   3095: semantics and for the stack effect of the compiled code.  For words with
                   3096: default compilation semantics these stack effects are usually not
                   3097: displayed; the stack effect of the compilation semantics is always
                   3098: @code{( -- )} for these words, the stack effect for the compiled code is
                   3099: the stack effect of the interpretation semantics.
                   3100: 
                   3101: Note that the state of the interpreter does not come into play when
                   3102: performing the compilation semantics in this way.  You can also perform
                   3103: it interpretively, e.g.:
                   3104: 
                   3105: @example
                   3106: : foo2 ( n1 n2 -- n )
                   3107:  [ MY-+ ] ;
                   3108: 1 2 foo .
                   3109: see foo
                   3110: @end example
1.21      crook    3111: 
1.48      anton    3112: However, there are some broken Forth systems where this does not always
                   3113: work, and therefore this practice has been declared non-standard in
                   3114: 1999.
                   3115: @c !! repair.fs
                   3116: 
                   3117: Here is another example for using @code{POSTPONE}:
1.44      crook    3118: 
1.48      anton    3119: @example
                   3120: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
                   3121:  POSTPONE negate POSTPONE + ; immediate compile-only
                   3122: : bar ( n1 n2 -- n )
                   3123:   MY-- ;
                   3124: 2 1 bar .
                   3125: see bar
                   3126: @end example
1.21      crook    3127: 
1.48      anton    3128: You can define @code{ENDIF} in this way:
1.21      crook    3129: 
1.48      anton    3130: @example
                   3131: : ENDIF ( Compilation: orig -- )
                   3132:   POSTPONE then ; immediate
                   3133: @end example
1.21      crook    3134: 
1.48      anton    3135: @assignment
                   3136: Write @code{MY-2DUP} that has compilation semantics equivalent to
                   3137: @code{2dup}, but compiles @code{over over}.
                   3138: @endassignment
1.29      crook    3139: 
1.48      anton    3140: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
                   3141: @section @code{Literal}
1.29      crook    3142: 
1.48      anton    3143: You cannot @code{POSTPONE} numbers:
1.21      crook    3144: 
1.48      anton    3145: @example
                   3146: : [FOO] POSTPONE 500 ; immediate
1.21      crook    3147: @end example
                   3148: 
1.48      anton    3149: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29      crook    3150: 
1.48      anton    3151: @example
                   3152: : [FOO] ( compilation: --; run-time: -- n )
                   3153:   500 POSTPONE literal ; immediate
1.29      crook    3154: 
1.60    ! anton    3155: : flip [FOO] ;
1.48      anton    3156: flip .
                   3157: see flip
                   3158: @end example
1.29      crook    3159: 
1.48      anton    3160: @code{LITERAL} consumes a number at compile-time (when it's compilation
                   3161: semantics are executed) and pushes it at run-time (when the code it
                   3162: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
                   3163: number computed at compile time into the current word:
1.29      crook    3164: 
1.48      anton    3165: @example
                   3166: : bar ( -- n )
                   3167:   [ 2 2 + ] literal ;
                   3168: see bar
                   3169: @end example
1.29      crook    3170: 
1.48      anton    3171: @assignment
                   3172: Write @code{]L} which allows writing the example above as @code{: bar (
                   3173: -- n ) [ 2 2 + ]L ;}
                   3174: @endassignment
                   3175: 
                   3176: 
                   3177: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
                   3178: @section Advanced macros
                   3179: 
                   3180: Reconsider @code{map-array} from @ref{Execution Tokens
                   3181: Tutorial,, Execution Tokens}.  It frequently performs @code{execute}, a
                   3182: relatively expensive operation in some implementations.  You can use
                   3183: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
                   3184: and produce a word that contains the word to be performed directly:
                   3185: 
                   3186: @c use ]] ... [[
                   3187: @example
                   3188: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
                   3189: \ at run-time, execute xt ( ... x -- ... ) for each element of the
                   3190: \ array beginning at addr and containing u elements
                   3191:   @{ xt @}
                   3192:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50      anton    3193:     POSTPONE i POSTPONE @@ xt compile,
1.48      anton    3194:   1 cells POSTPONE literal POSTPONE +loop ;
                   3195: 
                   3196: : sum-array ( addr u -- n )
                   3197:  0 rot rot [ ' + compile-map-array ] ;
                   3198: see sum-array
                   3199: a 5 sum-array .
                   3200: @end example
                   3201: 
                   3202: You can use the full power of Forth for generating the code; here's an
                   3203: example where the code is generated in a loop:
                   3204: 
                   3205: @example
                   3206: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
                   3207: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50      anton    3208:   POSTPONE tuck POSTPONE @@
1.48      anton    3209:   POSTPONE literal POSTPONE * POSTPONE +
                   3210:   POSTPONE swap POSTPONE cell+ ;
                   3211: 
                   3212: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51      pazsan   3213: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48      anton    3214:   0 postpone literal postpone swap
                   3215:   [ ' compile-vmul-step compile-map-array ]
                   3216:   postpone drop ;
                   3217: see compile-vmul
                   3218: 
                   3219: : a-vmul ( addr -- n )
1.51      pazsan   3220: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48      anton    3221:  [ a 5 compile-vmul ] ;
                   3222: see a-vmul
                   3223: a a-vmul .
                   3224: @end example
                   3225: 
                   3226: This example uses @code{compile-map-array} to show off, but you could
                   3227: also use @code{map-array} instead (try it now).
                   3228: 
                   3229: You can use this technique for efficient multiplication of large
                   3230: matrices.  In matrix multiplication, you multiply every line of one
                   3231: matrix with every column of the other matrix.  You can generate the code
                   3232: for one line once, and use it for every column.  The only downside of
                   3233: this technique is that it is cumbersome to recover the memory consumed
                   3234: by the generated code when you are done (and in more complicated cases
                   3235: it is not possible portably).
                   3236: 
                   3237: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
                   3238: @section Compilation Tokens
                   3239: 
                   3240: This section is Gforth-specific.  You can skip it.
                   3241: 
                   3242: @code{' word compile,} compiles the interpretation semantics.  For words
                   3243: with default compilation semantics this is the same as performing the
                   3244: compilation semantics.  To represent the compilation semantics of other
                   3245: words (e.g., words like @code{if} that have no interpretation
                   3246: semantics), Gforth has the concept of a compilation token (CT,
                   3247: consisting of two cells), and words @code{comp'} and @code{[comp']}.
                   3248: You can perform the compilation semantics represented by a CT with
                   3249: @code{execute}:
1.29      crook    3250: 
1.48      anton    3251: @example
                   3252: : foo2 ( n1 n2 -- n )
                   3253:    [ comp' + execute ] ;
                   3254: see foo
                   3255: @end example
1.29      crook    3256: 
1.48      anton    3257: You can compile the compilation semantics represented by a CT with
                   3258: @code{postpone,}:
1.30      anton    3259: 
1.48      anton    3260: @example
                   3261: : foo3 ( -- )
                   3262:   [ comp' + postpone, ] ;
                   3263: see foo3
                   3264: @end example
1.30      anton    3265: 
1.51      pazsan   3266: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48      anton    3267: @code{comp'} is particularly useful for words that have no
                   3268: interpretation semantics:
1.29      crook    3269: 
1.30      anton    3270: @example
1.48      anton    3271: ' if
1.60    ! anton    3272: comp' if .s 2drop
1.30      anton    3273: @end example
                   3274: 
1.29      crook    3275: 
1.48      anton    3276: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
                   3277: @section Wordlists and Search Order
                   3278: 
                   3279: The dictionary is not just a memory area that allows you to allocate
                   3280: memory with @code{allot}, it also contains the Forth words, arranged in
                   3281: several wordlists.  When searching for a word in a wordlist,
                   3282: conceptually you start searching at the youngest and proceed towards
                   3283: older words (in reality most systems nowadays use hash-tables); i.e., if
                   3284: you define a word with the same name as an older word, the new word
                   3285: shadows the older word.
                   3286: 
                   3287: Which wordlists are searched in which order is determined by the search
                   3288: order.  You can display the search order with @code{order}.  It displays
                   3289: first the search order, starting with the wordlist searched first, then
                   3290: it displays the wordlist that will contain newly defined words.
1.21      crook    3291: 
1.48      anton    3292: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21      crook    3293: 
1.48      anton    3294: @example
                   3295: wordlist constant mywords
                   3296: @end example
1.21      crook    3297: 
1.48      anton    3298: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
                   3299: defined words (the @emph{current} wordlist):
1.21      crook    3300: 
1.48      anton    3301: @example
                   3302: mywords set-current
                   3303: order
                   3304: @end example
1.26      crook    3305: 
1.48      anton    3306: Gforth does not display a name for the wordlist in @code{mywords}
                   3307: because this wordlist was created anonymously with @code{wordlist}.
1.21      crook    3308: 
1.48      anton    3309: You can get the current wordlist with @code{get-current ( -- wid)}.  If
                   3310: you want to put something into a specific wordlist without overall
                   3311: effect on the current wordlist, this typically looks like this:
1.21      crook    3312: 
1.48      anton    3313: @example
                   3314: get-current mywords set-current ( wid )
                   3315: create someword
                   3316: ( wid ) set-current
                   3317: @end example
1.21      crook    3318: 
1.48      anton    3319: You can write the search order with @code{set-order ( wid1 .. widn n --
                   3320: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
                   3321: searched wordlist is topmost.
1.21      crook    3322: 
1.48      anton    3323: @example
                   3324: get-order mywords swap 1+ set-order
                   3325: order
                   3326: @end example
1.21      crook    3327: 
1.48      anton    3328: Yes, the order of wordlists in the output of @code{order} is reversed
                   3329: from stack comments and the output of @code{.s} and thus unintuitive.
1.21      crook    3330: 
1.48      anton    3331: @assignment
                   3332: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
                   3333: wordlist to the search order.  Define @code{previous ( -- )}, which
                   3334: removes the first searched wordlist from the search order.  Experiment
                   3335: with boundary conditions (you will see some crashes or situations that
                   3336: are hard or impossible to leave).
                   3337: @endassignment
1.21      crook    3338: 
1.48      anton    3339: The search order is a powerful foundation for providing features similar
                   3340: to Modula-2 modules and C++ namespaces.  However, trying to modularize
                   3341: programs in this way has disadvantages for debugging and reuse/factoring
                   3342: that overcome the advantages in my experience (I don't do huge projects,
1.55      anton    3343: though).  These disadvantages are not so clear in other
1.48      anton    3344: languages/programming environments, because these langauges are not so
                   3345: strong in debugging and reuse.
1.21      crook    3346: 
                   3347: 
1.29      crook    3348: @c ******************************************************************
1.48      anton    3349: @node Introduction, Words, Tutorial, Top
1.29      crook    3350: @comment node-name,     next,           previous, up
                   3351: @chapter An Introduction to ANS Forth
                   3352: @cindex Forth - an introduction
1.21      crook    3353: 
1.29      crook    3354: The primary purpose of this manual is to document Gforth. However, since
                   3355: Forth is not a widely-known language and there is a lack of up-to-date
                   3356: teaching material, it seems worthwhile to provide some introductory
1.49      anton    3357: material.  For other sources of Forth-related
                   3358: information, see @ref{Forth-related information}.
1.21      crook    3359: 
1.29      crook    3360: The examples in this section should work on any ANS Forth; the
                   3361: output shown was produced using Gforth. Each example attempts to
                   3362: reproduce the exact output that Gforth produces. If you try out the
                   3363: examples (and you should), what you should type is shown @kbd{like this}
                   3364: and Gforth's response is shown @code{like this}. The single exception is
1.30      anton    3365: that, where the example shows @key{RET} it means that you should
1.29      crook    3366: press the ``carriage return'' key. Unfortunately, some output formats for
                   3367: this manual cannot show the difference between @kbd{this} and
                   3368: @code{this} which will make trying out the examples harder (but not
                   3369: impossible).
1.21      crook    3370: 
1.29      crook    3371: Forth is an unusual language. It provides an interactive development
                   3372: environment which includes both an interpreter and compiler. Forth
                   3373: programming style encourages you to break a problem down into many
                   3374: @cindex factoring
                   3375: small fragments (@dfn{factoring}), and then to develop and test each
                   3376: fragment interactively. Forth advocates assert that breaking the
                   3377: edit-compile-test cycle used by conventional programming languages can
                   3378: lead to great productivity improvements.
1.21      crook    3379: 
1.29      crook    3380: @menu
                   3381: * Introducing the Text Interpreter::
                   3382: * Stacks and Postfix notation::
                   3383: * Your first definition::
                   3384: * How does that work?::
                   3385: * Forth is written in Forth::
                   3386: * Review - elements of a Forth system::
                   3387: * Where to go next::
                   3388: * Exercises::
                   3389: @end menu
1.21      crook    3390: 
1.29      crook    3391: @comment ----------------------------------------------
                   3392: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
                   3393: @section Introducing the Text Interpreter
                   3394: @cindex text interpreter
                   3395: @cindex outer interpreter
1.21      crook    3396: 
1.30      anton    3397: @c IMO this is too detailed and the pace is too slow for
                   3398: @c an introduction.  If you know German, take a look at
                   3399: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
                   3400: @c to see how I do it - anton 
                   3401: 
1.44      crook    3402: @c nac-> Where I have accepted your comments 100% and modified the text
                   3403: @c accordingly, I have deleted your comments. Elsewhere I have added a
                   3404: @c response like this to attempt to rationalise what I have done. Of
                   3405: @c course, this is a very clumsy mechanism for something that would be
                   3406: @c done far more efficiently over a beer. Please delete any dialogue
                   3407: @c you consider closed.
                   3408: 
1.29      crook    3409: When you invoke the Forth image, you will see a startup banner printed
                   3410: and nothing else (if you have Gforth installed on your system, try
1.30      anton    3411: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29      crook    3412: its command line interpreter, which is called the @dfn{Text Interpreter}
                   3413: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
1.49      anton    3414: about the text interpreter as you read through this chapter, for more
                   3415: detail @pxref{The Text Interpreter}).
1.21      crook    3416: 
1.29      crook    3417: Although it's not obvious, Forth is actually waiting for your
1.30      anton    3418: input. Type a number and press the @key{RET} key:
1.21      crook    3419: 
1.26      crook    3420: @example
1.30      anton    3421: @kbd{45@key{RET}}  ok
1.26      crook    3422: @end example
1.21      crook    3423: 
1.29      crook    3424: Rather than give you a prompt to invite you to input something, the text
                   3425: interpreter prints a status message @i{after} it has processed a line
                   3426: of input. The status message in this case (``@code{ ok}'' followed by
                   3427: carriage-return) indicates that the text interpreter was able to process
                   3428: all of your input successfully. Now type something illegal:
                   3429: 
                   3430: @example
1.30      anton    3431: @kbd{qwer341@key{RET}}
1.29      crook    3432: :1: Undefined word
                   3433: qwer341
                   3434: ^^^^^^^
                   3435: $400D2BA8 Bounce
                   3436: $400DBDA8 no.extensions
                   3437: @end example
1.23      crook    3438: 
1.29      crook    3439: The exact text, other than the ``Undefined word'' may differ slightly on
                   3440: your system, but the effect is the same; when the text interpreter
                   3441: detects an error, it discards any remaining text on a line, resets
1.49      anton    3442: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
                   3443: messages}.
1.23      crook    3444: 
1.29      crook    3445: The text interpreter waits for you to press carriage-return, and then
                   3446: processes your input line. Starting at the beginning of the line, it
                   3447: breaks the line into groups of characters separated by spaces. For each
                   3448: group of characters in turn, it makes two attempts to do something:
1.23      crook    3449: 
1.29      crook    3450: @itemize @bullet
                   3451: @item
1.44      crook    3452: @cindex name dictionary
1.29      crook    3453: It tries to treat it as a command. It does this by searching a @dfn{name
                   3454: dictionary}. If the group of characters matches an entry in the name
                   3455: dictionary, the name dictionary provides the text interpreter with
                   3456: information that allows the text interpreter perform some actions. In
                   3457: Forth jargon, we say that the group
                   3458: @cindex word
                   3459: @cindex definition
                   3460: @cindex execution token
                   3461: @cindex xt
                   3462: of characters names a @dfn{word}, that the dictionary search returns an
                   3463: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
                   3464: word, and that the text interpreter executes the xt. Often, the terms
                   3465: @dfn{word} and @dfn{definition} are used interchangeably.
                   3466: @item
                   3467: If the text interpreter fails to find a match in the name dictionary, it
                   3468: tries to treat the group of characters as a number in the current number
                   3469: base (when you start up Forth, the current number base is base 10). If
                   3470: the group of characters legitimately represents a number, the text
                   3471: interpreter pushes the number onto a stack (we'll learn more about that
                   3472: in the next section).
                   3473: @end itemize
1.23      crook    3474: 
1.29      crook    3475: If the text interpreter is unable to do either of these things with any
                   3476: group of characters, it discards the group of characters and the rest of
                   3477: the line, then prints an error message. If the text interpreter reaches
                   3478: the end of the line without error, it prints the status message ``@code{ ok}''
                   3479: followed by carriage-return.
1.21      crook    3480: 
1.29      crook    3481: This is the simplest command we can give to the text interpreter:
1.23      crook    3482: 
                   3483: @example
1.30      anton    3484: @key{RET}  ok
1.23      crook    3485: @end example
1.21      crook    3486: 
1.29      crook    3487: The text interpreter did everything we asked it to do (nothing) without
                   3488: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
                   3489: command:
1.21      crook    3490: 
1.23      crook    3491: @example
1.30      anton    3492: @kbd{12 dup fred dup@key{RET}}
1.29      crook    3493: :1: Undefined word
                   3494: 12 dup fred dup
                   3495:        ^^^^
                   3496: $400D2BA8 Bounce
                   3497: $400DBDA8 no.extensions
1.23      crook    3498: @end example
1.21      crook    3499: 
1.29      crook    3500: When you press the carriage-return key, the text interpreter starts to
                   3501: work its way along the line:
1.21      crook    3502: 
1.29      crook    3503: @itemize @bullet
                   3504: @item
                   3505: When it gets to the space after the @code{2}, it takes the group of
                   3506: characters @code{12} and looks them up in the name
                   3507: dictionary@footnote{We can't tell if it found them or not, but assume
                   3508: for now that it did not}. There is no match for this group of characters
                   3509: in the name dictionary, so it tries to treat them as a number. It is
                   3510: able to do this successfully, so it puts the number, 12, ``on the stack''
                   3511: (whatever that means).
                   3512: @item
                   3513: The text interpreter resumes scanning the line and gets the next group
                   3514: of characters, @code{dup}. It looks it up in the name dictionary and
                   3515: (you'll have to take my word for this) finds it, and executes the word
                   3516: @code{dup} (whatever that means).
                   3517: @item
                   3518: Once again, the text interpreter resumes scanning the line and gets the
                   3519: group of characters @code{fred}. It looks them up in the name
                   3520: dictionary, but can't find them. It tries to treat them as a number, but
                   3521: they don't represent any legal number.
                   3522: @end itemize
1.21      crook    3523: 
1.29      crook    3524: At this point, the text interpreter gives up and prints an error
                   3525: message. The error message shows exactly how far the text interpreter
                   3526: got in processing the line. In particular, it shows that the text
                   3527: interpreter made no attempt to do anything with the final character
                   3528: group, @code{dup}, even though we have good reason to believe that the
                   3529: text interpreter would have no problem looking that word up and
                   3530: executing it a second time.
1.21      crook    3531: 
                   3532: 
1.29      crook    3533: @comment ----------------------------------------------
                   3534: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
                   3535: @section Stacks, postfix notation and parameter passing
                   3536: @cindex text interpreter
                   3537: @cindex outer interpreter
1.21      crook    3538: 
1.29      crook    3539: In procedural programming languages (like C and Pascal), the
                   3540: building-block of programs is the @dfn{function} or @dfn{procedure}. These
                   3541: functions or procedures are called with @dfn{explicit parameters}. For
                   3542: example, in C we might write:
1.21      crook    3543: 
1.23      crook    3544: @example
1.29      crook    3545: total = total + new_volume(length,height,depth);
1.23      crook    3546: @end example
1.21      crook    3547: 
1.23      crook    3548: @noindent
1.29      crook    3549: where new_volume is a function-call to another piece of code, and total,
                   3550: length, height and depth are all variables. length, height and depth are
                   3551: parameters to the function-call.
1.21      crook    3552: 
1.29      crook    3553: In Forth, the equivalent of the function or procedure is the
                   3554: @dfn{definition} and parameters are implicitly passed between
                   3555: definitions using a shared stack that is visible to the
                   3556: programmer. Although Forth does support variables, the existence of the
                   3557: stack means that they are used far less often than in most other
                   3558: programming languages. When the text interpreter encounters a number, it
                   3559: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30      anton    3560: actual number is implementation-dependent ...) and the particular stack
1.29      crook    3561: used for any operation is implied unambiguously by the operation being
                   3562: performed. The stack used for all integer operations is called the @dfn{data
                   3563: stack} and, since this is the stack used most commonly, references to
                   3564: ``the data stack'' are often abbreviated to ``the stack''.
1.21      crook    3565: 
1.29      crook    3566: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21      crook    3567: 
1.23      crook    3568: @example
1.30      anton    3569: @kbd{1 2 3@key{RET}}  ok
1.23      crook    3570: @end example
1.21      crook    3571: 
1.29      crook    3572: Then this instructs the text interpreter to placed three numbers on the
                   3573: (data) stack. An analogy for the behaviour of the stack is to take a
                   3574: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
                   3575: the table. The 3 was the last card onto the pile (``last-in'') and if
                   3576: you take a card off the pile then, unless you're prepared to fiddle a
                   3577: bit, the card that you take off will be the 3 (``first-out''). The
                   3578: number that will be first-out of the stack is called the @dfn{top of
                   3579: stack}, which
                   3580: @cindex TOS definition
                   3581: is often abbreviated to @dfn{TOS}.
1.21      crook    3582: 
1.29      crook    3583: To understand how parameters are passed in Forth, consider the
                   3584: behaviour of the definition @code{+} (pronounced ``plus''). You will not
                   3585: be surprised to learn that this definition performs addition. More
                   3586: precisely, it adds two number together and produces a result. Where does
                   3587: it get the two numbers from? It takes the top two numbers off the
                   3588: stack. Where does it place the result? On the stack. You can act-out the
                   3589: behaviour of @code{+} with your playing cards like this:
1.21      crook    3590: 
                   3591: @itemize @bullet
                   3592: @item
1.29      crook    3593: Pick up two cards from the stack on the table
1.21      crook    3594: @item
1.29      crook    3595: Stare at them intently and ask yourself ``what @i{is} the sum of these two
                   3596: numbers''
1.21      crook    3597: @item
1.29      crook    3598: Decide that the answer is 5
1.21      crook    3599: @item
1.29      crook    3600: Shuffle the two cards back into the pack and find a 5
1.21      crook    3601: @item
1.29      crook    3602: Put a 5 on the remaining ace that's on the table.
1.21      crook    3603: @end itemize
                   3604: 
1.29      crook    3605: If you don't have a pack of cards handy but you do have Forth running,
                   3606: you can use the definition @code{.s} to show the current state of the stack,
                   3607: without affecting the stack. Type:
1.21      crook    3608: 
                   3609: @example
1.30      anton    3610: @kbd{clearstack 1 2 3@key{RET}} ok
                   3611: @kbd{.s@key{RET}} <3> 1 2 3  ok
1.23      crook    3612: @end example
                   3613: 
1.29      crook    3614: The text interpreter looks up the word @code{clearstack} and executes
                   3615: it; it tidies up the stack and removes any entries that may have been
                   3616: left on it by earlier examples. The text interpreter pushes each of the
                   3617: three numbers in turn onto the stack. Finally, the text interpreter
                   3618: looks up the word @code{.s} and executes it. The effect of executing
                   3619: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
                   3620: followed by a list of all the items on the stack; the item on the far
                   3621: right-hand side is the TOS.
1.21      crook    3622: 
1.29      crook    3623: You can now type:
1.21      crook    3624: 
1.29      crook    3625: @example
1.30      anton    3626: @kbd{+ .s@key{RET}} <2> 1 5  ok
1.29      crook    3627: @end example
1.21      crook    3628: 
1.29      crook    3629: @noindent
                   3630: which is correct; there are now 2 items on the stack and the result of
                   3631: the addition is 5.
1.23      crook    3632: 
1.29      crook    3633: If you're playing with cards, try doing a second addition: pick up the
                   3634: two cards, work out that their sum is 6, shuffle them into the pack,
                   3635: look for a 6 and place that on the table. You now have just one item on
                   3636: the stack. What happens if you try to do a third addition? Pick up the
                   3637: first card, pick up the second card -- ah! There is no second card. This
                   3638: is called a @dfn{stack underflow} and consitutes an error. If you try to
                   3639: do the same thing with Forth it will report an error (probably a Stack
                   3640: Underflow or an Invalid Memory Address error).
1.23      crook    3641: 
1.29      crook    3642: The opposite situation to a stack underflow is a @dfn{stack overflow},
                   3643: which simply accepts that there is a finite amount of storage space
                   3644: reserved for the stack. To stretch the playing card analogy, if you had
                   3645: enough packs of cards and you piled the cards up on the table, you would
                   3646: eventually be unable to add another card; you'd hit the ceiling. Gforth
                   3647: allows you to set the maximum size of the stacks. In general, the only
                   3648: time that you will get a stack overflow is because a definition has a
                   3649: bug in it and is generating data on the stack uncontrollably.
1.23      crook    3650: 
1.29      crook    3651: There's one final use for the playing card analogy. If you model your
                   3652: stack using a pack of playing cards, the maximum number of items on
                   3653: your stack will be 52 (I assume you didn't use the Joker). The maximum
                   3654: @i{value} of any item on the stack is 13 (the King). In fact, the only
                   3655: possible numbers are positive integer numbers 1 through 13; you can't
                   3656: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
                   3657: think about some of the cards, you can accommodate different
                   3658: numbers. For example, you could think of the Jack as representing 0,
                   3659: the Queen as representing -1 and the King as representing -2. Your
1.45      crook    3660: @i{range} remains unchanged (you can still only represent a total of 13
1.29      crook    3661: numbers) but the numbers that you can represent are -2 through 10.
1.28      crook    3662: 
1.29      crook    3663: In that analogy, the limit was the amount of information that a single
                   3664: stack entry could hold, and Forth has a similar limit. In Forth, the
                   3665: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
                   3666: implementation dependent and affects the maximum value that a stack
                   3667: entry can hold. A Standard Forth provides a cell size of at least
                   3668: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21      crook    3669: 
1.29      crook    3670: Forth does not do any type checking for you, so you are free to
                   3671: manipulate and combine stack items in any way you wish. A convenient way
                   3672: of treating stack items is as 2's complement signed integers, and that
                   3673: is what Standard words like @code{+} do. Therefore you can type:
1.21      crook    3674: 
1.29      crook    3675: @example
1.30      anton    3676: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
1.29      crook    3677: @end example
1.21      crook    3678: 
1.29      crook    3679: If you use numbers and definitions like @code{+} in order to turn Forth
                   3680: into a great big pocket calculator, you will realise that it's rather
                   3681: different from a normal calculator. Rather than typing 2 + 3 = you had
                   3682: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
                   3683: result). The terminology used to describe this difference is to say that
                   3684: your calculator uses @dfn{Infix Notation} (parameters and operators are
                   3685: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
                   3686: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21      crook    3687: 
1.29      crook    3688: Whilst postfix notation might look confusing to begin with, it has
                   3689: several important advantages:
1.21      crook    3690: 
1.23      crook    3691: @itemize @bullet
                   3692: @item
1.29      crook    3693: it is unambiguous
1.23      crook    3694: @item
1.29      crook    3695: it is more concise
1.23      crook    3696: @item
1.29      crook    3697: it fits naturally with a stack-based system
1.23      crook    3698: @end itemize
1.21      crook    3699: 
1.29      crook    3700: To examine these claims in more detail, consider these sums:
1.21      crook    3701: 
1.29      crook    3702: @example
                   3703: 6 + 5 * 4 =
                   3704: 4 * 5 + 6 =
                   3705: @end example
1.21      crook    3706: 
1.29      crook    3707: If you're just learning maths or your maths is very rusty, you will
                   3708: probably come up with the answer 44 for the first and 26 for the
                   3709: second. If you are a bit of a whizz at maths you will remember the
                   3710: @i{convention} that multiplication takes precendence over addition, and
                   3711: you'd come up with the answer 26 both times. To explain the answer 26
                   3712: to someone who got the answer 44, you'd probably rewrite the first sum
                   3713: like this:
1.21      crook    3714: 
1.29      crook    3715: @example
                   3716: 6 + (5 * 4) =
                   3717: @end example
1.21      crook    3718: 
1.29      crook    3719: If what you really wanted was to perform the addition before the
                   3720: multiplication, you would have to use parentheses to force it.
1.21      crook    3721: 
1.29      crook    3722: If you did the first two sums on a pocket calculator you would probably
                   3723: get the right answers, unless you were very cautious and entered them using
                   3724: these keystroke sequences:
1.21      crook    3725: 
1.29      crook    3726: 6 + 5 = * 4 =
                   3727: 4 * 5 = + 6 =
1.21      crook    3728: 
1.29      crook    3729: Postfix notation is unambiguous because the order that the operators
                   3730: are applied is always explicit; that also means that parentheses are
                   3731: never required. The operators are @i{active} (the act of quoting the
                   3732: operator makes the operation occur) which removes the need for ``=''.
1.28      crook    3733: 
1.29      crook    3734: The sum 6 + 5 * 4 can be written (in postfix notation) in two
                   3735: equivalent ways:
1.26      crook    3736: 
                   3737: @example
1.29      crook    3738: 6 5 4 * +      or:
                   3739: 5 4 * 6 +
1.26      crook    3740: @end example
1.23      crook    3741: 
1.29      crook    3742: An important thing that you should notice about this notation is that
                   3743: the @i{order} of the numbers does not change; if you want to subtract
                   3744: 2 from 10 you type @code{10 2 -}.
1.1       anton    3745: 
1.29      crook    3746: The reason that Forth uses postfix notation is very simple to explain: it
                   3747: makes the implementation extremely simple, and it follows naturally from
                   3748: using the stack as a mechanism for passing parameters. Another way of
                   3749: thinking about this is to realise that all Forth definitions are
                   3750: @i{active}; they execute as they are encountered by the text
                   3751: interpreter. The result of this is that the syntax of Forth is trivially
                   3752: simple.
1.1       anton    3753: 
                   3754: 
                   3755: 
1.29      crook    3756: @comment ----------------------------------------------
                   3757: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
                   3758: @section Your first Forth definition
                   3759: @cindex first definition
1.1       anton    3760: 
1.29      crook    3761: Until now, the examples we've seen have been trivial; we've just been
                   3762: using Forth as a bigger-than-pocket calculator. Also, each calculation
                   3763: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
                   3764: again@footnote{That's not quite true. If you press the up-arrow key on
                   3765: your keyboard you should be able to scroll back to any earlier command,
                   3766: edit it and re-enter it.} In this section we'll see how to add new
                   3767: words to Forth's vocabulary.
1.1       anton    3768: 
1.29      crook    3769: The easiest way to create a new word is to use a @dfn{colon
                   3770: definition}. We'll define a few and try them out before worrying too
                   3771: much about how they work. Try typing in these examples; be careful to
                   3772: copy the spaces accurately:
1.1       anton    3773: 
1.29      crook    3774: @example
                   3775: : add-two 2 + . ;
                   3776: : greet ." Hello and welcome" ;
                   3777: : demo 5 add-two ;
                   3778: @end example
1.1       anton    3779: 
1.29      crook    3780: @noindent
                   3781: Now try them out:
1.1       anton    3782: 
1.29      crook    3783: @example
1.30      anton    3784: @kbd{greet@key{RET}} Hello and welcome  ok
                   3785: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
                   3786: @kbd{4 add-two@key{RET}} 6  ok
                   3787: @kbd{demo@key{RET}} 7  ok
                   3788: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
1.29      crook    3789: @end example
1.1       anton    3790: 
1.29      crook    3791: The first new thing that we've introduced here is the pair of words
                   3792: @code{:} and @code{;}. These are used to start and terminate a new
                   3793: definition, respectively. The first word after the @code{:} is the name
                   3794: for the new definition.
1.1       anton    3795: 
1.29      crook    3796: As you can see from the examples, a definition is built up of words that
                   3797: have already been defined; Forth makes no distinction between
                   3798: definitions that existed when you started the system up, and those that
                   3799: you define yourself.
1.1       anton    3800: 
1.29      crook    3801: The examples also introduce the words @code{.} (dot), @code{."}
                   3802: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
                   3803: the stack and displays it. It's like @code{.s} except that it only
                   3804: displays the top item of the stack and it is destructive; after it has
                   3805: executed, the number is no longer on the stack. There is always one
                   3806: space printed after the number, and no spaces before it. Dot-quote
                   3807: defines a string (a sequence of characters) that will be printed when
                   3808: the word is executed. The string can contain any printable characters
                   3809: except @code{"}. A @code{"} has a special function; it is not a Forth
                   3810: word but it acts as a delimiter (the way that delimiters work is
                   3811: described in the next section). Finally, @code{dup} duplicates the value
                   3812: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1       anton    3813: 
1.29      crook    3814: We already know that the text interpreter searches through the
                   3815: dictionary to locate names. If you've followed the examples earlier, you
                   3816: will already have a definition called @code{add-two}. Lets try modifying
                   3817: it by typing in a new definition:
1.1       anton    3818: 
1.29      crook    3819: @example
1.30      anton    3820: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
1.29      crook    3821: @end example
1.5       anton    3822: 
1.29      crook    3823: Forth recognised that we were defining a word that already exists, and
                   3824: printed a message to warn us of that fact. Let's try out the new
                   3825: definition:
1.5       anton    3826: 
1.29      crook    3827: @example
1.30      anton    3828: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
1.29      crook    3829: @end example
1.1       anton    3830: 
1.29      crook    3831: @noindent
                   3832: All that we've actually done here, though, is to create a new
                   3833: definition, with a particular name. The fact that there was already a
                   3834: definition with the same name did not make any difference to the way
                   3835: that the new definition was created (except that Forth printed a warning
                   3836: message). The old definition of add-two still exists (try @code{demo}
                   3837: again to see that this is true). Any new definition will use the new
                   3838: definition of @code{add-two}, but old definitions continue to use the
                   3839: version that already existed at the time that they were @code{compiled}.
1.1       anton    3840: 
1.29      crook    3841: Before you go on to the next section, try defining and redefining some
                   3842: words of your own.
1.1       anton    3843: 
1.29      crook    3844: @comment ----------------------------------------------
                   3845: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
                   3846: @section How does that work?
                   3847: @cindex parsing words
1.1       anton    3848: 
1.30      anton    3849: @c That's pretty deep (IMO way too deep) for an introduction. - anton
                   3850: 
                   3851: @c Is it a good idea to talk about the interpretation semantics of a
                   3852: @c number? We don't have an xt to go along with it. - anton
                   3853: 
                   3854: @c Now that I have eliminated execution semantics, I wonder if it would not
                   3855: @c be better to keep them (or add run-time semantics), to make it easier to
                   3856: @c explain what compilation semantics usually does. - anton
                   3857: 
1.44      crook    3858: @c nac-> I removed the term ``default compilation sematics'' from the
                   3859: @c introductory chapter. Removing ``execution semantics'' was making
                   3860: @c everything simpler to explain, then I think the use of this term made
                   3861: @c everything more complex again. I replaced it with ``default
                   3862: @c semantics'' (which is used elsewhere in the manual) by which I mean
                   3863: @c ``a definition that has neither the immediate nor the compile-only
                   3864: @c flag set''. I reworded big chunks of the ``how does that work''
                   3865: @c section (and, unusually for me, I think I even made it shorter!).  See
                   3866: @c what you think -- I know I have not addressed your primary concern
                   3867: @c that it is too heavy-going for an introduction. From what I understood
                   3868: @c of your course notes it looks as though they might be a good framework. 
                   3869: @c Things that I've tried to capture here are some things that came as a
                   3870: @c great revelation here when I first understood them. Also, I like the
                   3871: @c fact that a very simple code example shows up almost all of the issues
                   3872: @c that you need to understand to see how Forth works. That's unique and
                   3873: @c worthwhile to emphasise.
                   3874: 
1.29      crook    3875: Now we're going to take another look at the definition of @code{add-two}
                   3876: from the previous section. From our knowledge of the way that the text
                   3877: interpreter works, we would have expected this result when we tried to
                   3878: define @code{add-two}:
1.21      crook    3879: 
1.29      crook    3880: @example
1.44      crook    3881: @kbd{: add-two 2 + . ;@key{RET}}
1.29      crook    3882:   ^^^^^^^
                   3883: Error: Undefined word
                   3884: @end example
1.28      crook    3885: 
1.29      crook    3886: The reason that this didn't happen is bound up in the way that @code{:}
                   3887: works. The word @code{:} does two special things. The first special
                   3888: thing that it does prevents the text interpreter from ever seeing the
                   3889: characters @code{add-two}. The text interpreter uses a variable called
                   3890: @cindex modifying >IN
1.44      crook    3891: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29      crook    3892: input line. When it encounters the word @code{:} it behaves in exactly
                   3893: the same way as it does for any other word; it looks it up in the name
                   3894: dictionary, finds its xt and executes it. When @code{:} executes, it
                   3895: looks at the input buffer, finds the word @code{add-two} and advances the
                   3896: value of @code{>IN} to point past it. It then does some other stuff
                   3897: associated with creating the new definition (including creating an entry
                   3898: for @code{add-two} in the name dictionary). When the execution of @code{:}
                   3899: completes, control returns to the text interpreter, which is oblivious
                   3900: to the fact that it has been tricked into ignoring part of the input
                   3901: line.
1.21      crook    3902: 
1.29      crook    3903: @cindex parsing words
                   3904: Words like @code{:} -- words that advance the value of @code{>IN} and so
                   3905: prevent the text interpreter from acting on the whole of the input line
                   3906: -- are called @dfn{parsing words}.
1.21      crook    3907: 
1.29      crook    3908: @cindex @code{state} - effect on the text interpreter
                   3909: @cindex text interpreter - effect of state
                   3910: The second special thing that @code{:} does is change the value of a
                   3911: variable called @code{state}, which affects the way that the text
                   3912: interpreter behaves. When Gforth starts up, @code{state} has the value
                   3913: 0, and the text interpreter is said to be @dfn{interpreting}. During a
                   3914: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44      crook    3915: the text interpreter is said to be @dfn{compiling}.
                   3916: 
                   3917: In this example, the text interpreter is compiling when it processes the
                   3918: string ``@code{2 + . ;}''. It still breaks the string down into
                   3919: character sequences in the same way. However, instead of pushing the
                   3920: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
                   3921: into the definition of @code{add-two} that will make the number @code{2} get
                   3922: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
                   3923: the behaviours of @code{+} and @code{.} are also compiled into the
                   3924: definition.
                   3925: 
                   3926: One category of words don't get compiled. These so-called @dfn{immediate
                   3927: words} get executed (performed @i{now}) regardless of whether the text
                   3928: interpreter is interpreting or compiling. The word @code{;} is an
                   3929: immediate word. Rather than being compiled into the definition, it
                   3930: executes. Its effect is to terminate the current definition, which
                   3931: includes changing the value of @code{state} back to 0.
                   3932: 
                   3933: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
                   3934: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
                   3935: definition.
1.28      crook    3936: 
1.30      anton    3937: In Forth, every word or number can be described in terms of two
1.29      crook    3938: properties:
1.28      crook    3939: 
                   3940: @itemize @bullet
                   3941: @item
1.29      crook    3942: @cindex interpretation semantics
1.44      crook    3943: Its @dfn{interpretation semantics} describe how it will behave when the
                   3944: text interpreter encounters it in @dfn{interpret} state. The
                   3945: interpretation semantics of a word are represented by an @dfn{execution
                   3946: token}.
1.28      crook    3947: @item
1.29      crook    3948: @cindex compilation semantics
1.44      crook    3949: Its @dfn{compilation semantics} describe how it will behave when the
                   3950: text interpreter encounters it in @dfn{compile} state. The compilation
                   3951: semantics of a word are represented in an implementation-dependent way;
                   3952: Gforth uses a @dfn{compilation token}.
1.29      crook    3953: @end itemize
                   3954: 
                   3955: @noindent
                   3956: Numbers are always treated in a fixed way:
                   3957: 
                   3958: @itemize @bullet
1.28      crook    3959: @item
1.44      crook    3960: When the number is @dfn{interpreted}, its behaviour is to push the
                   3961: number onto the stack.
1.28      crook    3962: @item
1.30      anton    3963: When the number is @dfn{compiled}, a piece of code is appended to the
                   3964: current definition that pushes the number when it runs. (In other words,
                   3965: the compilation semantics of a number are to postpone its interpretation
                   3966: semantics until the run-time of the definition that it is being compiled
                   3967: into.)
1.29      crook    3968: @end itemize
                   3969: 
1.44      crook    3970: Words don't behave in such a regular way, but most have @i{default
                   3971: semantics} which means that they behave like this:
1.29      crook    3972: 
                   3973: @itemize @bullet
1.28      crook    3974: @item
1.30      anton    3975: The @dfn{interpretation semantics} of the word are to do something useful.
                   3976: @item
1.29      crook    3977: The @dfn{compilation semantics} of the word are to append its
1.30      anton    3978: @dfn{interpretation semantics} to the current definition (so that its
                   3979: run-time behaviour is to do something useful).
1.28      crook    3980: @end itemize
                   3981: 
1.30      anton    3982: @cindex immediate words
1.44      crook    3983: The actual behaviour of any particular word can be controlled by using
                   3984: the words @code{immediate} and @code{compile-only} when the word is
                   3985: defined. These words set flags in the name dictionary entry of the most
                   3986: recently defined word, and these flags are retrieved by the text
                   3987: interpreter when it finds the word in the name dictionary.
                   3988: 
                   3989: A word that is marked as @dfn{immediate} has compilation semantics that
                   3990: are identical to its interpretation semantics. In other words, it
                   3991: behaves like this:
1.29      crook    3992: 
                   3993: @itemize @bullet
                   3994: @item
1.30      anton    3995: The @dfn{interpretation semantics} of the word are to do something useful.
1.29      crook    3996: @item
1.30      anton    3997: The @dfn{compilation semantics} of the word are to do something useful
                   3998: (and actually the same thing); i.e., it is executed during compilation.
1.29      crook    3999: @end itemize
1.28      crook    4000: 
1.44      crook    4001: Marking a word as @dfn{compile-only} prohibits the text interpreter from
                   4002: performing the interpretation semantics of the word directly; an attempt
                   4003: to do so will generate an error. It is never necessary to use
                   4004: @code{compile-only} (and it is not even part of ANS Forth, though it is
                   4005: provided by many implementations) but it is good etiquette to apply it
                   4006: to a word that will not behave correctly (and might have unexpected
                   4007: side-effects) in interpret state. For example, it is only legal to use
                   4008: the conditional word @code{IF} within a definition. If you forget this
                   4009: and try to use it elsewhere, the fact that (in Gforth) it is marked as
                   4010: @code{compile-only} allows the text interpreter to generate a helpful
                   4011: error message rather than subjecting you to the consequences of your
                   4012: folly.
                   4013: 
1.29      crook    4014: This example shows the difference between an immediate and a
                   4015: non-immediate word:
1.28      crook    4016: 
1.29      crook    4017: @example
                   4018: : show-state state @@ . ;
                   4019: : show-state-now show-state ; immediate
                   4020: : word1 show-state ;
                   4021: : word2 show-state-now ;
1.28      crook    4022: @end example
1.23      crook    4023: 
1.29      crook    4024: The word @code{immediate} after the definition of @code{show-state-now}
                   4025: makes that word an immediate word. These definitions introduce a new
                   4026: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
                   4027: variable, and leaves it on the stack. Therefore, the behaviour of
                   4028: @code{show-state} is to print a number that represents the current value
                   4029: of @code{state}.
1.28      crook    4030: 
1.29      crook    4031: When you execute @code{word1}, it prints the number 0, indicating that
                   4032: the system is interpreting. When the text interpreter compiled the
                   4033: definition of @code{word1}, it encountered @code{show-state} whose
1.30      anton    4034: compilation semantics are to append its interpretation semantics to the
1.29      crook    4035: current definition. When you execute @code{word1}, it performs the
1.30      anton    4036: interpretation semantics of @code{show-state}.  At the time that @code{word1}
1.29      crook    4037: (and therefore @code{show-state}) are executed, the system is
                   4038: interpreting.
1.28      crook    4039: 
1.30      anton    4040: When you pressed @key{RET} after entering the definition of @code{word2},
1.29      crook    4041: you should have seen the number -1 printed, followed by ``@code{
                   4042: ok}''. When the text interpreter compiled the definition of
                   4043: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30      anton    4044: whose compilation semantics are therefore to perform its interpretation
1.29      crook    4045: semantics. It is executed straight away (even before the text
                   4046: interpreter has moved on to process another group of characters; the
                   4047: @code{;} in this example). The effect of executing it are to display the
                   4048: value of @code{state} @i{at the time that the definition of}
                   4049: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
                   4050: system is compiling at this time. If you execute @code{word2} it does
                   4051: nothing at all.
1.28      crook    4052: 
1.29      crook    4053: @cindex @code{."}, how it works
                   4054: Before leaving the subject of immediate words, consider the behaviour of
                   4055: @code{."} in the definition of @code{greet}, in the previous
                   4056: section. This word is both a parsing word and an immediate word. Notice
                   4057: that there is a space between @code{."} and the start of the text
                   4058: @code{Hello and welcome}, but that there is no space between the last
                   4059: letter of @code{welcome} and the @code{"} character. The reason for this
                   4060: is that @code{."} is a Forth word; it must have a space after it so that
                   4061: the text interpreter can identify it. The @code{"} is not a Forth word;
                   4062: it is a @dfn{delimiter}. The examples earlier show that, when the string
                   4063: is displayed, there is neither a space before the @code{H} nor after the
                   4064: @code{e}. Since @code{."} is an immediate word, it executes at the time
                   4065: that @code{greet} is defined. When it executes, its behaviour is to
                   4066: search forward in the input line looking for the delimiter. When it
                   4067: finds the delimiter, it updates @code{>IN} to point past the
                   4068: delimiter. It also compiles some magic code into the definition of
                   4069: @code{greet}; the xt of a run-time routine that prints a text string. It
                   4070: compiles the string @code{Hello and welcome} into memory so that it is
                   4071: available to be printed later. When the text interpreter gains control,
                   4072: the next word it finds in the input stream is @code{;} and so it
                   4073: terminates the definition of @code{greet}.
1.28      crook    4074: 
                   4075: 
                   4076: @comment ----------------------------------------------
1.29      crook    4077: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
                   4078: @section Forth is written in Forth
                   4079: @cindex structure of Forth programs
                   4080: 
                   4081: When you start up a Forth compiler, a large number of definitions
                   4082: already exist. In Forth, you develop a new application using bottom-up
                   4083: programming techniques to create new definitions that are defined in
                   4084: terms of existing definitions. As you create each definition you can
                   4085: test and debug it interactively.
                   4086: 
                   4087: If you have tried out the examples in this section, you will probably
                   4088: have typed them in by hand; when you leave Gforth, your definitions will
                   4089: be lost. You can avoid this by using a text editor to enter Forth source
                   4090: code into a file, and then loading code from the file using
1.49      anton    4091: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29      crook    4092: processed by the text interpreter, just as though you had typed it in by
                   4093: hand@footnote{Actually, there are some subtle differences -- see
                   4094: @ref{The Text Interpreter}.}.
                   4095: 
                   4096: Gforth also supports the traditional Forth alternative to using text
1.49      anton    4097: files for program entry (@pxref{Blocks}).
1.28      crook    4098: 
1.29      crook    4099: In common with many, if not most, Forth compilers, most of Gforth is
                   4100: actually written in Forth. All of the @file{.fs} files in the
                   4101: installation directory@footnote{For example,
1.30      anton    4102: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29      crook    4103: study to see examples of Forth programming.
1.28      crook    4104: 
1.29      crook    4105: Gforth maintains a history file that records every line that you type to
                   4106: the text interpreter. This file is preserved between sessions, and is
                   4107: used to provide a command-line recall facility. If you enter long
                   4108: definitions by hand, you can use a text editor to paste them out of the
                   4109: history file into a Forth source file for reuse at a later time
1.49      anton    4110: (for more information @pxref{Command-line editing}).
1.28      crook    4111: 
                   4112: 
                   4113: @comment ----------------------------------------------
1.29      crook    4114: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
                   4115: @section Review - elements of a Forth system
                   4116: @cindex elements of a Forth system
1.28      crook    4117: 
1.29      crook    4118: To summarise this chapter:
1.28      crook    4119: 
                   4120: @itemize @bullet
                   4121: @item
1.29      crook    4122: Forth programs use @dfn{factoring} to break a problem down into small
                   4123: fragments called @dfn{words} or @dfn{definitions}.
                   4124: @item
                   4125: Forth program development is an interactive process.
                   4126: @item
                   4127: The main command loop that accepts input, and controls both
                   4128: interpretation and compilation, is called the @dfn{text interpreter}
                   4129: (also known as the @dfn{outer interpreter}).
                   4130: @item
                   4131: Forth has a very simple syntax, consisting of words and numbers
                   4132: separated by spaces or carriage-return characters. Any additional syntax
                   4133: is imposed by @dfn{parsing words}.
                   4134: @item
                   4135: Forth uses a stack to pass parameters between words. As a result, it
                   4136: uses postfix notation.
                   4137: @item
                   4138: To use a word that has previously been defined, the text interpreter
                   4139: searches for the word in the @dfn{name dictionary}.
                   4140: @item
1.30      anton    4141: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28      crook    4142: @item
1.29      crook    4143: The text interpreter uses the value of @code{state} to select between
                   4144: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
                   4145: semantics} of a word that it encounters.
1.28      crook    4146: @item
1.30      anton    4147: The relationship between the @dfn{interpretation semantics} and
                   4148: @dfn{compilation semantics} for a word
1.29      crook    4149: depend upon the way in which the word was defined (for example, whether
                   4150: it is an @dfn{immediate} word).
1.28      crook    4151: @item
1.29      crook    4152: Forth definitions can be implemented in Forth (called @dfn{high-level
                   4153: definitions}) or in some other way (usually a lower-level language and
                   4154: as a result often called @dfn{low-level definitions}, @dfn{code
                   4155: definitions} or @dfn{primitives}).
1.28      crook    4156: @item
1.29      crook    4157: Many Forth systems are implemented mainly in Forth.
1.28      crook    4158: @end itemize
                   4159: 
                   4160: 
1.29      crook    4161: @comment ----------------------------------------------
1.48      anton    4162: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29      crook    4163: @section Where To Go Next
                   4164: @cindex where to go next
1.28      crook    4165: 
1.29      crook    4166: Amazing as it may seem, if you have read (and understood) this far, you
                   4167: know almost all the fundamentals about the inner workings of a Forth
                   4168: system. You certainly know enough to be able to read and understand the
                   4169: rest of this manual and the ANS Forth document, to learn more about the
                   4170: facilities that Forth in general and Gforth in particular provide. Even
                   4171: scarier, you know almost enough to implement your own Forth system.
1.30      anton    4172: However, that's not a good idea just yet... better to try writing some
1.29      crook    4173: programs in Gforth.
1.28      crook    4174: 
1.29      crook    4175: Forth has such a rich vocabulary that it can be hard to know where to
                   4176: start in learning it. This section suggests a few sets of words that are
                   4177: enough to write small but useful programs. Use the word index in this
                   4178: document to learn more about each word, then try it out and try to write
                   4179: small definitions using it. Start by experimenting with these words:
1.28      crook    4180: 
                   4181: @itemize @bullet
                   4182: @item
1.29      crook    4183: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
                   4184: @item
                   4185: Comparison: @code{MIN MAX =}
                   4186: @item
                   4187: Logic: @code{AND OR XOR NOT}
                   4188: @item
                   4189: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28      crook    4190: @item
1.29      crook    4191: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28      crook    4192: @item
1.29      crook    4193: Input/Output: @code{. ." EMIT CR KEY}
1.28      crook    4194: @item
1.29      crook    4195: Defining words: @code{: ; CREATE}
1.28      crook    4196: @item
1.29      crook    4197: Memory allocation words: @code{ALLOT ,}
1.28      crook    4198: @item
1.29      crook    4199: Tools: @code{SEE WORDS .S MARKER}
                   4200: @end itemize
                   4201: 
                   4202: When you have mastered those, go on to:
                   4203: 
                   4204: @itemize @bullet
1.28      crook    4205: @item
1.29      crook    4206: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28      crook    4207: @item
1.29      crook    4208: Memory access: @code{@@ !}
1.28      crook    4209: @end itemize
1.23      crook    4210: 
1.29      crook    4211: When you have mastered these, there's nothing for it but to read through
                   4212: the whole of this manual and find out what you've missed.
                   4213: 
                   4214: @comment ----------------------------------------------
1.48      anton    4215: @node Exercises,  , Where to go next, Introduction
1.29      crook    4216: @section Exercises
                   4217: @cindex exercises
                   4218: 
                   4219: TODO: provide a set of programming excercises linked into the stuff done
                   4220: already and into other sections of the manual. Provide solutions to all
                   4221: the exercises in a .fs file in the distribution.
                   4222: 
                   4223: @c Get some inspiration from Starting Forth and Kelly&Spies.
                   4224: 
                   4225: @c excercises:
                   4226: @c 1. take inches and convert to feet and inches.
                   4227: @c 2. take temperature and convert from fahrenheight to celcius;
                   4228: @c    may need to care about symmetric vs floored??
                   4229: @c 3. take input line and do character substitution
                   4230: @c    to encipher or decipher
                   4231: @c 4. as above but work on a file for in and out
                   4232: @c 5. take input line and convert to pig-latin 
                   4233: @c
                   4234: @c thing of sets of things to exercise then come up with
                   4235: @c problems that need those things.
                   4236: 
                   4237: 
1.26      crook    4238: @c ******************************************************************
1.29      crook    4239: @node Words, Error messages, Introduction, Top
1.1       anton    4240: @chapter Forth Words
1.26      crook    4241: @cindex words
1.1       anton    4242: 
                   4243: @menu
                   4244: * Notation::                    
1.21      crook    4245: * Comments::
                   4246: * Boolean Flags::
1.1       anton    4247: * Arithmetic::                  
                   4248: * Stack Manipulation::          
1.5       anton    4249: * Memory::                      
1.1       anton    4250: * Control Structures::          
                   4251: * Defining Words::              
1.47      crook    4252: * Interpretation and Compilation Semantics::
                   4253: * Tokens for Words::            
1.21      crook    4254: * The Text Interpreter::
                   4255: * Word Lists::                   
                   4256: * Environmental Queries::
1.12      anton    4257: * Files::                       
                   4258: * Blocks::                      
                   4259: * Other I/O::                   
                   4260: * Programming Tools::           
                   4261: * Assembler and Code Words::    
                   4262: * Threading Words::             
1.26      crook    4263: * Locals::                      
                   4264: * Structures::                  
                   4265: * Object-oriented Forth::       
1.21      crook    4266: * Passing Commands to the OS::
1.47      crook    4267: * Keeping track of Time::
1.21      crook    4268: * Miscellaneous Words::
1.1       anton    4269: @end menu
                   4270: 
1.21      crook    4271: @node Notation, Comments, Words, Words
1.1       anton    4272: @section Notation
                   4273: @cindex notation of glossary entries
                   4274: @cindex format of glossary entries
                   4275: @cindex glossary notation format
                   4276: @cindex word glossary entry format
                   4277: 
                   4278: The Forth words are described in this section in the glossary notation
                   4279: that has become a de-facto standard for Forth texts, i.e.,
                   4280: 
                   4281: @format
1.29      crook    4282: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
1.1       anton    4283: @end format
1.29      crook    4284: @i{Description}
1.1       anton    4285: 
                   4286: @table @var
                   4287: @item word
1.28      crook    4288: The name of the word.
1.1       anton    4289: 
                   4290: @item Stack effect
                   4291: @cindex stack effect
1.29      crook    4292: The stack effect is written in the notation @code{@i{before} --
                   4293: @i{after}}, where @i{before} and @i{after} describe the top of
1.1       anton    4294: stack entries before and after the execution of the word. The rest of
                   4295: the stack is not touched by the word. The top of stack is rightmost,
                   4296: i.e., a stack sequence is written as it is typed in. Note that Gforth
                   4297: uses a separate floating point stack, but a unified stack
1.29      crook    4298: notation. Also, return stack effects are not shown in @i{stack
                   4299: effect}, but in @i{Description}. The name of a stack item describes
1.1       anton    4300: the type and/or the function of the item. See below for a discussion of
                   4301: the types.
                   4302: 
                   4303: All words have two stack effects: A compile-time stack effect and a
                   4304: run-time stack effect. The compile-time stack-effect of most words is
1.29      crook    4305: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1       anton    4306: this standard behaviour, or the word does other unusual things at
                   4307: compile time, both stack effects are shown; otherwise only the run-time
                   4308: stack effect is shown.
                   4309: 
                   4310: @cindex pronounciation of words
                   4311: @item pronunciation
                   4312: How the word is pronounced.
                   4313: 
                   4314: @cindex wordset
                   4315: @item wordset
1.21      crook    4316: The ANS Forth standard is divided into several word sets. A standard
                   4317: system need not support all of them. Therefore, in theory, the fewer
                   4318: word sets your program uses the more portable it will be. However, we
                   4319: suspect that most ANS Forth systems on personal machines will feature
1.26      crook    4320: all word sets. Words that are not defined in ANS Forth have
1.21      crook    4321: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1       anton    4322: describes words that will work in future releases of Gforth;
                   4323: @code{gforth-internal} words are more volatile. Environmental query
                   4324: strings are also displayed like words; you can recognize them by the
1.21      crook    4325: @code{environment} in the word set field.
1.1       anton    4326: 
                   4327: @item Description
                   4328: A description of the behaviour of the word.
                   4329: @end table
                   4330: 
                   4331: @cindex types of stack items
                   4332: @cindex stack item types
                   4333: The type of a stack item is specified by the character(s) the name
                   4334: starts with:
                   4335: 
                   4336: @table @code
                   4337: @item f
                   4338: @cindex @code{f}, stack item type
                   4339: Boolean flags, i.e. @code{false} or @code{true}.
                   4340: @item c
                   4341: @cindex @code{c}, stack item type
                   4342: Char
                   4343: @item w
                   4344: @cindex @code{w}, stack item type
                   4345: Cell, can contain an integer or an address
                   4346: @item n
                   4347: @cindex @code{n}, stack item type
                   4348: signed integer
                   4349: @item u
                   4350: @cindex @code{u}, stack item type
                   4351: unsigned integer
                   4352: @item d
                   4353: @cindex @code{d}, stack item type
                   4354: double sized signed integer
                   4355: @item ud
                   4356: @cindex @code{ud}, stack item type
                   4357: double sized unsigned integer
                   4358: @item r
                   4359: @cindex @code{r}, stack item type
                   4360: Float (on the FP stack)
1.21      crook    4361: @item a-
1.1       anton    4362: @cindex @code{a_}, stack item type
                   4363: Cell-aligned address
1.21      crook    4364: @item c-
1.1       anton    4365: @cindex @code{c_}, stack item type
                   4366: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21      crook    4367: @item f-
1.1       anton    4368: @cindex @code{f_}, stack item type
                   4369: Float-aligned address
1.21      crook    4370: @item df-
1.1       anton    4371: @cindex @code{df_}, stack item type
                   4372: Address aligned for IEEE double precision float
1.21      crook    4373: @item sf-
1.1       anton    4374: @cindex @code{sf_}, stack item type
                   4375: Address aligned for IEEE single precision float
                   4376: @item xt
                   4377: @cindex @code{xt}, stack item type
                   4378: Execution token, same size as Cell
                   4379: @item wid
                   4380: @cindex @code{wid}, stack item type
1.21      crook    4381: Word list ID, same size as Cell
1.1       anton    4382: @item f83name
                   4383: @cindex @code{f83name}, stack item type
                   4384: Pointer to a name structure
                   4385: @item "
                   4386: @cindex @code{"}, stack item type
1.12      anton    4387: string in the input stream (not on the stack). The terminating character
                   4388: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1       anton    4389: quotes.
                   4390: @end table
                   4391: 
1.21      crook    4392: @node Comments, Boolean Flags, Notation, Words
                   4393: @section Comments
1.26      crook    4394: @cindex comments
1.21      crook    4395: 
1.29      crook    4396: Forth supports two styles of comment; the traditional @i{in-line} comment,
                   4397: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21      crook    4398: 
1.44      crook    4399: 
1.23      crook    4400: doc-(
1.21      crook    4401: doc-\
1.23      crook    4402: doc-\G
1.21      crook    4403: 
1.44      crook    4404: 
1.21      crook    4405: @node Boolean Flags, Arithmetic, Comments, Words
                   4406: @section Boolean Flags
1.26      crook    4407: @cindex Boolean flags
1.21      crook    4408: 
                   4409: A Boolean flag is cell-sized. A cell with all bits clear represents the
                   4410: flag @code{false} and a flag with all bits set represents the flag
1.26      crook    4411: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29      crook    4412: a cell that has @i{any} bit set as @code{true}.
1.21      crook    4413: 
1.44      crook    4414: 
1.21      crook    4415: doc-true
                   4416: doc-false
1.29      crook    4417: doc-on
                   4418: doc-off
1.21      crook    4419: 
1.44      crook    4420: 
1.21      crook    4421: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1       anton    4422: @section Arithmetic
                   4423: @cindex arithmetic words
                   4424: 
                   4425: @cindex division with potentially negative operands
                   4426: Forth arithmetic is not checked, i.e., you will not hear about integer
                   4427: overflow on addition or multiplication, you may hear about division by
                   4428: zero if you are lucky. The operator is written after the operands, but
                   4429: the operands are still in the original order. I.e., the infix @code{2-1}
                   4430: corresponds to @code{2 1 -}. Forth offers a variety of division
                   4431: operators. If you perform division with potentially negative operands,
                   4432: you do not want to use @code{/} or @code{/mod} with its undefined
                   4433: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
                   4434: former, @pxref{Mixed precision}).
1.26      crook    4435: @comment TODO discuss the different division forms and the std approach
1.1       anton    4436: 
                   4437: @menu
                   4438: * Single precision::            
                   4439: * Bitwise operations::          
1.21      crook    4440: * Double precision::            Double-cell integer arithmetic
                   4441: * Numeric comparison::
1.29      crook    4442: * Mixed precision::             Operations with single and double-cell integers
1.1       anton    4443: * Floating Point::              
                   4444: @end menu
                   4445: 
                   4446: @node Single precision, Bitwise operations, Arithmetic, Arithmetic
                   4447: @subsection Single precision
                   4448: @cindex single precision arithmetic words
                   4449: 
1.21      crook    4450: By default, numbers in Forth are single-precision integers that are 1
1.26      crook    4451: cell in size. They can be signed or unsigned, depending upon how you
1.49      anton    4452: treat them. For the rules used by the text interpreter for recognising
                   4453: single-precision integers see @ref{Number Conversion}.
1.21      crook    4454: 
1.44      crook    4455: 
1.1       anton    4456: doc-+
1.21      crook    4457: doc-1+
1.1       anton    4458: doc--
1.21      crook    4459: doc-1-
1.1       anton    4460: doc-*
                   4461: doc-/
                   4462: doc-mod
                   4463: doc-/mod
                   4464: doc-negate
                   4465: doc-abs
                   4466: doc-min
                   4467: doc-max
1.21      crook    4468: doc-d>s
1.27      crook    4469: doc-floored
1.1       anton    4470: 
1.44      crook    4471: 
1.21      crook    4472: @node Bitwise operations, Double precision, Single precision, Arithmetic
1.1       anton    4473: @subsection Bitwise operations
                   4474: @cindex bitwise operation words
                   4475: 
1.44      crook    4476: 
1.1       anton    4477: doc-and
                   4478: doc-or
                   4479: doc-xor
                   4480: doc-invert
1.21      crook    4481: doc-lshift
                   4482: doc-rshift
1.1       anton    4483: doc-2*
1.21      crook    4484: doc-d2*
1.1       anton    4485: doc-2/
1.21      crook    4486: doc-d2/
                   4487: 
1.44      crook    4488: 
1.21      crook    4489: @node Double precision, Numeric comparison, Bitwise operations, Arithmetic
                   4490: @subsection Double precision
                   4491: @cindex double precision arithmetic words
                   4492: 
1.49      anton    4493: For the rules used by the text interpreter for
                   4494: recognising double-precision integers, see @ref{Number Conversion}.
1.21      crook    4495: 
                   4496: A double precision number is represented by a cell pair, with the most
1.31      anton    4497: significant cell at the TOS. It is trivial to convert an unsigned
1.26      crook    4498: single to an (unsigned) double; simply push a @code{0} onto the
                   4499: TOS. Since numbers are represented by Gforth using 2's complement
                   4500: arithmetic, converting a signed single to a (signed) double requires
1.31      anton    4501: sign-extension across the most significant cell. This can be achieved
1.26      crook    4502: using @code{s>d}. The moral of the story is that you cannot convert a
                   4503: number without knowing whether it represents an unsigned or a
                   4504: signed number.
1.21      crook    4505: 
1.44      crook    4506: 
1.21      crook    4507: doc-s>d
                   4508: doc-d+
                   4509: doc-d-
                   4510: doc-dnegate
                   4511: doc-dabs
                   4512: doc-dmin
                   4513: doc-dmax
                   4514: 
1.44      crook    4515: 
1.21      crook    4516: @node Numeric comparison, Mixed precision, Double precision, Arithmetic
                   4517: @subsection Numeric comparison
                   4518: @cindex numeric comparison words
                   4519: 
1.44      crook    4520: 
1.28      crook    4521: doc-<
                   4522: doc-<=
                   4523: doc-<>
                   4524: doc-=
                   4525: doc->
                   4526: doc->=
                   4527: 
1.21      crook    4528: doc-0<
1.23      crook    4529: doc-0<=
1.21      crook    4530: doc-0<>
                   4531: doc-0=
1.23      crook    4532: doc-0>
                   4533: doc-0>=
1.28      crook    4534: 
                   4535: doc-u<
                   4536: doc-u<=
1.44      crook    4537: @c u<> and u= exist but are the same as <> and =
1.31      anton    4538: @c doc-u<>
                   4539: @c doc-u=
1.28      crook    4540: doc-u>
                   4541: doc-u>=
                   4542: 
                   4543: doc-within
                   4544: 
                   4545: doc-d<
                   4546: doc-d<=
                   4547: doc-d<>
                   4548: doc-d=
                   4549: doc-d>
                   4550: doc-d>=
1.23      crook    4551: 
1.21      crook    4552: doc-d0<
1.23      crook    4553: doc-d0<=
                   4554: doc-d0<>
1.21      crook    4555: doc-d0=
1.23      crook    4556: doc-d0>
                   4557: doc-d0>=
                   4558: 
1.21      crook    4559: doc-du<
1.28      crook    4560: doc-du<=
1.44      crook    4561: @c du<> and du= exist but are the same as d<> and d=
1.31      anton    4562: @c doc-du<>
                   4563: @c doc-du=
1.28      crook    4564: doc-du>
                   4565: doc-du>=
1.1       anton    4566: 
1.44      crook    4567: 
1.21      crook    4568: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1       anton    4569: @subsection Mixed precision
                   4570: @cindex mixed precision arithmetic words
                   4571: 
1.44      crook    4572: 
1.1       anton    4573: doc-m+
                   4574: doc-*/
                   4575: doc-*/mod
                   4576: doc-m*
                   4577: doc-um*
                   4578: doc-m*/
                   4579: doc-um/mod
                   4580: doc-fm/mod
                   4581: doc-sm/rem
                   4582: 
1.44      crook    4583: 
1.21      crook    4584: @node Floating Point,  , Mixed precision, Arithmetic
1.1       anton    4585: @subsection Floating Point
                   4586: @cindex floating point arithmetic words
                   4587: 
1.49      anton    4588: For the rules used by the text interpreter for
                   4589: recognising floating-point numbers see @ref{Number Conversion}.
1.1       anton    4590: 
1.32      anton    4591: Gforth has a separate floating point
1.26      crook    4592: stack, but the documentation uses the unified notation.
1.1       anton    4593: 
                   4594: @cindex floating-point arithmetic, pitfalls
                   4595: Floating point numbers have a number of unpleasant surprises for the
                   4596: unwary (e.g., floating point addition is not associative) and even a few
                   4597: for the wary. You should not use them unless you know what you are doing
                   4598: or you don't care that the results you get are totally bogus. If you
                   4599: want to learn about the problems of floating point numbers (and how to
                   4600: avoid them), you might start with @cite{David Goldberg, What Every
                   4601: Computer Scientist Should Know About Floating-Point Arithmetic, ACM
1.17      anton    4602: Computing Surveys 23(1):5@minus{}48, March 1991}
1.47      crook    4603: (@uref{http://www.validgh.com/goldberg/paper.ps}).
1.1       anton    4604: 
1.44      crook    4605: 
1.21      crook    4606: doc-d>f
                   4607: doc-f>d
1.1       anton    4608: doc-f+
                   4609: doc-f-
                   4610: doc-f*
                   4611: doc-f/
                   4612: doc-fnegate
                   4613: doc-fabs
                   4614: doc-fmax
                   4615: doc-fmin
                   4616: doc-floor
                   4617: doc-fround
                   4618: doc-f**
                   4619: doc-fsqrt
                   4620: doc-fexp
                   4621: doc-fexpm1
                   4622: doc-fln
                   4623: doc-flnp1
                   4624: doc-flog
                   4625: doc-falog
1.32      anton    4626: doc-f2*
                   4627: doc-f2/
                   4628: doc-1/f
                   4629: doc-precision
                   4630: doc-set-precision
                   4631: 
                   4632: @cindex angles in trigonometric operations
                   4633: @cindex trigonometric operations
                   4634: Angles in floating point operations are given in radians (a full circle
                   4635: has 2 pi radians).
                   4636: 
1.1       anton    4637: doc-fsin
                   4638: doc-fcos
                   4639: doc-fsincos
                   4640: doc-ftan
                   4641: doc-fasin
                   4642: doc-facos
                   4643: doc-fatan
                   4644: doc-fatan2
                   4645: doc-fsinh
                   4646: doc-fcosh
                   4647: doc-ftanh
                   4648: doc-fasinh
                   4649: doc-facosh
                   4650: doc-fatanh
1.21      crook    4651: doc-pi
1.28      crook    4652: 
1.32      anton    4653: @cindex equality of floats
                   4654: @cindex floating-point comparisons
1.31      anton    4655: One particular problem with floating-point arithmetic is that comparison
                   4656: for equality often fails when you would expect it to succeed.  For this
                   4657: reason approximate equality is often preferred (but you still have to
                   4658: know what you are doing).  The comparison words are:
                   4659: 
                   4660: doc-f~rel
                   4661: doc-f~abs
                   4662: doc-f=
                   4663: doc-f~
                   4664: doc-f<>
                   4665: 
                   4666: doc-f<
                   4667: doc-f<=
                   4668: doc-f>
                   4669: doc-f>=
                   4670: 
1.21      crook    4671: doc-f0<
1.28      crook    4672: doc-f0<=
                   4673: doc-f0<>
1.21      crook    4674: doc-f0=
1.28      crook    4675: doc-f0>
                   4676: doc-f0>=
                   4677: 
1.1       anton    4678: 
                   4679: @node Stack Manipulation, Memory, Arithmetic, Words
                   4680: @section Stack Manipulation
                   4681: @cindex stack manipulation words
                   4682: 
                   4683: @cindex floating-point stack in the standard
1.21      crook    4684: Gforth maintains a number of separate stacks:
                   4685: 
1.29      crook    4686: @cindex data stack
                   4687: @cindex parameter stack
1.21      crook    4688: @itemize @bullet
                   4689: @item
1.29      crook    4690: A data stack (also known as the @dfn{parameter stack}) -- for
                   4691: characters, cells, addresses, and double cells.
1.21      crook    4692: 
1.29      crook    4693: @cindex floating-point stack
1.21      crook    4694: @item
1.44      crook    4695: A floating point stack -- for holding floating point (FP) numbers.
1.21      crook    4696: 
1.29      crook    4697: @cindex return stack
1.21      crook    4698: @item
1.44      crook    4699: A return stack -- for holding the return addresses of colon
1.32      anton    4700: definitions and other (non-FP) data.
1.21      crook    4701: 
1.29      crook    4702: @cindex locals stack
1.21      crook    4703: @item
1.44      crook    4704: A locals stack -- for holding local variables.
1.21      crook    4705: @end itemize
                   4706: 
1.1       anton    4707: @menu
                   4708: * Data stack::                  
                   4709: * Floating point stack::        
                   4710: * Return stack::                
                   4711: * Locals stack::                
                   4712: * Stack pointer manipulation::  
                   4713: @end menu
                   4714: 
                   4715: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
                   4716: @subsection Data stack
                   4717: @cindex data stack manipulation words
                   4718: @cindex stack manipulations words, data stack
                   4719: 
1.44      crook    4720: 
1.1       anton    4721: doc-drop
                   4722: doc-nip
                   4723: doc-dup
                   4724: doc-over
                   4725: doc-tuck
                   4726: doc-swap
1.21      crook    4727: doc-pick
1.1       anton    4728: doc-rot
                   4729: doc--rot
                   4730: doc-?dup
                   4731: doc-roll
                   4732: doc-2drop
                   4733: doc-2nip
                   4734: doc-2dup
                   4735: doc-2over
                   4736: doc-2tuck
                   4737: doc-2swap
                   4738: doc-2rot
                   4739: 
1.44      crook    4740: 
1.1       anton    4741: @node Floating point stack, Return stack, Data stack, Stack Manipulation
                   4742: @subsection Floating point stack
                   4743: @cindex floating-point stack manipulation words
                   4744: @cindex stack manipulation words, floating-point stack
                   4745: 
1.32      anton    4746: Whilst every sane Forth has a separate floating-point stack, it is not
                   4747: strictly required; an ANS Forth system could theoretically keep
                   4748: floating-point numbers on the data stack. As an additional difficulty,
                   4749: you don't know how many cells a floating-point number takes. It is
                   4750: reportedly possible to write words in a way that they work also for a
                   4751: unified stack model, but we do not recommend trying it. Instead, just
                   4752: say that your program has an environmental dependency on a separate
                   4753: floating-point stack.
                   4754: 
                   4755: doc-floating-stack
                   4756: 
1.1       anton    4757: doc-fdrop
                   4758: doc-fnip
                   4759: doc-fdup
                   4760: doc-fover
                   4761: doc-ftuck
                   4762: doc-fswap
1.21      crook    4763: doc-fpick
1.1       anton    4764: doc-frot
                   4765: 
1.44      crook    4766: 
1.1       anton    4767: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
                   4768: @subsection Return stack
                   4769: @cindex return stack manipulation words
                   4770: @cindex stack manipulation words, return stack
                   4771: 
1.32      anton    4772: @cindex return stack and locals
                   4773: @cindex locals and return stack
                   4774: A Forth system is allowed to keep local variables on the
                   4775: return stack. This is reasonable, as local variables usually eliminate
                   4776: the need to use the return stack explicitly. So, if you want to produce
                   4777: a standard compliant program and you are using local variables in a
                   4778: word, forget about return stack manipulations in that word (refer to the
                   4779: standard document for the exact rules).
                   4780: 
1.1       anton    4781: doc->r
                   4782: doc-r>
                   4783: doc-r@
                   4784: doc-rdrop
                   4785: doc-2>r
                   4786: doc-2r>
                   4787: doc-2r@
                   4788: doc-2rdrop
                   4789: 
1.44      crook    4790: 
1.1       anton    4791: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
                   4792: @subsection Locals stack
                   4793: 
1.47      crook    4794: Gforth uses an extra locals stack. It is described, along with the
                   4795: reasons for its existence, in @ref{Implementation,Implementation of locals}.
1.21      crook    4796: 
1.1       anton    4797: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
                   4798: @subsection Stack pointer manipulation
                   4799: @cindex stack pointer manipulation words
                   4800: 
1.44      crook    4801: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21      crook    4802: doc-sp0
1.1       anton    4803: doc-sp@
                   4804: doc-sp!
1.21      crook    4805: doc-fp0
1.1       anton    4806: doc-fp@
                   4807: doc-fp!
1.21      crook    4808: doc-rp0
1.1       anton    4809: doc-rp@
                   4810: doc-rp!
1.21      crook    4811: doc-lp0
1.1       anton    4812: doc-lp@
                   4813: doc-lp!
                   4814: 
1.44      crook    4815: 
1.1       anton    4816: @node Memory, Control Structures, Stack Manipulation, Words
                   4817: @section Memory
1.26      crook    4818: @cindex memory words
1.1       anton    4819: 
1.32      anton    4820: @menu
                   4821: * Memory model::                
                   4822: * Dictionary allocation::       
                   4823: * Heap Allocation::             
                   4824: * Memory Access::               
                   4825: * Address arithmetic::          
                   4826: * Memory Blocks::               
                   4827: @end menu
                   4828: 
                   4829: @node Memory model, Dictionary allocation, Memory, Memory
                   4830: @subsection ANS Forth and Gforth memory models
                   4831: 
                   4832: @c The ANS Forth description is a mess (e.g., is the heap part of
                   4833: @c the dictionary?), so let's not stick to closely with it.
                   4834: 
                   4835: ANS Forth considers a Forth system as consisting of several memories, of
                   4836: which only @dfn{data space} is managed and accessible with the memory
                   4837: words.  Memory not necessarily in data space includes the stacks, the
                   4838: code (called code space) and the headers (called name space). In Gforth
                   4839: everything is in data space, but the code for the primitives is usually
                   4840: read-only.
                   4841: 
                   4842: Data space is divided into a number of areas: The (data space portion of
                   4843: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
                   4844: refer to the search data structure embodied in word lists and headers,
                   4845: because it is used for looking up names, just as you would in a
                   4846: conventional dictionary.}, the heap, and a number of system-allocated
                   4847: buffers.
                   4848: 
                   4849: In ANS Forth data space is also divided into contiguous regions.  You
                   4850: can only use address arithmetic within a contiguous region, not between
                   4851: them.  Usually each allocation gives you one contiguous region, but the
1.33      anton    4852: dictionary allocation words have additional rules (@pxref{Dictionary
1.32      anton    4853: allocation}).
                   4854: 
                   4855: Gforth provides one big address space, and address arithmetic can be
                   4856: performed between any addresses. However, in the dictionary headers or
                   4857: code are interleaved with data, so almost the only contiguous data space
                   4858: regions there are those described by ANS Forth as contiguous; but you
                   4859: can be sure that the dictionary is allocated towards increasing
                   4860: addresses even between contiguous regions.  The memory order of
                   4861: allocations in the heap is platform-dependent (and possibly different
                   4862: from one run to the next).
                   4863: 
                   4864: @subsubsection ANS Forth dictionary details
                   4865: 
                   4866: This section is just informative, you can skip it if you are in a hurry.
1.27      crook    4867: 
1.29      crook    4868: When you create a colon definition, the text interpreter compiles the
1.32      anton    4869: code for the definition into the code space and compiles the name
                   4870: of the definition into the header space, together with other
1.27      crook    4871: information about the definition (such as its execution token).
                   4872: 
1.44      crook    4873: When you create a variable, the execution of @code{Variable} will
1.32      anton    4874: compile some code, assign one cell in data space, and compile the name
                   4875: of the variable into the header space.
1.27      crook    4876: 
                   4877: @cindex memory regions - relationship between them
                   4878: ANS Forth does not specify the relationship between the three memory
                   4879: regions, and specifies that a Standard program must not access code or
                   4880: data space directly -- it may only access data space directly. In
                   4881: addition, the Standard defines what relationships you may and may not
                   4882: rely on when allocating regions in data space. These constraints are
                   4883: simply a reflection of the many diverse techniques that are used to
                   4884: implement Forth systems; understanding and following the requirements of
                   4885: the Standard allows you to write portable programs -- programs that run
                   4886: in the same way on any of these diverse systems. Another way of looking
                   4887: at this is to say that ANS Forth was designed to permit compliant Forth
                   4888: systems to be implemented in many diverse ways.
                   4889: 
                   4890: @cindex memory regions - how they are assigned
1.29      crook    4891: Here are some examples of ways in which name, code and data spaces
                   4892: might be assigned in different Forth implementations:
1.27      crook    4893: 
                   4894: @itemize @bullet
                   4895: @item
                   4896: For a Forth system that runs from RAM under a general-purpose operating
                   4897: system, it can be convenient to interleave name, code and data spaces in
                   4898: a single contiguous memory region. This organisation can be
                   4899: memory-efficient (for example, because the relationship between the name
1.32      anton    4900: dictionary entry and the associated code space entry can be
1.27      crook    4901: implicit, rather than requiring an explicit memory pointer to reference
1.32      anton    4902: from the header space and the code space). This is the
1.27      crook    4903: organisation used by Gforth, as this example@footnote{The addresses
                   4904: in the example have been truncated to fit it onto the page, and the
                   4905: addresses and data shown will not match the output from your system} shows:
                   4906: @example
                   4907: hex
                   4908: variable fred 123456 fred !
                   4909: variable jim abcd jim !
                   4910: : foo + / - ;
                   4911: ' fred 10 - 50 dump 
                   4912: ..80: 5C 46 0E 40  84 66 72 65 - 64 20 20 20  20 20 20 20  \F.@.fred       
1.50      anton    4913: ..90: D0 9B 04 08  00 00 00 00 - 56 34 12 00  80 46 0E 40  ........V4...F.@@
1.27      crook    4914: ..A0: 83 6A 69 6D  20 20 20 20 - D0 9B 04 08  00 00 00 00  .jim    ........
                   4915: ..B0: CD AB 00 00  9C 46 0E 40 - 83 66 6F 6F  20 20 20 20  .....F.@.foo    
                   4916: ..C0: 80 9B 04 08  00 00 00 00 - E4 2E 05 08  0C 2F 05 08  ............./..
                   4917: @end example
                   4918: 
                   4919: @item
                   4920: For a high-performance system running on a modern RISC processor with a
                   4921: modified Harvard architecture (one that has a unified main memory but
                   4922: separate instruction and data caches), it is desirable to separate
                   4923: processor instructions from processor data. This encourages a high cache
1.32      anton    4924: density and therefore a high cache hit rate. The Forth code space
1.27      crook    4925: is not necessarily made up entirely of processor instructions; its
                   4926: nature is dependent upon the Forth implementation. 
                   4927: 
                   4928: @item
                   4929: A Forth compiler that runs on a segmented 8086 processor could be
                   4930: designed to interleave the name, code and data spaces within a single
                   4931: 64Kbyte segment. A more common implementation choice is to use a
                   4932: separate 64Kbyte segment for each region, which provides more memory
                   4933: overall but provides an address map in which only the data space is
                   4934: accessible.
                   4935: 
                   4936: @item
                   4937: Microprocessors exist that run Forth (or many of the primitives required
                   4938: to implement the Forth virtual machine efficiently) directly. On these
                   4939: processors, the relationship between name, code and data spaces may be
1.32      anton    4940: imposed as a side-effect of the architecture of the processor.
1.27      crook    4941: 
                   4942: @item
                   4943: A Forth compiler that executes from ROM on an embedded system needs its
                   4944: data space separated from the name and code spaces so that the data
                   4945: space can be mapped to a RAM area.
                   4946: 
                   4947: @item 
                   4948: A Forth compiler that runs on an embedded system may have a requirement
                   4949: for a small memory footprint. On such a system it can be useful to
1.32      anton    4950: separate the header space from the data and code spaces; once the
                   4951: application has been compiled, the header space is no longer
1.27      crook    4952: required@footnote{more strictly speaking, most applications can be
1.32      anton    4953: designed so that this is the case}. The header space can be deleted
1.29      crook    4954: entirely, or could be stored in memory on a remote @i{host} system for
1.27      crook    4955: debug and development purposes. In the latter case, the compiler running
1.29      crook    4956: on the @i{target} system could implement a protocol across a
1.32      anton    4957: communication link that would allow it to interrogate the header space.
1.27      crook    4958: @end itemize
                   4959: 
1.32      anton    4960: @node Dictionary allocation, Heap Allocation, Memory model, Memory
                   4961: @subsection Dictionary allocation
1.27      crook    4962: @cindex reserving data space
                   4963: @cindex data space - reserving some
                   4964: 
1.32      anton    4965: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
                   4966: you want to deallocate X, you also deallocate everything
                   4967: allocated after X.
                   4968: 
                   4969: The allocations using the words below are contiguous and grow the region
                   4970: towards increasing addresses.  Other words that allocate dictionary
                   4971: memory of any kind (i.e., defining words including @code{:noname}) end
                   4972: the contiguous region and start a new one.
                   4973: 
                   4974: In ANS Forth only @code{create}d words are guaranteed to produce an
                   4975: address that is the start of the following contiguous region.  In
                   4976: particular, the cell allocated by @code{variable} is not guaranteed to
                   4977: be contiguous with following @code{allot}ed memory.
                   4978: 
                   4979: You can deallocate memory by using @code{allot} with a negative argument
                   4980: (with some restrictions, see @code{allot}). For larger deallocations use
                   4981: @code{marker}.
1.27      crook    4982: 
1.29      crook    4983: 
1.27      crook    4984: doc-here
                   4985: doc-unused
                   4986: doc-allot
                   4987: doc-c,
1.29      crook    4988: doc-f,
1.27      crook    4989: doc-,
                   4990: doc-2,
1.29      crook    4991: @cindex user space
                   4992: doc-udp
                   4993: doc-uallot
1.27      crook    4994: 
1.32      anton    4995: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
                   4996: course you should allocate memory in an aligned way, too. I.e., before
                   4997: allocating allocating a cell, @code{here} must be cell-aligned, etc.
                   4998: The words below align @code{here} if it is not already.  Basically it is
                   4999: only already aligned for a type, if the last allocation was a multiple
                   5000: of the size of this type and if @code{here} was aligned for this type
                   5001: before.
                   5002: 
                   5003: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
                   5004: ANS Forth (@code{maxalign}ed in Gforth).
                   5005: 
                   5006: doc-align
                   5007: doc-falign
                   5008: doc-sfalign
                   5009: doc-dfalign
                   5010: doc-maxalign
                   5011: doc-cfalign
                   5012: 
                   5013: 
                   5014: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
                   5015: @subsection Heap allocation
                   5016: @cindex heap allocation
                   5017: @cindex dynamic allocation of memory
                   5018: @cindex memory-allocation word set
                   5019: 
                   5020: Heap allocation supports deallocation of allocated memory in any
                   5021: order. Dictionary allocation is not affected by it (i.e., it does not
                   5022: end a contiguous region). In Gforth, these words are implemented using
                   5023: the standard C library calls malloc(), free() and resize().
                   5024: 
                   5025: doc-allocate
                   5026: doc-free
                   5027: doc-resize
                   5028: 
1.27      crook    5029: 
1.32      anton    5030: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1       anton    5031: @subsection Memory Access
                   5032: @cindex memory access words
                   5033: 
1.44      crook    5034: 
1.1       anton    5035: doc-@
                   5036: doc-!
                   5037: doc-+!
                   5038: doc-c@
                   5039: doc-c!
                   5040: doc-2@
                   5041: doc-2!
                   5042: doc-f@
                   5043: doc-f!
                   5044: doc-sf@
                   5045: doc-sf!
                   5046: doc-df@
                   5047: doc-df!
                   5048: 
1.32      anton    5049: @node Address arithmetic, Memory Blocks, Memory Access, Memory
                   5050: @subsection Address arithmetic
1.1       anton    5051: @cindex address arithmetic words
                   5052: 
1.32      anton    5053: Address arithmetic is the foundation on which data structures like
                   5054: arrays, records (@pxref{Structures}) and objects (@pxref{Object-oriented
                   5055: Forth}) are built.
                   5056: 
1.1       anton    5057: ANS Forth does not specify the sizes of the data types. Instead, it
                   5058: offers a number of words for computing sizes and doing address
1.29      crook    5059: arithmetic. Address arithmetic is performed in terms of address units
                   5060: (aus); on most systems the address unit is one byte. Note that a
                   5061: character may have more than one au, so @code{chars} is no noop (on
                   5062: systems where it is a noop, it compiles to nothing).
1.1       anton    5063: 
                   5064: @cindex alignment of addresses for types
                   5065: ANS Forth also defines words for aligning addresses for specific
                   5066: types. Many computers require that accesses to specific data types
                   5067: must only occur at specific addresses; e.g., that cells may only be
                   5068: accessed at addresses divisible by 4. Even if a machine allows unaligned
                   5069: accesses, it can usually perform aligned accesses faster. 
                   5070: 
                   5071: For the performance-conscious: alignment operations are usually only
                   5072: necessary during the definition of a data structure, not during the
                   5073: (more frequent) accesses to it.
                   5074: 
                   5075: ANS Forth defines no words for character-aligning addresses. This is not
                   5076: an oversight, but reflects the fact that addresses that are not
                   5077: char-aligned have no use in the standard and therefore will not be
                   5078: created.
                   5079: 
                   5080: @cindex @code{CREATE} and alignment
1.29      crook    5081: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1       anton    5082: are cell-aligned; in addition, Gforth guarantees that these addresses
                   5083: are aligned for all purposes.
                   5084: 
1.26      crook    5085: Note that the ANS Forth word @code{char} has nothing to do with address
                   5086: arithmetic.
1.1       anton    5087: 
1.44      crook    5088: 
1.1       anton    5089: doc-chars
                   5090: doc-char+
                   5091: doc-cells
                   5092: doc-cell+
                   5093: doc-cell
                   5094: doc-aligned
                   5095: doc-floats
                   5096: doc-float+
                   5097: doc-float
                   5098: doc-faligned
                   5099: doc-sfloats
                   5100: doc-sfloat+
                   5101: doc-sfaligned
                   5102: doc-dfloats
                   5103: doc-dfloat+
                   5104: doc-dfaligned
                   5105: doc-maxaligned
                   5106: doc-cfaligned
                   5107: doc-address-unit-bits
                   5108: 
1.44      crook    5109: 
1.32      anton    5110: @node Memory Blocks,  , Address arithmetic, Memory
1.1       anton    5111: @subsection Memory Blocks
                   5112: @cindex memory block words
1.27      crook    5113: @cindex character strings - moving and copying
                   5114: 
1.49      anton    5115: Memory blocks often represent character strings; For ways of storing
                   5116: character strings in memory see @ref{String Formats}.  For other
                   5117: string-processing words see @ref{Displaying characters and strings}.
1.1       anton    5118: 
1.32      anton    5119: Some of these words work on address units. Others work on character
                   5120: units (increments of @code{CHAR}), and expect a @code{CHAR}-aligned
                   5121: address. Choose the correct operation depending upon your data type.
1.21      crook    5122: 
                   5123: When copying characters between overlapping memory regions, choose
                   5124: carefully between @code{cmove} and @code{cmove>}.
                   5125: 
1.29      crook    5126: You can only use any of these words @i{portably} to access data space.
1.21      crook    5127: 
1.27      crook    5128: @comment TODO - think the naming of the arguments is wrong for move
1.29      crook    5129: @comment well, really it seems to be the Standard that's wrong; it
                   5130: @comment describes MOVE as a word that requires a CELL-aligned source
                   5131: @comment and destination address but a xtranfer count that need not
                   5132: @comment be a multiple of CELL.
1.44      crook    5133: 
1.1       anton    5134: doc-move
                   5135: doc-erase
                   5136: doc-cmove
                   5137: doc-cmove>
                   5138: doc-fill
                   5139: doc-blank
1.21      crook    5140: doc-compare
                   5141: doc-search
1.27      crook    5142: doc--trailing
                   5143: doc-/string
                   5144: 
1.44      crook    5145: 
1.27      crook    5146: @comment TODO examples
                   5147: 
1.1       anton    5148: 
1.26      crook    5149: @node Control Structures, Defining Words, Memory, Words
1.1       anton    5150: @section Control Structures
                   5151: @cindex control structures
                   5152: 
1.33      anton    5153: Control structures in Forth cannot be used interpretively, only in a
                   5154: colon definition@footnote{To be precise, they have no interpretation
                   5155: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
                   5156: not like this limitation, but have not seen a satisfying way around it
                   5157: yet, although many schemes have been proposed.
1.1       anton    5158: 
                   5159: @menu
1.33      anton    5160: * Selection::                   IF ... ELSE ... ENDIF
                   5161: * Simple Loops::                BEGIN ...
1.29      crook    5162: * Counted Loops::               DO
                   5163: * Arbitrary control structures::
                   5164: * Calls and returns::
1.1       anton    5165: * Exception Handling::          
                   5166: @end menu
                   5167: 
                   5168: @node Selection, Simple Loops, Control Structures, Control Structures
                   5169: @subsection Selection
                   5170: @cindex selection control structures
                   5171: @cindex control structures for selection
                   5172: 
1.33      anton    5173: @c what's the purpose of all these @i? Maybe we should define a macro
                   5174: @c so we can produce logical markup.  - anton
                   5175: 
1.44      crook    5176: @c nac-> When I started working on the manual, a mixture of @i and @var
                   5177: @c were used inconsistently in code examples and \Glossary entries. These
                   5178: @c two behave differently in info format so I decided to standardize on @i.
                   5179: @c Logical markup would be better but texi isn't really upto it, and
                   5180: @c texi2html just ignores macros.
1.47      crook    5181: @c nac02dec1999-> update: the latest texinfo release can spit out html
                   5182: @c and it handles macros, so we could do some logical markup. Unfortunately
                   5183: @c texinfo will not split html output, which would be a big pain if you
                   5184: @c wanted to put the document on the web, which would be nice.
1.44      crook    5185: 
1.1       anton    5186: @cindex @code{IF} control structure
                   5187: @example
1.29      crook    5188: @i{flag}
1.1       anton    5189: IF
1.29      crook    5190:   @i{code}
1.1       anton    5191: ENDIF
                   5192: @end example
1.21      crook    5193: @noindent
1.33      anton    5194: 
1.44      crook    5195: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
                   5196: with any bit set represents truth) @i{code} is executed.
1.33      anton    5197: 
1.1       anton    5198: @example
1.29      crook    5199: @i{flag}
1.1       anton    5200: IF
1.29      crook    5201:   @i{code1}
1.1       anton    5202: ELSE
1.29      crook    5203:   @i{code2}
1.1       anton    5204: ENDIF
                   5205: @end example
                   5206: 
1.44      crook    5207: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
                   5208: executed.
1.33      anton    5209: 
1.1       anton    5210: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
                   5211: standard, and @code{ENDIF} is not, although it is quite popular. We
                   5212: recommend using @code{ENDIF}, because it is less confusing for people
                   5213: who also know other languages (and is not prone to reinforcing negative
                   5214: prejudices against Forth in these people). Adding @code{ENDIF} to a
                   5215: system that only supplies @code{THEN} is simple:
                   5216: @example
1.21      crook    5217: : ENDIF   POSTPONE THEN ; immediate
1.1       anton    5218: @end example
                   5219: 
                   5220: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
                   5221: (adv.)}  has the following meanings:
                   5222: @quotation
                   5223: ... 2b: following next after in order ... 3d: as a necessary consequence
                   5224: (if you were there, then you saw them).
                   5225: @end quotation
                   5226: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
                   5227: and many other programming languages has the meaning 3d.]
                   5228: 
1.21      crook    5229: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1       anton    5230: you can avoid using @code{?dup}. Using these alternatives is also more
1.26      crook    5231: efficient than using @code{?dup}. Definitions in ANS Forth
1.1       anton    5232: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
                   5233: @file{compat/control.fs}.
                   5234: 
                   5235: @cindex @code{CASE} control structure
                   5236: @example
1.29      crook    5237: @i{n}
1.1       anton    5238: CASE
1.29      crook    5239:   @i{n1} OF @i{code1} ENDOF
                   5240:   @i{n2} OF @i{code2} ENDOF
1.1       anton    5241:   @dots{}
                   5242: ENDCASE
                   5243: @end example
                   5244: 
1.29      crook    5245: Executes the first @i{codei}, where the @i{ni} is equal to
                   5246: @i{n}. A default case can be added by simply writing the code after
                   5247: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
1.1       anton    5248: but must not consume it.
                   5249: 
                   5250: @node Simple Loops, Counted Loops, Selection, Control Structures
                   5251: @subsection Simple Loops
                   5252: @cindex simple loops
                   5253: @cindex loops without count 
                   5254: 
                   5255: @cindex @code{WHILE} loop
                   5256: @example
                   5257: BEGIN
1.29      crook    5258:   @i{code1}
                   5259:   @i{flag}
1.1       anton    5260: WHILE
1.29      crook    5261:   @i{code2}
1.1       anton    5262: REPEAT
                   5263: @end example
                   5264: 
1.29      crook    5265: @i{code1} is executed and @i{flag} is computed. If it is true,
                   5266: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1       anton    5267: false, execution continues after the @code{REPEAT}.
                   5268: 
                   5269: @cindex @code{UNTIL} loop
                   5270: @example
                   5271: BEGIN
1.29      crook    5272:   @i{code}
                   5273:   @i{flag}
1.1       anton    5274: UNTIL
                   5275: @end example
                   5276: 
1.29      crook    5277: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1       anton    5278: 
                   5279: @cindex endless loop
                   5280: @cindex loops, endless
                   5281: @example
                   5282: BEGIN
1.29      crook    5283:   @i{code}
1.1       anton    5284: AGAIN
                   5285: @end example
                   5286: 
                   5287: This is an endless loop.
                   5288: 
                   5289: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
                   5290: @subsection Counted Loops
                   5291: @cindex counted loops
                   5292: @cindex loops, counted
                   5293: @cindex @code{DO} loops
                   5294: 
                   5295: The basic counted loop is:
                   5296: @example
1.29      crook    5297: @i{limit} @i{start}
1.1       anton    5298: ?DO
1.29      crook    5299:   @i{body}
1.1       anton    5300: LOOP
                   5301: @end example
                   5302: 
1.29      crook    5303: This performs one iteration for every integer, starting from @i{start}
                   5304: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21      crook    5305: accessed with @code{i}. For example, the loop:
1.1       anton    5306: @example
                   5307: 10 0 ?DO
                   5308:   i .
                   5309: LOOP
                   5310: @end example
1.21      crook    5311: @noindent
                   5312: prints @code{0 1 2 3 4 5 6 7 8 9}
                   5313: 
1.1       anton    5314: The index of the innermost loop can be accessed with @code{i}, the index
                   5315: of the next loop with @code{j}, and the index of the third loop with
                   5316: @code{k}.
                   5317: 
1.44      crook    5318: 
1.1       anton    5319: doc-i
                   5320: doc-j
                   5321: doc-k
                   5322: 
1.44      crook    5323: 
1.1       anton    5324: The loop control data are kept on the return stack, so there are some
1.21      crook    5325: restrictions on mixing return stack accesses and counted loop words. In
                   5326: particuler, if you put values on the return stack outside the loop, you
                   5327: cannot read them inside the loop@footnote{well, not in a way that is
                   5328: portable.}. If you put values on the return stack within a loop, you
                   5329: have to remove them before the end of the loop and before accessing the
                   5330: index of the loop.
1.1       anton    5331: 
                   5332: There are several variations on the counted loop:
                   5333: 
1.21      crook    5334: @itemize @bullet
                   5335: @item
                   5336: @code{LEAVE} leaves the innermost counted loop immediately; execution
                   5337: continues after the associated @code{LOOP} or @code{NEXT}. For example:
                   5338: 
                   5339: @example
                   5340: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
                   5341: @end example
                   5342: prints @code{0 1 2 3}
                   5343: 
1.1       anton    5344: 
1.21      crook    5345: @item
                   5346: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
                   5347: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
                   5348: return stack so @code{EXIT} can get to its return address. For example:
                   5349: 
                   5350: @example
                   5351: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
                   5352: @end example
                   5353: prints @code{0 1 2 3}
                   5354: 
                   5355: 
                   5356: @item
1.29      crook    5357: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1       anton    5358: (and @code{LOOP} iterates until they become equal by wrap-around
                   5359: arithmetic). This behaviour is usually not what you want. Therefore,
                   5360: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29      crook    5361: @code{?DO}), which do not enter the loop if @i{start} is greater than
                   5362: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1       anton    5363: unsigned loop parameters.
                   5364: 
1.21      crook    5365: @item
                   5366: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
                   5367: the loop, independent of the loop parameters. Do not use @code{DO}, even
                   5368: if you know that the loop is entered in any case. Such knowledge tends
                   5369: to become invalid during maintenance of a program, and then the
                   5370: @code{DO} will make trouble.
                   5371: 
                   5372: @item
1.29      crook    5373: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
                   5374: index by @i{n} instead of by 1. The loop is terminated when the border
                   5375: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1       anton    5376: 
1.21      crook    5377: @example
                   5378: 4 0 +DO  i .  2 +LOOP
                   5379: @end example
                   5380: @noindent
                   5381: prints @code{0 2}
                   5382: 
                   5383: @example
                   5384: 4 1 +DO  i .  2 +LOOP
                   5385: @end example
                   5386: @noindent
                   5387: prints @code{1 3}
1.1       anton    5388: 
                   5389: 
                   5390: @cindex negative increment for counted loops
                   5391: @cindex counted loops with negative increment
1.29      crook    5392: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1       anton    5393: 
1.21      crook    5394: @example
                   5395: -1 0 ?DO  i .  -1 +LOOP
                   5396: @end example
                   5397: @noindent
                   5398: prints @code{0 -1}
1.1       anton    5399: 
1.21      crook    5400: @example
                   5401: 0 0 ?DO  i .  -1 +LOOP
                   5402: @end example
                   5403: prints nothing.
1.1       anton    5404: 
1.29      crook    5405: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
                   5406: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
                   5407: index by @i{u} each iteration. The loop is terminated when the border
                   5408: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1       anton    5409: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
                   5410: 
1.21      crook    5411: @example
                   5412: -2 0 -DO  i .  1 -LOOP
                   5413: @end example
                   5414: @noindent
                   5415: prints @code{0 -1}
1.1       anton    5416: 
1.21      crook    5417: @example
                   5418: -1 0 -DO  i .  1 -LOOP
                   5419: @end example
                   5420: @noindent
                   5421: prints @code{0}
                   5422: 
                   5423: @example
                   5424: 0 0 -DO  i .  1 -LOOP
                   5425: @end example
                   5426: @noindent
                   5427: prints nothing.
1.1       anton    5428: 
1.21      crook    5429: @end itemize
1.1       anton    5430: 
                   5431: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26      crook    5432: @code{-LOOP} are not defined in ANS Forth. However, an implementation
                   5433: for these words that uses only standard words is provided in
                   5434: @file{compat/loops.fs}.
1.1       anton    5435: 
                   5436: 
                   5437: @cindex @code{FOR} loops
1.26      crook    5438: Another counted loop is:
1.1       anton    5439: @example
1.29      crook    5440: @i{n}
1.1       anton    5441: FOR
1.29      crook    5442:   @i{body}
1.1       anton    5443: NEXT
                   5444: @end example
                   5445: This is the preferred loop of native code compiler writers who are too
1.26      crook    5446: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29      crook    5447: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
                   5448: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26      crook    5449: Forth systems may behave differently, even if they support @code{FOR}
                   5450: loops. To avoid problems, don't use @code{FOR} loops.
1.1       anton    5451: 
                   5452: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
                   5453: @subsection Arbitrary control structures
                   5454: @cindex control structures, user-defined
                   5455: 
                   5456: @cindex control-flow stack
                   5457: ANS Forth permits and supports using control structures in a non-nested
                   5458: way. Information about incomplete control structures is stored on the
                   5459: control-flow stack. This stack may be implemented on the Forth data
                   5460: stack, and this is what we have done in Gforth.
                   5461: 
                   5462: @cindex @code{orig}, control-flow stack item
                   5463: @cindex @code{dest}, control-flow stack item
                   5464: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
                   5465: entry represents a backward branch target. A few words are the basis for
                   5466: building any control structure possible (except control structures that
                   5467: need storage, like calls, coroutines, and backtracking).
                   5468: 
1.44      crook    5469: 
1.1       anton    5470: doc-if
                   5471: doc-ahead
                   5472: doc-then
                   5473: doc-begin
                   5474: doc-until
                   5475: doc-again
                   5476: doc-cs-pick
                   5477: doc-cs-roll
                   5478: 
1.44      crook    5479: 
1.21      crook    5480: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
                   5481: manipulate the control-flow stack in a portable way. Without them, you
                   5482: would need to know how many stack items are occupied by a control-flow
                   5483: entry (many systems use one cell. In Gforth they currently take three,
                   5484: but this may change in the future).
                   5485: 
1.1       anton    5486: Some standard control structure words are built from these words:
                   5487: 
1.44      crook    5488: 
1.1       anton    5489: doc-else
                   5490: doc-while
                   5491: doc-repeat
                   5492: 
1.44      crook    5493: 
                   5494: @noindent
1.1       anton    5495: Gforth adds some more control-structure words:
                   5496: 
1.44      crook    5497: 
1.1       anton    5498: doc-endif
                   5499: doc-?dup-if
                   5500: doc-?dup-0=-if
                   5501: 
1.44      crook    5502: 
                   5503: @noindent
1.1       anton    5504: Counted loop words constitute a separate group of words:
                   5505: 
1.44      crook    5506: 
1.1       anton    5507: doc-?do
                   5508: doc-+do
                   5509: doc-u+do
                   5510: doc--do
                   5511: doc-u-do
                   5512: doc-do
                   5513: doc-for
                   5514: doc-loop
                   5515: doc-+loop
                   5516: doc--loop
                   5517: doc-next
                   5518: doc-leave
                   5519: doc-?leave
                   5520: doc-unloop
                   5521: doc-done
                   5522: 
1.44      crook    5523: 
1.21      crook    5524: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
                   5525: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1       anton    5526: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
                   5527: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
                   5528: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
                   5529: resolved (by using one of the loop-ending words or @code{DONE}).
                   5530: 
1.44      crook    5531: @noindent
1.26      crook    5532: Another group of control structure words are:
1.1       anton    5533: 
1.44      crook    5534: 
1.1       anton    5535: doc-case
                   5536: doc-endcase
                   5537: doc-of
                   5538: doc-endof
                   5539: 
1.44      crook    5540: 
1.21      crook    5541: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
                   5542: @code{CS-ROLL}.
1.1       anton    5543: 
                   5544: @subsubsection Programming Style
1.47      crook    5545: @cindex control structures programming style
                   5546: @cindex programming style, arbitrary control structures
1.1       anton    5547: 
                   5548: In order to ensure readability we recommend that you do not create
                   5549: arbitrary control structures directly, but define new control structure
                   5550: words for the control structure you want and use these words in your
1.26      crook    5551: program. For example, instead of writing:
1.1       anton    5552: 
                   5553: @example
1.26      crook    5554: BEGIN
1.1       anton    5555:   ...
1.26      crook    5556: IF [ 1 CS-ROLL ]
1.1       anton    5557:   ...
1.26      crook    5558: AGAIN THEN
1.1       anton    5559: @end example
                   5560: 
1.21      crook    5561: @noindent
1.1       anton    5562: we recommend defining control structure words, e.g.,
                   5563: 
                   5564: @example
1.26      crook    5565: : WHILE ( DEST -- ORIG DEST )
                   5566:  POSTPONE IF
                   5567:  1 CS-ROLL ; immediate
                   5568: 
                   5569: : REPEAT ( orig dest -- )
                   5570:  POSTPONE AGAIN
                   5571:  POSTPONE THEN ; immediate
1.1       anton    5572: @end example
                   5573: 
1.21      crook    5574: @noindent
1.1       anton    5575: and then using these to create the control structure:
                   5576: 
                   5577: @example
1.26      crook    5578: BEGIN
1.1       anton    5579:   ...
1.26      crook    5580: WHILE
1.1       anton    5581:   ...
1.26      crook    5582: REPEAT
1.1       anton    5583: @end example
                   5584: 
                   5585: That's much easier to read, isn't it? Of course, @code{REPEAT} and
                   5586: @code{WHILE} are predefined, so in this example it would not be
                   5587: necessary to define them.
                   5588: 
                   5589: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
                   5590: @subsection Calls and returns
                   5591: @cindex calling a definition
                   5592: @cindex returning from a definition
                   5593: 
1.3       anton    5594: @cindex recursive definitions
                   5595: A definition can be called simply be writing the name of the definition
1.26      crook    5596: to be called. Normally a definition is invisible during its own
1.3       anton    5597: definition. If you want to write a directly recursive definition, you
1.26      crook    5598: can use @code{recursive} to make the current definition visible, or
                   5599: @code{recurse} to call the current definition directly.
1.3       anton    5600: 
1.44      crook    5601: 
1.3       anton    5602: doc-recursive
                   5603: doc-recurse
                   5604: 
1.44      crook    5605: 
1.21      crook    5606: @comment TODO add example of the two recursion methods
1.12      anton    5607: @quotation
                   5608: @progstyle
                   5609: I prefer using @code{recursive} to @code{recurse}, because calling the
                   5610: definition by name is more descriptive (if the name is well-chosen) than
                   5611: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
                   5612: implementation, it is much better to read (and think) ``now sort the
                   5613: partitions'' than to read ``now do a recursive call''.
                   5614: @end quotation
1.3       anton    5615: 
1.29      crook    5616: For mutual recursion, use @code{Defer}red words, like this:
1.3       anton    5617: 
                   5618: @example
1.28      crook    5619: Defer foo
1.3       anton    5620: 
                   5621: : bar ( ... -- ... )
                   5622:  ... foo ... ;
                   5623: 
                   5624: :noname ( ... -- ... )
                   5625:  ... bar ... ;
                   5626: IS foo
                   5627: @end example
                   5628: 
1.44      crook    5629: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33      anton    5630: 
1.26      crook    5631: The current definition returns control to the calling definition when
1.33      anton    5632: the end of the definition is reached or @code{EXIT} is encountered.
1.1       anton    5633: 
                   5634: doc-exit
                   5635: doc-;s
                   5636: 
1.44      crook    5637: 
1.1       anton    5638: @node Exception Handling,  , Calls and returns, Control Structures
                   5639: @subsection Exception Handling
1.26      crook    5640: @cindex exceptions
1.1       anton    5641: 
1.26      crook    5642: If your program detects a fatal error condition, the simplest action
                   5643: that it can take is to @code{quit}. This resets the return stack and
                   5644: restarts the text interpreter, but does not print any error message.
1.21      crook    5645: 
1.26      crook    5646: The next stage in severity is to execute @code{abort}, which has the
                   5647: same effect as @code{quit}, with the addition that it resets the data
                   5648: stack.
1.1       anton    5649: 
1.26      crook    5650: A slightly more sophisticated approach is use use @code{abort"}, which
                   5651: compiles a string to be used as an error message and does a conditional
                   5652: @code{abort} at run-time. For example:
1.1       anton    5653: 
1.26      crook    5654: @example
1.30      anton    5655: @kbd{: checker abort" That flag was true" ." A false flag" ;@key{RET}}  ok
                   5656: @kbd{0 checker@key{RET}} A false flag ok
                   5657: @kbd{1 checker@key{RET}}
1.26      crook    5658: :1: That flag was true
                   5659: 1 checker
                   5660:   ^^^^^^^
                   5661: $400D1648 throw 
                   5662: $400E4660
                   5663: @end example
1.1       anton    5664: 
1.26      crook    5665: These simple techniques allow a program to react to a fatal error
                   5666: condition, but they are not exactly user-friendly. The ANS Forth
                   5667: Exception word set provides the pair of words @code{throw} and
                   5668: @code{catch}, which can be used to provide sophisticated error-handling.
1.1       anton    5669: 
1.26      crook    5670: @code{catch} has a similar behaviour to @code{execute}, in that it takes
1.29      crook    5671: an @i{xt} as a parameter and starts execution of the xt. However,
1.26      crook    5672: before passing control to the xt, @code{catch} pushes an
1.29      crook    5673: @dfn{exception frame} onto the @dfn{exception stack}. This exception
1.26      crook    5674: frame is used to restore the system to a known state if a detected error
                   5675: occurs during the execution of the xt. A typical way to use @code{catch}
                   5676: would be:
1.1       anton    5677: 
1.26      crook    5678: @example
                   5679: ... ['] foo catch IF ...
                   5680: @end example
1.1       anton    5681: 
1.33      anton    5682: @c TOS is undefined. - anton
1.44      crook    5683: 
                   5684: @c nac-> TODO -- I need to look at this example again.
                   5685: 
1.26      crook    5686: Whilst @code{foo} executes, it can call other words to any level of
                   5687: nesting, as usual.  If @code{foo} (and all the words that it calls)
1.33      anton    5688: execute successfully, control will ultimately pass to the word following
                   5689: the @code{catch}, and there will be a 0 at TOS.  However, if any word
                   5690: detects an error, it can terminate the execution of @code{foo} by
                   5691: pushing a non-zero error code onto the stack and then performing a
                   5692: @code{throw}. The execution of @code{throw} will pass control to the
                   5693: word following the @code{catch}, but this time the TOS will hold the
                   5694: error code. Therefore, the @code{IF} in the example can be used to
                   5695: determine whether @code{foo} executed successfully.
1.1       anton    5696: 
1.26      crook    5697: This simple example shows how you can use @code{throw} and @code{catch}
                   5698: to ``take over'' exception handling from the system:
1.1       anton    5699: @example
1.26      crook    5700: : my-div ['] / catch if ." DIVIDE ERROR" else ." OK.. " . then ;
1.1       anton    5701: @end example
                   5702: 
1.26      crook    5703: The next example is more sophisticated and shows a multi-level
                   5704: @code{throw} and @code{catch}. To understand this example, start at the
                   5705: definition of @code{top-level} and work backwards:
                   5706: 
1.1       anton    5707: @example
1.26      crook    5708: : lowest-level ( -- c )
                   5709:     key dup 27 = if
1.44      crook    5710:         1 throw \ ESCAPE key pressed
1.26      crook    5711:     else
1.44      crook    5712:         ." lowest-level successful" CR
1.26      crook    5713:     then
                   5714: ;
                   5715: 
                   5716: : lower-level ( -- c )
                   5717:     lowest-level
                   5718:     \ at this level consider a CTRL-U to be a fatal error
                   5719:     dup 21 = if \ CTRL-U
1.44      crook    5720:         2 throw
1.26      crook    5721:     else
1.44      crook    5722:         ." lower-level successful" CR
1.26      crook    5723:     then
                   5724: ;
                   5725: 
                   5726: : low-level ( -- c )
                   5727:     ['] lower-level catch
                   5728:     ?dup if
1.44      crook    5729:         \ error occurred - do we recognise it?
                   5730:         dup 1 = if
                   5731:             \ ESCAPE key pressed.. pretend it was an E
                   5732:             [char] E
                   5733:         else throw \ propogate the error upwards
                   5734:         then
1.26      crook    5735:     then
                   5736:     ." low-level successfull" CR
                   5737: ;
                   5738: 
                   5739: : top-level ( -- )
                   5740:     CR ['] low-level catch \ CATCH is used like EXECUTE
                   5741:     ?dup if \ error occurred..
1.44      crook    5742:         ." Error " . ." occurred - contact your supplier"
1.26      crook    5743:     else
1.44      crook    5744:         ." The '" emit ." ' key was pressed" CR
1.26      crook    5745:     then
                   5746: ;
1.1       anton    5747: @end example
                   5748: 
1.26      crook    5749: The ANS Forth document assigns @code{throw} codes thus:
1.1       anton    5750: 
1.26      crook    5751: @itemize @bullet
                   5752: @item
                   5753: codes in the range -1 -- -255 are reserved to be assigned by the
                   5754: Standard. Assignments for codes in the range -1 -- -58 are currently
                   5755: documented in the Standard. In particular, @code{-1 throw} is equivalent
                   5756: to @code{abort} and @code{-2 throw} is equivalent to @code{abort"}.
                   5757: @item
                   5758: codes in the range -256 -- -4095 are reserved to be assigned by the system.
                   5759: @item
                   5760: all other codes may be assigned by programs.
                   5761: @end itemize
1.1       anton    5762: 
1.26      crook    5763: Gforth provides the word @code{exception} as a mechanism for assigning
                   5764: system throw codes to applications. This allows multiple applications to
                   5765: co-exist in memory without any clash of @code{throw} codes. A definition
                   5766: of @code{exception} in ANS Forth is provided in
                   5767: @file{compat/exception.fs}.
1.1       anton    5768: 
1.44      crook    5769: 
1.26      crook    5770: doc-quit
                   5771: doc-abort
                   5772: doc-abort"
1.1       anton    5773: 
1.26      crook    5774: doc-catch
1.29      crook    5775: doc-throw
                   5776: doc---exception-exception
                   5777: 
                   5778: 
1.44      crook    5779: 
1.29      crook    5780: @c -------------------------------------------------------------
1.47      crook    5781: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29      crook    5782: @section Defining Words
                   5783: @cindex defining words
                   5784: 
1.47      crook    5785: Defining words are used to extend Forth by creating new entries in the dictionary.
                   5786: 
1.29      crook    5787: @menu
1.44      crook    5788: * CREATE::
                   5789: * Variables::                   Variables and user variables
                   5790: * Constants::
                   5791: * Values::                      Initialised variables
1.29      crook    5792: * Colon Definitions::
1.44      crook    5793: * Anonymous Definitions::       Definitions without names
1.29      crook    5794: * User-defined Defining Words::
1.44      crook    5795: * Deferred words::              Allow forward references
                   5796: * Aliases::
1.29      crook    5797: * Supplying names::
                   5798: @end menu
                   5799: 
1.44      crook    5800: @node CREATE, Variables, Defining Words, Defining Words
                   5801: @subsection @code{CREATE}
1.29      crook    5802: @cindex simple defining words
                   5803: @cindex defining words, simple
                   5804: 
                   5805: Defining words are used to create new entries in the dictionary. The
                   5806: simplest defining word is @code{CREATE}. @code{CREATE} is used like
                   5807: this:
                   5808: 
                   5809: @example
                   5810: CREATE new-word1
                   5811: @end example
                   5812: 
                   5813: @code{CREATE} is a parsing word that generates a dictionary entry for
                   5814: @code{new-word1}. When @code{new-word1} is executed, all that it does is
                   5815: leave an address on the stack. The address represents the value of
                   5816: the data space pointer (@code{HERE}) at the time that @code{new-word1}
                   5817: was defined. Therefore, @code{CREATE} is a way of associating a name
                   5818: with the address of a region of memory.
                   5819: 
1.34      anton    5820: doc-create
                   5821: 
1.29      crook    5822: By extending this example to reserve some memory in data space, we end
                   5823: up with a @i{variable}. Here are two different ways to do it:
                   5824: 
                   5825: @example
                   5826: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
                   5827: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
                   5828: @end example
                   5829: 
                   5830: The variable can be examined and modified using @code{@@} (``fetch'') and
                   5831: @code{!} (``store'') like this:
                   5832: 
                   5833: @example
                   5834: new-word2 @@ .      \ get address, fetch from it and display
                   5835: 1234 new-word2 !   \ new value, get address, store to it
                   5836: @end example
                   5837: 
1.44      crook    5838: @cindex arrays
                   5839: A similar mechanism can be used to create arrays. For example, an
                   5840: 80-character text input buffer:
1.29      crook    5841: 
                   5842: @example
1.44      crook    5843: CREATE text-buf 80 chars allot
                   5844: 
                   5845: text-buf 0 chars c@@ \ the 1st character (offset 0)
                   5846: text-buf 3 chars c@@ \ the 4th character (offset 3)
                   5847: @end example
1.29      crook    5848: 
1.44      crook    5849: You can build arbitrarily complex data structures by allocating
1.49      anton    5850: appropriate areas of memory. For further discussions of this, and to
                   5851: learn about some Gforth tools that make it easier, see
                   5852: @xref{Structures}.
1.44      crook    5853: 
                   5854: 
                   5855: @node Variables, Constants, CREATE, Defining Words
                   5856: @subsection Variables
                   5857: @cindex variables
                   5858: 
                   5859: The previous section showed how a sequence of commands could be used to
                   5860: generate a variable.  As a final refinement, the whole code sequence can
                   5861: be wrapped up in a defining word (pre-empting the subject of the next
                   5862: section), making it easier to create new variables:
                   5863: 
                   5864: @example
                   5865: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
                   5866: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
                   5867: 
                   5868: myvariableX foo \ variable foo starts off with an unknown value
                   5869: myvariable0 joe \ whilst joe is initialised to 0
1.29      crook    5870: 
                   5871: 45 3 * foo !   \ set foo to 135
                   5872: 1234 joe !     \ set joe to 1234
                   5873: 3 joe +!       \ increment joe by 3.. to 1237
                   5874: @end example
                   5875: 
                   5876: Not surprisingly, there is no need to define @code{myvariable}, since
1.44      crook    5877: Forth already has a definition @code{Variable}. ANS Forth does not
                   5878: require a @code{Variable} to be initialised when it is created (i.e., it
                   5879: behaves like @code{myvariableX}). In contrast, Gforth's @code{Variable}
                   5880: initialises the variable to 0 (i.e., it behaves exactly like
                   5881: @code{myvariable0}). Forth also provides @code{2Variable} and
1.47      crook    5882: @code{fvariable} for double and floating-point variables, respectively
                   5883: -- both are initialised to 0 in Gforth. If you use a @code{Variable} to
                   5884: store a boolean, you can use @code{on} and @code{off} to toggle its
                   5885: state.
1.29      crook    5886: 
1.34      anton    5887: doc-variable
                   5888: doc-2variable
                   5889: doc-fvariable
                   5890: 
1.29      crook    5891: @cindex user variables
                   5892: @cindex user space
                   5893: The defining word @code{User} behaves in the same way as @code{Variable}.
                   5894: The difference is that it reserves space in @i{user (data) space} rather
                   5895: than normal data space. In a Forth system that has a multi-tasker, each
                   5896: task has its own set of user variables.
                   5897: 
1.34      anton    5898: doc-user
                   5899: 
1.29      crook    5900: @comment TODO is that stuff about user variables strictly correct? Is it
                   5901: @comment just terminal tasks that have user variables?
                   5902: @comment should document tasker.fs (with some examples) elsewhere
                   5903: @comment in this manual, then expand on user space and user variables.
                   5904: 
1.44      crook    5905: 
                   5906: @node Constants, Values, Variables, Defining Words
                   5907: @subsection Constants
                   5908: @cindex constants
                   5909: 
                   5910: @code{Constant} allows you to declare a fixed value and refer to it by
                   5911: name. For example:
1.29      crook    5912: 
                   5913: @example
                   5914: 12 Constant INCHES-PER-FOOT
                   5915: 3E+08 fconstant SPEED-O-LIGHT
                   5916: @end example
                   5917: 
                   5918: A @code{Variable} can be both read and written, so its run-time
                   5919: behaviour is to supply an address through which its current value can be
                   5920: manipulated. In contrast, the value of a @code{Constant} cannot be
                   5921: changed once it has been declared@footnote{Well, often it can be -- but
                   5922: not in a Standard, portable way. It's safer to use a @code{Value} (read
                   5923: on).} so it's not necessary to supply the address -- it is more
                   5924: efficient to return the value of the constant directly. That's exactly
                   5925: what happens; the run-time effect of a constant is to put its value on
1.49      anton    5926: the top of the stack (You can find one
                   5927: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29      crook    5928: 
                   5929: Gforth also provides @code{2Constant} and @code{fconstant} for defining
                   5930: double and floating-point constants, respectively.
                   5931: 
1.34      anton    5932: doc-constant
                   5933: doc-2constant
                   5934: doc-fconstant
                   5935: 
                   5936: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44      crook    5937: @c nac-> How could that not be true in an ANS Forth? You can't define a
                   5938: @c constant, use it and then delete the definition of the constant..
                   5939: @c I agree that it's rather deep, but IMO it is an important difference
                   5940: @c relative to other programming languages.. often it's annoying: it
                   5941: @c certainly changes my programming style relative to C.
                   5942: 
1.29      crook    5943: Constants in Forth behave differently from their equivalents in other
                   5944: programming languages. In other languages, a constant (such as an EQU in
                   5945: assembler or a #define in C) only exists at compile-time; in the
                   5946: executable program the constant has been translated into an absolute
                   5947: number and, unless you are using a symbolic debugger, it's impossible to
                   5948: know what abstract thing that number represents. In Forth a constant has
1.44      crook    5949: an entry in the header space and remains there after the code that uses
                   5950: it has been defined. In fact, it must remain in the dictionary since it
                   5951: has run-time duties to perform. For example:
1.29      crook    5952: 
                   5953: @example
                   5954: 12 Constant INCHES-PER-FOOT
                   5955: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
                   5956: @end example
                   5957: 
                   5958: @cindex in-lining of constants
                   5959: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
                   5960: associated with the constant @code{INCHES-PER-FOOT}. If you use
                   5961: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
                   5962: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
                   5963: attempt to optimise constants by in-lining them where they are used. You
                   5964: can force Gforth to in-line a constant like this:
                   5965: 
                   5966: @example
                   5967: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
                   5968: @end example
                   5969: 
                   5970: If you use @code{see} to decompile @i{this} version of
                   5971: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49      anton    5972: longer present. To understand how this works, read
                   5973: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29      crook    5974: 
                   5975: In-lining constants in this way might improve execution time
                   5976: fractionally, and can ensure that a constant is now only referenced at
                   5977: compile-time. However, the definition of the constant still remains in
                   5978: the dictionary. Some Forth compilers provide a mechanism for controlling
                   5979: a second dictionary for holding transient words such that this second
                   5980: dictionary can be deleted later in order to recover memory
                   5981: space. However, there is no standard way of doing this.
                   5982: 
                   5983: 
1.44      crook    5984: @node Values, Colon Definitions, Constants, Defining Words
                   5985: @subsection Values
                   5986: @cindex values
1.34      anton    5987: 
1.44      crook    5988: A @code{Value} is like a @code{Variable} but with two important
                   5989: differences:
1.29      crook    5990: 
                   5991: @itemize @bullet
                   5992: @item
1.44      crook    5993: A @code{Value} is initialised when it is declared; like a
                   5994: @code{Constant} but unlike a @code{Variable}.
1.29      crook    5995: @item
1.44      crook    5996: A @code{Value} returns its value rather than its address when it is
                   5997: executed; i.e., it has the same run-time behaviour as @code{Constant}.
1.29      crook    5998: @end itemize
                   5999: 
1.44      crook    6000: A @code{Value} needs an additional word, @code{TO} to allow its value to
                   6001: be changed. Here are some examples:
1.29      crook    6002: 
                   6003: @example
1.44      crook    6004: 12 Value APPLES \ Define APPLES with an initial value of 12
                   6005: 34 TO APPLES    \ Change the value of APPLES. TO is a parsing word
                   6006: APPLES          \ puts 34 on the top of the stack.
1.29      crook    6007: @end example
                   6008: 
1.44      crook    6009: doc-value
                   6010: doc-to
1.29      crook    6011: 
1.35      anton    6012: 
1.44      crook    6013: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
                   6014: @subsection Colon Definitions
                   6015: @cindex colon definitions
1.35      anton    6016: 
                   6017: @example
1.44      crook    6018: : name ( ... -- ... )
                   6019:     word1 word2 word3 ;
1.29      crook    6020: @end example
                   6021: 
1.44      crook    6022: @noindent
                   6023: Creates a word called @code{name} that, upon execution, executes
                   6024: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29      crook    6025: 
1.49      anton    6026: The explanation above is somewhat superficial. For simple examples of
                   6027: colon definitions see @ref{Your first definition}.  For an in-depth
                   6028: discussion of some of the issues involved, see @xref{Interpretation and
                   6029: Compilation Semantics}.
1.29      crook    6030: 
1.44      crook    6031: doc-:
                   6032: doc-;
1.1       anton    6033: 
1.34      anton    6034: 
1.44      crook    6035: @node Anonymous Definitions, User-defined Defining Words, Colon Definitions, Defining Words
                   6036: @subsection Anonymous Definitions
                   6037: @cindex colon definitions
                   6038: @cindex defining words without name
1.34      anton    6039: 
1.44      crook    6040: Sometimes you want to define an @dfn{anonymous word}; a word without a
                   6041: name. You can do this with:
1.1       anton    6042: 
1.44      crook    6043: doc-:noname
1.1       anton    6044: 
1.44      crook    6045: This leaves the execution token for the word on the stack after the
                   6046: closing @code{;}. Here's an example in which a deferred word is
                   6047: initialised with an @code{xt} from an anonymous colon definition:
1.1       anton    6048: 
1.29      crook    6049: @example
1.44      crook    6050: Defer deferred
                   6051: :noname ( ... -- ... )
                   6052:   ... ;
                   6053: IS deferred
1.29      crook    6054: @end example
1.26      crook    6055: 
1.44      crook    6056: @noindent
                   6057: Gforth provides an alternative way of doing this, using two separate
                   6058: words:
1.27      crook    6059: 
1.44      crook    6060: doc-noname
                   6061: @cindex execution token of last defined word
                   6062: doc-lastxt
1.1       anton    6063: 
1.44      crook    6064: @noindent
                   6065: The previous example can be rewritten using @code{noname} and
                   6066: @code{lastxt}:
1.1       anton    6067: 
1.26      crook    6068: @example
1.44      crook    6069: Defer deferred
                   6070: noname : ( ... -- ... )
                   6071:   ... ;
                   6072: lastxt IS deferred
1.26      crook    6073: @end example
1.1       anton    6074: 
1.29      crook    6075: @noindent
1.44      crook    6076: @code{noname} works with any defining word, not just @code{:}.
                   6077: 
                   6078: @code{lastxt} also works when the last word was not defined as
                   6079: @code{noname}. It also has the useful property that is is valid as soon
                   6080: as the header for a definition has been built. Thus:
                   6081: 
                   6082: @example
                   6083: lastxt . : foo [ lastxt . ] ; ' foo .
                   6084: @end example
1.1       anton    6085: 
1.44      crook    6086: @noindent
                   6087: prints 3 numbers; the last two are the same.
1.26      crook    6088: 
1.1       anton    6089: 
1.44      crook    6090: @node User-defined Defining Words, Deferred words, Anonymous Definitions, Defining Words
1.26      crook    6091: @subsection User-defined Defining Words
                   6092: @cindex user-defined defining words
                   6093: @cindex defining words, user-defined
1.1       anton    6094: 
1.29      crook    6095: You can create a new defining word by wrapping defining-time code around
                   6096: an existing defining word and putting the sequence in a colon
                   6097: definition. For example, suppose that you have a word @code{stats} that
                   6098: gathers statistics about colon definitions given the @i{xt} of the
                   6099: definition, and you want every colon definition in your application to
                   6100: make a call to @code{stats}. You can define and use a new version of
                   6101: @code{:} like this:
                   6102: 
                   6103: @example
                   6104: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
                   6105:   ... ;  \ other code
                   6106: 
                   6107: : my: : lastxt postpone literal ['] stats compile, ;
                   6108: 
                   6109: my: foo + - ;
                   6110: @end example
                   6111: 
                   6112: When @code{foo} is defined using @code{my:} these steps occur:
                   6113: 
                   6114: @itemize @bullet
                   6115: @item
                   6116: @code{my:} is executed.
                   6117: @item
                   6118: The @code{:} within the definition (the one between @code{my:} and
                   6119: @code{lastxt}) is executed, and does just what it always does; it parses
                   6120: the input stream for a name, builds a dictionary header for the name
                   6121: @code{foo} and switches @code{state} from interpret to compile.
                   6122: @item
                   6123: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
                   6124: being defined -- @code{foo} -- onto the stack.
                   6125: @item
                   6126: The code that was produced by @code{postpone literal} is executed; this
                   6127: causes the value on the stack to be compiled as a literal in the code
                   6128: area of @code{foo}.
                   6129: @item
                   6130: The code @code{['] stats} compiles a literal into the definition of
                   6131: @code{my:}. When @code{compile,} is executed, that literal -- the
                   6132: execution token for @code{stats} -- is layed down in the code area of
                   6133: @code{foo} , following the literal@footnote{Strictly speaking, the
                   6134: mechanism that @code{compile,} uses to convert an @i{xt} into something
                   6135: in the code area is implementation-dependent. A threaded implementation
                   6136: might spit out the execution token directly whilst another
                   6137: implementation might spit out a native code sequence.}.
                   6138: @item
                   6139: At this point, the execution of @code{my:} is complete, and control
                   6140: returns to the text interpreter. The text interpreter is in compile
                   6141: state, so subsequent text @code{+ -} is compiled into the definition of
                   6142: @code{foo} and the @code{;} terminates the definition as always.
                   6143: @end itemize
                   6144: 
                   6145: You can use @code{see} to decompile a word that was defined using
                   6146: @code{my:} and see how it is different from a normal @code{:}
                   6147: definition. For example:
                   6148: 
                   6149: @example
                   6150: : bar + - ;  \ like foo but using : rather than my:
                   6151: see bar
                   6152: : bar
                   6153:   + - ;
                   6154: see foo
                   6155: : foo
                   6156:   107645672 stats + - ;
                   6157: 
                   6158: \ use ' stats . to show that 107645672 is the xt for stats
                   6159: @end example
                   6160: 
                   6161: You can use techniques like this to make new defining words in terms of
                   6162: @i{any} existing defining word.
1.1       anton    6163: 
                   6164: 
1.29      crook    6165: @cindex defining defining words
1.26      crook    6166: @cindex @code{CREATE} ... @code{DOES>}
                   6167: If you want the words defined with your defining words to behave
                   6168: differently from words defined with standard defining words, you can
                   6169: write your defining word like this:
1.1       anton    6170: 
                   6171: @example
1.26      crook    6172: : def-word ( "name" -- )
1.29      crook    6173:     CREATE @i{code1}
1.26      crook    6174: DOES> ( ... -- ... )
1.29      crook    6175:     @i{code2} ;
1.26      crook    6176: 
                   6177: def-word name
1.1       anton    6178: @end example
                   6179: 
1.29      crook    6180: @cindex child words
                   6181: This fragment defines a @dfn{defining word} @code{def-word} and then
                   6182: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
                   6183: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
                   6184: is not executed at this time. The word @code{name} is sometimes called a
                   6185: @dfn{child} of @code{def-word}.
                   6186: 
                   6187: When you execute @code{name}, the address of the body of @code{name} is
                   6188: put on the data stack and @i{code2} is executed (the address of the body
                   6189: of @code{name} is the address @code{HERE} returns immediately after the
                   6190: @code{CREATE}).
                   6191: 
                   6192: @cindex atavism in child words
1.33      anton    6193: You can use @code{def-word} to define a set of child words that behave
1.29      crook    6194: differently, though atavistically; they all have a common run-time
                   6195: behaviour determined by @i{code2}. Typically, the @i{code1} sequence
                   6196: builds a data area in the body of the child word. The structure of the
                   6197: data is common to all children of @code{def-word}, but the data values
                   6198: are specific -- and private -- to each child word. When a child word is
                   6199: executed, the address of its private data area is passed as a parameter
                   6200: on TOS to be used and manipulated@footnote{It is legitimate both to read
                   6201: and write to this data area.} by @i{code2}.
                   6202: 
                   6203: The two fragments of code that make up the defining words act (are
                   6204: executed) at two completely separate times:
1.1       anton    6205: 
1.29      crook    6206: @itemize @bullet
                   6207: @item
                   6208: At @i{define time}, the defining word executes @i{code1} to generate a
                   6209: child word
                   6210: @item
                   6211: At @i{child execution time}, when a child word is invoked, @i{code2}
                   6212: is executed, using parameters (data) that are private and specific to
                   6213: the child word.
                   6214: @end itemize
                   6215: 
1.44      crook    6216: Another way of understanding the behaviour of @code{def-word} and
                   6217: @code{name} is to say that, if you make the following definitions:
1.33      anton    6218: @example
                   6219: : def-word1 ( "name" -- )
                   6220:     CREATE @i{code1} ;
                   6221: 
                   6222: : action1 ( ... -- ... )
                   6223:     @i{code2} ;
                   6224: 
                   6225: def-word1 name1
                   6226: @end example
                   6227: 
1.44      crook    6228: @noindent
                   6229: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1       anton    6230: 
1.29      crook    6231: The classic example is that you can define @code{CONSTANT} in this way:
1.26      crook    6232: 
1.1       anton    6233: @example
1.29      crook    6234: : CONSTANT ( w "name" -- )
                   6235:     CREATE ,
1.26      crook    6236: DOES> ( -- w )
                   6237:     @@ ;
1.1       anton    6238: @end example
                   6239: 
1.29      crook    6240: @comment There is a beautiful description of how this works and what
                   6241: @comment it does in the Forthwrite 100th edition.. as well as an elegant
                   6242: @comment commentary on the Counting Fruits problem.
                   6243: 
                   6244: When you create a constant with @code{5 CONSTANT five}, a set of
                   6245: define-time actions take place; first a new word @code{five} is created,
                   6246: then the value 5 is laid down in the body of @code{five} with
1.44      crook    6247: @code{,}. When @code{five} is executed, the address of the body is put on
1.29      crook    6248: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
                   6249: no code of its own; it simply contains a data field and a pointer to the
                   6250: code that follows @code{DOES>} in its defining word. That makes words
                   6251: created in this way very compact.
                   6252: 
                   6253: The final example in this section is intended to remind you that space
                   6254: reserved in @code{CREATE}d words is @i{data} space and therefore can be
                   6255: both read and written by a Standard program@footnote{Exercise: use this
                   6256: example as a starting point for your own implementation of @code{Value}
                   6257: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
                   6258: @code{[']}.}:
                   6259: 
                   6260: @example
                   6261: : foo ( "name" -- )
                   6262:     CREATE -1 ,
                   6263: DOES> ( -- )
1.33      anton    6264:     @@ . ;
1.29      crook    6265: 
                   6266: foo first-word
                   6267: foo second-word
                   6268: 
                   6269: 123 ' first-word >BODY !
                   6270: @end example
                   6271: 
                   6272: If @code{first-word} had been a @code{CREATE}d word, we could simply
                   6273: have executed it to get the address of its data field. However, since it
                   6274: was defined to have @code{DOES>} actions, its execution semantics are to
                   6275: perform those @code{DOES>} actions. To get the address of its data field
                   6276: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
                   6277: translate the xt into the address of the data field.  When you execute
                   6278: @code{first-word}, it will display @code{123}. When you execute
                   6279: @code{second-word} it will display @code{-1}.
1.26      crook    6280: 
                   6281: @cindex stack effect of @code{DOES>}-parts
                   6282: @cindex @code{DOES>}-parts, stack effect
1.29      crook    6283: In the examples above the stack comment after the @code{DOES>} specifies
1.26      crook    6284: the stack effect of the defined words, not the stack effect of the
                   6285: following code (the following code expects the address of the body on
                   6286: the top of stack, which is not reflected in the stack comment). This is
                   6287: the convention that I use and recommend (it clashes a bit with using
                   6288: locals declarations for stack effect specification, though).
1.1       anton    6289: 
1.53      anton    6290: @menu
                   6291: * CREATE..DOES> applications::  
                   6292: * CREATE..DOES> details::       
1.59      anton    6293: * Advanced does> usage example::  
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.1       anton    6333: @example
1.26      crook    6334: : curry+ ( n1 -- )
                   6335:     CREATE ,
                   6336: DOES> ( n2 -- n1+n2 )
                   6337:     @@ + ;
                   6338: 
                   6339:  3 curry+ 3+
                   6340: -2 curry+ 2-
1.1       anton    6341: @end example
                   6342: 
1.59      anton    6343: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26      crook    6344: @subsubsection The gory details of @code{CREATE..DOES>}
                   6345: @cindex @code{CREATE} ... @code{DOES>}, details
1.1       anton    6346: 
1.26      crook    6347: doc-does>
1.1       anton    6348: 
1.26      crook    6349: @cindex @code{DOES>} in a separate definition
                   6350: This means that you need not use @code{CREATE} and @code{DOES>} in the
                   6351: same definition; you can put the @code{DOES>}-part in a separate
1.29      crook    6352: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26      crook    6353: @example
                   6354: : does1 
                   6355: DOES> ( ... -- ... )
1.44      crook    6356:     ... ;
                   6357: 
                   6358: : does2
                   6359: DOES> ( ... -- ... )
                   6360:     ... ;
                   6361: 
                   6362: : def-word ( ... -- ... )
                   6363:     create ...
                   6364:     IF
                   6365:        does1
                   6366:     ELSE
                   6367:        does2
                   6368:     ENDIF ;
                   6369: @end example
                   6370: 
                   6371: In this example, the selection of whether to use @code{does1} or
                   6372: @code{does2} is made at compile-time; at the time that the child word is
                   6373: @code{CREATE}d.
                   6374: 
                   6375: @cindex @code{DOES>} in interpretation state
                   6376: In a standard program you can apply a @code{DOES>}-part only if the last
                   6377: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
                   6378: will override the behaviour of the last word defined in any case. In a
                   6379: standard program, you can use @code{DOES>} only in a colon
                   6380: definition. In Gforth, you can also use it in interpretation state, in a
                   6381: kind of one-shot mode; for example:
                   6382: @example
                   6383: CREATE name ( ... -- ... )
                   6384:   @i{initialization}
                   6385: DOES>
                   6386:   @i{code} ;
                   6387: @end example
                   6388: 
                   6389: @noindent
                   6390: is equivalent to the standard:
                   6391: @example
                   6392: :noname
                   6393: DOES>
                   6394:     @i{code} ;
                   6395: CREATE name EXECUTE ( ... -- ... )
                   6396:     @i{initialization}
                   6397: @end example
                   6398: 
1.53      anton    6399: doc->body
                   6400: 
1.59      anton    6401: @node Advanced does> usage example,  , CREATE..DOES> details, User-defined Defining Words
                   6402: @subsubsection Advanced does> usage example
                   6403: 
                   6404: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
                   6405: for disassembling instructions, that follow a very repetetive scheme:
                   6406: 
                   6407: @example
                   6408: :noname @var{disasm-operands} s" @var{inst-name}" type ;
                   6409: @var{entry-num} cells @var{table} + !
                   6410: @end example
                   6411: 
                   6412: Of course, this inspires the idea to factor out the commonalities to
                   6413: allow a definition like
                   6414: 
                   6415: @example
                   6416: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
                   6417: @end example
                   6418: 
                   6419: The parameters @var{disasm-operands} and @var{table} are usually
                   6420: correlated.  Moreover, there existed code defining instructions like
                   6421: this:
                   6422: 
                   6423: @example
                   6424: @var{entry-num} @var{inst-format} @var{inst-name}
                   6425: @end example
                   6426: 
                   6427: This code comes from the assembler and resides in
                   6428: @file{arch/mips/insts.fs}.
                   6429: 
                   6430: So I had to define the @var{inst-format} words that performed the scheme
                   6431: above when executed.  At first I chose to use run-time code-generation:
                   6432: 
                   6433: @example
                   6434: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
                   6435:   :noname Postpone @var{disasm-operands}
                   6436:   name Postpone sliteral Postpone type Postpone ;
                   6437:   swap cells @var{table} + ! ;
                   6438: @end example
                   6439: 
                   6440: Note that this supplies the other two parameters of the scheme above.
1.44      crook    6441: 
1.59      anton    6442: An alternative would have been to write this using
                   6443: @code{create}/@code{does>}:
                   6444: 
                   6445: @example
                   6446: : @var{inst-format} ( entry-num "name" -- )
                   6447:   here name string, ( entry-num c-addr ) \ parse and save "name"
                   6448:   noname create , ( entry-num )
                   6449:   lastxt swap cells @var{table} + !
                   6450: does> ( addr w -- )
                   6451:   \ disassemble instruction w at addr
                   6452:   @@ >r 
                   6453:   @var{disasm-operands}
                   6454:   r> count type ;
                   6455: @end example
                   6456: 
                   6457: Somehow the first solution is simpler, mainly because it's simpler to
                   6458: shift a string from definition-time to use-time with @code{sliteral}
                   6459: than with @code{string,} and friends.
                   6460: 
                   6461: I wrote a lot of words following this scheme and soon thought about
                   6462: factoring out the commonalities among them.  Note that this uses a
                   6463: two-level defining word, i.e., a word that defines ordinary defining
                   6464: words.
                   6465: 
                   6466: This time a solution involving @code{postpone} and friends seemed more
                   6467: difficult (try it as an exercise), so I decided to use a
                   6468: @code{create}/@code{does>} word; since I was already at it, I also used
                   6469: @code{create}/@code{does>} for the lower level (try using
                   6470: @code{postpone} etc. as an exercise), resulting in the following
                   6471: definition:
                   6472: 
                   6473: @example
                   6474: : define-format ( disasm-xt table-xt -- )
                   6475:     \ define an instruction format that uses disasm-xt for
                   6476:     \ disassembling and enters the defined instructions into table
                   6477:     \ table-xt
                   6478:     create 2,
                   6479: does> ( u "inst" -- )
                   6480:     \ defines an anonymous word for disassembling instruction inst,
                   6481:     \ and enters it as u-th entry into table-xt
                   6482:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
                   6483:     noname create 2,      \ define anonymous word
                   6484:     execute lastxt swap ! \ enter xt of defined word into table-xt
                   6485: does> ( addr w -- )
                   6486:     \ disassemble instruction w at addr
                   6487:     2@@ >r ( addr w disasm-xt R: c-addr )
                   6488:     execute ( R: c-addr ) \ disassemble operands
                   6489:     r> count type ; \ print name 
                   6490: @end example
                   6491: 
                   6492: Note that the tables here (in contrast to above) do the @code{cells +}
                   6493: by themselves (that's why you have to pass an xt).  This word is used in
                   6494: the following way:
                   6495: 
                   6496: @example
                   6497: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
                   6498: @end example
                   6499: 
                   6500: In terms of currying, this kind of two-level defining word provides the
                   6501: parameters in three stages: first @var{disasm-operands} and @var{table},
                   6502: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
                   6503: the instruction to be disassembled.  
                   6504: 
                   6505: Of course this did not quite fit all the instruction format names used
                   6506: in @file{insts.fs}, so I had to define a few wrappers that conditioned
                   6507: the parameters into the right form.
                   6508: 
                   6509: If you have trouble following this section, don't worry.  First, this is
                   6510: involved and takes time (and probably some playing around) to
                   6511: understand; second, this is the first two-level
                   6512: @code{create}/@code{does>} word I have written in seventeen years of
                   6513: Forth; and if I did not have @file{insts.fs} to start with, I may well
                   6514: have elected to use just a one-level defining word (with some repeating
                   6515: of parameters when using the defining word). So it is not necessary to
                   6516: understand this, but it may improve your understanding of Forth.
1.44      crook    6517: 
                   6518: 
                   6519: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
                   6520: @subsection Deferred words
                   6521: @cindex deferred words
                   6522: 
                   6523: The defining word @code{Defer} allows you to define a word by name
                   6524: without defining its behaviour; the definition of its behaviour is
                   6525: deferred. Here are two situation where this can be useful:
                   6526: 
                   6527: @itemize @bullet
                   6528: @item
                   6529: Where you want to allow the behaviour of a word to be altered later, and
                   6530: for all precompiled references to the word to change when its behaviour
                   6531: is changed.
                   6532: @item
                   6533: For mutual recursion; @xref{Calls and returns}.
                   6534: @end itemize
                   6535: 
                   6536: In the following example, @code{foo} always invokes the version of
                   6537: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
                   6538: always invokes the version that prints ``@code{Hello}''. There is no way
                   6539: of getting @code{foo} to use the later version without re-ordering the
                   6540: source code and recompiling it.
                   6541: 
                   6542: @example
                   6543: : greet ." Good morning" ;
                   6544: : foo ... greet ... ;
                   6545: : greet ." Hello" ;
                   6546: : bar ... greet ... ;
                   6547: @end example
                   6548: 
                   6549: This problem can be solved by defining @code{greet} as a @code{Defer}red
                   6550: word. The behaviour of a @code{Defer}red word can be defined and
                   6551: redefined at any time by using @code{IS} to associate the xt of a
                   6552: previously-defined word with it. The previous example becomes:
                   6553: 
                   6554: @example
                   6555: Defer greet
                   6556: : foo ... greet ... ;
                   6557: : bar ... greet ... ;
                   6558: : greet1 ." Good morning" ;
                   6559: : greet2 ." Hello" ;
                   6560: ' greet2 <IS> greet  \ make greet behave like greet2
                   6561: @end example
                   6562: 
                   6563: A deferred word can be used to improve the statistics-gathering example
                   6564: from @ref{User-defined Defining Words}; rather than edit the
                   6565: application's source code to change every @code{:} to a @code{my:}, do
                   6566: this:
                   6567: 
                   6568: @example
                   6569: : real: : ;     \ retain access to the original
                   6570: defer :         \ redefine as a deferred word
                   6571: ' my: IS :      \ use special version of :
                   6572: \
                   6573: \ load application here
                   6574: \
                   6575: ' real: IS :    \ go back to the original
                   6576: @end example
                   6577: 
                   6578: 
                   6579: One thing to note is that @code{<IS>} consumes its name when it is
                   6580: executed.  If you want to specify the name at compile time, use
                   6581: @code{[IS]}:
                   6582: 
                   6583: @example
                   6584: : set-greet ( xt -- )
                   6585:   [IS] greet ;
                   6586: 
                   6587: ' greet1 set-greet
                   6588: @end example
                   6589: 
                   6590: A deferred word can only inherit default semantics from the xt (because
1.49      anton    6591: that is all that an xt can represent -- for more discussion of this
                   6592: @pxref{Tokens for Words}). However, the semantics of the deferred word
1.44      crook    6593: itself can be modified at the time that it is defined. For example:
                   6594: 
                   6595: @example
                   6596: : bar .... ; compile-only
                   6597: Defer fred immediate
                   6598: Defer jim
                   6599: 
                   6600: ' bar <IS> jim  \ jim has default semantics
                   6601: ' bar <IS> fred \ fred is immediate
                   6602: @end example
                   6603: 
                   6604: doc-defer
                   6605: doc-<is>
                   6606: doc-[is]
                   6607: doc-is
                   6608: @comment TODO document these: what's defers [is]
                   6609: doc-what's
                   6610: doc-defers
                   6611: 
                   6612: @c Use @code{words-deferred} to see a list of deferred words.
                   6613: 
                   6614: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
                   6615: are provided in @file{compat/defer.fs}.
                   6616: 
                   6617: 
                   6618: @node Aliases, Supplying names, Deferred words, Defining Words
                   6619: @subsection Aliases
                   6620: @cindex aliases
1.1       anton    6621: 
1.44      crook    6622: The defining word @code{Alias} allows you to define a word by name that
                   6623: has the same behaviour as some other word. Here are two situation where
                   6624: this can be useful:
1.1       anton    6625: 
1.44      crook    6626: @itemize @bullet
                   6627: @item
                   6628: When you want access to a word's definition from a different word list
                   6629: (for an example of this, see the definition of the @code{Root} word list
                   6630: in the Gforth source).
                   6631: @item
                   6632: When you want to create a synonym; a definition that can be known by
                   6633: either of two names (for example, @code{THEN} and @code{ENDIF} are
                   6634: aliases).
                   6635: @end itemize
1.1       anton    6636: 
1.44      crook    6637: The word whose behaviour the alias is to inherit is represented by an
                   6638: xt. Therefore, the alias only inherits default semantics from its
                   6639: ancestor. The semantics of the alias itself can be modified at the time
                   6640: that it is defined. For example:
1.1       anton    6641: 
                   6642: @example
1.44      crook    6643: : foo ... ; immediate
                   6644: 
                   6645: ' foo Alias bar \ bar is not an immediate word
                   6646: ' foo Alias fooby immediate \ fooby is an immediate word
1.1       anton    6647: @end example
                   6648: 
1.44      crook    6649: Words that are aliases have the same xt, different headers in the
                   6650: dictionary, and consequently different name tokens (@pxref{Tokens for
                   6651: Words}) and possibly different immediate flags.  An alias can only have
                   6652: default or immediate compilation semantics; you can define aliases for
                   6653: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1       anton    6654: 
1.44      crook    6655: doc-alias
1.26      crook    6656: 
1.1       anton    6657: 
1.52      anton    6658: @node Supplying names,  , Aliases, Defining Words
1.29      crook    6659: @subsection Supplying the name of a defined word
1.26      crook    6660: @cindex names for defined words
1.44      crook    6661: @cindex defining words, name given in a string
1.1       anton    6662: 
1.29      crook    6663: By default, a defining word takes the name for the defined word from the
1.26      crook    6664: input stream. Sometimes you want to supply the name from a string. You
                   6665: can do this with:
1.1       anton    6666: 
1.26      crook    6667: doc-nextname
1.1       anton    6668: 
1.26      crook    6669: For example:
1.1       anton    6670: 
1.26      crook    6671: @example
                   6672: s" foo" nextname create
                   6673: @end example
1.44      crook    6674: 
1.26      crook    6675: @noindent
                   6676: is equivalent to:
1.44      crook    6677: 
1.26      crook    6678: @example
                   6679: create foo
                   6680: @end example
1.1       anton    6681: 
1.29      crook    6682: @noindent
1.44      crook    6683: @code{nextname} works with any defining word, not just @code{:}.
1.1       anton    6684: 
                   6685: 
1.47      crook    6686: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
                   6687: @section Interpretation and Compilation Semantics
1.26      crook    6688: @cindex semantics, interpretation and compilation
1.1       anton    6689: 
1.26      crook    6690: @cindex interpretation semantics
                   6691: The @dfn{interpretation semantics} of a word are what the text
                   6692: interpreter does when it encounters the word in interpret state. It also
                   6693: appears in some other contexts, e.g., the execution token returned by
1.29      crook    6694: @code{' @i{word}} identifies the interpretation semantics of
                   6695: @i{word} (in other words, @code{' @i{word} execute} is equivalent to
                   6696: interpret-state text interpretation of @code{@i{word}}).
1.1       anton    6697: 
1.26      crook    6698: @cindex compilation semantics
                   6699: The @dfn{compilation semantics} of a word are what the text interpreter
                   6700: does when it encounters the word in compile state. It also appears in
1.29      crook    6701: other contexts, e.g, @code{POSTPONE @i{word}} compiles@footnote{In
1.26      crook    6702: standard terminology, ``appends to the current definition''.} the
1.29      crook    6703: compilation semantics of @i{word}.
1.1       anton    6704: 
1.26      crook    6705: @cindex execution semantics
                   6706: The standard also talks about @dfn{execution semantics}. They are used
                   6707: only for defining the interpretation and compilation semantics of many
                   6708: words. By default, the interpretation semantics of a word are to
                   6709: @code{execute} its execution semantics, and the compilation semantics of
                   6710: a word are to @code{compile,} its execution semantics.@footnote{In
                   6711: standard terminology: The default interpretation semantics are its
                   6712: execution semantics; the default compilation semantics are to append its
                   6713: execution semantics to the execution semantics of the current
                   6714: definition.}
                   6715: 
                   6716: @comment TODO expand, make it co-operate with new sections on text interpreter.
                   6717: 
                   6718: @cindex immediate words
                   6719: @cindex compile-only words
                   6720: You can change the semantics of the most-recently defined word:
                   6721: 
1.44      crook    6722: 
1.26      crook    6723: doc-immediate
                   6724: doc-compile-only
                   6725: doc-restrict
                   6726: 
1.44      crook    6727: 
1.26      crook    6728: Note that ticking (@code{'}) a compile-only word gives an error
                   6729: (``Interpreting a compile-only word'').
1.1       anton    6730: 
1.47      crook    6731: @menu
                   6732: * Combined words::
                   6733: @end menu
1.44      crook    6734: 
1.48      anton    6735: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44      crook    6736: @subsection Combined Words
                   6737: @cindex combined words
                   6738: 
                   6739: Gforth allows you to define @dfn{combined words} -- words that have an
                   6740: arbitrary combination of interpretation and compilation semantics.
                   6741: 
1.1       anton    6742: 
1.26      crook    6743: doc-interpret/compile:
1.1       anton    6744: 
1.44      crook    6745: 
1.26      crook    6746: This feature was introduced for implementing @code{TO} and @code{S"}. I
                   6747: recommend that you do not define such words, as cute as they may be:
                   6748: they make it hard to get at both parts of the word in some contexts.
                   6749: E.g., assume you want to get an execution token for the compilation
                   6750: part. Instead, define two words, one that embodies the interpretation
                   6751: part, and one that embodies the compilation part.  Once you have done
                   6752: that, you can define a combined word with @code{interpret/compile:} for
                   6753: the convenience of your users.
1.1       anton    6754: 
1.26      crook    6755: You might try to use this feature to provide an optimizing
                   6756: implementation of the default compilation semantics of a word. For
                   6757: example, by defining:
1.1       anton    6758: @example
1.26      crook    6759: :noname
                   6760:    foo bar ;
                   6761: :noname
                   6762:    POSTPONE foo POSTPONE bar ;
1.29      crook    6763: interpret/compile: opti-foobar
1.1       anton    6764: @end example
1.26      crook    6765: 
1.23      crook    6766: @noindent
1.26      crook    6767: as an optimizing version of:
                   6768: 
1.1       anton    6769: @example
1.26      crook    6770: : foobar
                   6771:     foo bar ;
1.1       anton    6772: @end example
                   6773: 
1.26      crook    6774: Unfortunately, this does not work correctly with @code{[compile]},
                   6775: because @code{[compile]} assumes that the compilation semantics of all
                   6776: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29      crook    6777: opti-foobar} would compile compilation semantics, whereas
                   6778: @code{[compile] foobar} would compile interpretation semantics.
1.1       anton    6779: 
1.26      crook    6780: @cindex state-smart words (are a bad idea)
1.29      crook    6781: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26      crook    6782: by @code{interpret/compile:} (words are state-smart if they check
                   6783: @code{STATE} during execution). E.g., they would try to code
                   6784: @code{foobar} like this:
1.1       anton    6785: 
1.26      crook    6786: @example
                   6787: : foobar
                   6788:   STATE @@
                   6789:   IF ( compilation state )
                   6790:     POSTPONE foo POSTPONE bar
                   6791:   ELSE
                   6792:     foo bar
                   6793:   ENDIF ; immediate
                   6794: @end example
1.1       anton    6795: 
1.26      crook    6796: Although this works if @code{foobar} is only processed by the text
                   6797: interpreter, it does not work in other contexts (like @code{'} or
                   6798: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
                   6799: for a state-smart word, not for the interpretation semantics of the
                   6800: original @code{foobar}; when you execute this execution token (directly
                   6801: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
                   6802: state, the result will not be what you expected (i.e., it will not
                   6803: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
                   6804: write them@footnote{For a more detailed discussion of this topic, see
                   6805: @cite{@code{State}-smartness -- Why it is Evil and How to Exorcise it} by Anton
                   6806: Ertl; presented at EuroForth '98 and available from
1.47      crook    6807: @*@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz}}!
1.1       anton    6808: 
1.26      crook    6809: @cindex defining words with arbitrary semantics combinations
                   6810: It is also possible to write defining words that define words with
                   6811: arbitrary combinations of interpretation and compilation semantics. In
                   6812: general, they look like this:
1.1       anton    6813: 
1.26      crook    6814: @example
                   6815: : def-word
                   6816:     create-interpret/compile
1.29      crook    6817:     @i{code1}
1.26      crook    6818: interpretation>
1.29      crook    6819:     @i{code2}
1.26      crook    6820: <interpretation
                   6821: compilation>
1.29      crook    6822:     @i{code3}
1.26      crook    6823: <compilation ;
                   6824: @end example
1.1       anton    6825: 
1.29      crook    6826: For a @i{word} defined with @code{def-word}, the interpretation
                   6827: semantics are to push the address of the body of @i{word} and perform
                   6828: @i{code2}, and the compilation semantics are to push the address of
                   6829: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26      crook    6830: can also be defined like this (except that the defined constants don't
                   6831: behave correctly when @code{[compile]}d):
1.1       anton    6832: 
1.26      crook    6833: @example
                   6834: : constant ( n "name" -- )
                   6835:     create-interpret/compile
                   6836:     ,
                   6837: interpretation> ( -- n )
                   6838:     @@
                   6839: <interpretation
                   6840: compilation> ( compilation. -- ; run-time. -- n )
                   6841:     @@ postpone literal
                   6842: <compilation ;
                   6843: @end example
1.1       anton    6844: 
1.44      crook    6845: 
1.26      crook    6846: doc-create-interpret/compile
                   6847: doc-interpretation>
                   6848: doc-<interpretation
                   6849: doc-compilation>
                   6850: doc-<compilation
1.1       anton    6851: 
1.44      crook    6852: 
1.29      crook    6853: Words defined with @code{interpret/compile:} and
1.26      crook    6854: @code{create-interpret/compile} have an extended header structure that
                   6855: differs from other words; however, unless you try to access them with
                   6856: plain address arithmetic, you should not notice this. Words for
                   6857: accessing the header structure usually know how to deal with this; e.g.,
1.29      crook    6858: @code{'} @i{word} @code{>body} also gives you the body of a word created
                   6859: with @code{create-interpret/compile}.
1.1       anton    6860: 
1.44      crook    6861: 
1.27      crook    6862: doc-postpone
1.44      crook    6863: 
1.29      crook    6864: @comment TODO -- expand glossary text for POSTPONE
1.27      crook    6865: 
1.47      crook    6866: 
                   6867: @c -------------------------------------------------------------
                   6868: @node Tokens for Words, The Text Interpreter, Interpretation and Compilation Semantics, Words
                   6869: @section Tokens for Words
                   6870: @cindex tokens for words
                   6871: 
                   6872: This section describes the creation and use of tokens that represent
                   6873: words.
                   6874: 
                   6875: Named words have information stored in their header space entries to
                   6876: indicate any non-default semantics (@pxref{Interpretation and
                   6877: Compilation Semantics}). The semantics can be modified, using
                   6878: @code{immediate} and/or @code{compile-only}, at the time that the words
                   6879: are defined. Unnamed words have (by definition) no header space
                   6880: entry, and therefore must have default semantics.
                   6881: 
                   6882: Named words have interpretation and compilation semantics. Unnamed words
                   6883: just have execution semantics.
                   6884: 
                   6885: @cindex xt
                   6886: @cindex execution token
                   6887: The execution semantics of an unnamed word are represented by an
                   6888: @dfn{execution token} (@i{xt}). As explained in @ref{Supplying names},
                   6889: the execution token of the last word defined can be produced with
                   6890: @code{lastxt}.
                   6891: 
                   6892: The interpretation semantics of a named word are also represented by an
                   6893: execution token. You can produce the execution token using @code{'} or
                   6894: @code{[']}. A simple example shows the difference between the two:
                   6895: 
                   6896: @example
                   6897: : greet ( -- )   ." Hello" ;
                   6898: : foo ( -- xt )  ['] greet execute ; \ ['] parses greet at compile-time
                   6899: : bar ( -- )     ' execute ; \  '  parses at run-time
                   6900: 
                   6901: \ the next four lines all do the same thing
                   6902: foo
                   6903: bar greet
                   6904: greet
                   6905: ' greet EXECUTE
                   6906: @end example
                   6907: 
                   6908: An execution token occupies one cell.
                   6909: @cindex code field address
                   6910: @cindex CFA
                   6911: In Gforth, the abstract data type @i{execution token} is implemented
                   6912: as a code field address (CFA).
                   6913: @comment TODO note that the standard does not say what it represents..
                   6914: @comment and you cannot necessarily compile it in all Forths (eg native
                   6915: @comment compilers?).
                   6916: 
                   6917: For literals, use @code{'} in interpreted code and @code{[']} in
                   6918: compiled code. Gforth's @code{'} and @code{[']} behave somewhat
                   6919: unusually by complaining about compile-only words. To get the execution
                   6920: token for a compile-only word @i{name}, use @code{COMP' @i{name} DROP}
                   6921: or @code{[COMP'] @i{name} DROP}.
                   6922: 
                   6923: @cindex compilation token
                   6924: The compilation semantics of a named word are represented by a
                   6925: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
                   6926: @i{xt} is an execution token. The compilation semantics represented by
                   6927: the compilation token can be performed with @code{execute}, which
                   6928: consumes the whole compilation token, with an additional stack effect
                   6929: determined by the represented compilation semantics.
                   6930: 
                   6931: At present, the @i{w} part of a compilation token is an execution token,
                   6932: and the @i{xt} part represents either @code{execute} or
                   6933: @code{compile,}@footnote{Depending upon the compilation semantics of the
                   6934: word. If the word has default compilation semantics, the @i{xt} will
                   6935: represent @code{compile,}. Otherwise (e.g., for immediate words), the
                   6936: @i{xt} will represent @code{execute}.}. However, don't rely on that
                   6937: knowledge, unless necessary; future versions of Gforth may introduce
                   6938: unusual compilation tokens (e.g., a compilation token that represents
                   6939: the compilation semantics of a literal).
                   6940: 
                   6941: You can compile the compilation semantics with @code{postpone,}. I.e.,
                   6942: @code{COMP' @i{word} postpone,} is equivalent to @code{postpone
                   6943: @i{word}}.
                   6944: 
                   6945: @cindex name token
                   6946: @cindex name field address
                   6947: @cindex NFA
                   6948: Named words are also represented by the @dfn{name token}, (@i{nt}). In
                   6949: Gforth, the abstract data type @emph{name token} is implemented as a
                   6950: name field address (NFA).
                   6951: 
                   6952: 
                   6953: doc-execute
                   6954: doc-perform
                   6955: doc-compile,
                   6956: doc-[']
                   6957: doc-'
                   6958: doc-[comp']
                   6959: doc-comp'
                   6960: doc-postpone,
                   6961: 
                   6962: doc-find-name
                   6963: doc-name>int
                   6964: doc-name?int
                   6965: doc-name>comp
                   6966: doc-name>string
                   6967: 
                   6968: 
1.26      crook    6969: @c ----------------------------------------------------------
1.47      crook    6970: @node The Text Interpreter, Word Lists, Tokens for Words, Words
1.26      crook    6971: @section  The Text Interpreter
                   6972: @cindex interpreter - outer
                   6973: @cindex text interpreter
                   6974: @cindex outer interpreter
1.1       anton    6975: 
1.34      anton    6976: @c Should we really describe all these ugly details?  IMO the text
                   6977: @c interpreter should be much cleaner, but that may not be possible within
                   6978: @c ANS Forth. - anton
1.44      crook    6979: @c nac-> I wanted to explain how it works to show how you can exploit
                   6980: @c it in your own programs. When I was writing a cross-compiler, figuring out
                   6981: @c some of these gory details was very helpful to me. None of the textbooks
                   6982: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
                   6983: @c seems to positively avoid going into too much detail for some of
                   6984: @c the internals.
1.34      anton    6985: 
1.29      crook    6986: The text interpreter@footnote{This is an expanded version of the
                   6987: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34      anton    6988: that processes input from the current input device. It is also called
                   6989: the outer interpreter, in contrast to the inner interpreter
                   6990: (@pxref{Engine}) which executes the compiled Forth code on interpretive
                   6991: implementations.
1.27      crook    6992: 
1.29      crook    6993: @cindex interpret state
                   6994: @cindex compile state
                   6995: The text interpreter operates in one of two states: @dfn{interpret
                   6996: state} and @dfn{compile state}. The current state is defined by the
                   6997: aptly-named variable, @code{state}.
                   6998: 
                   6999: This section starts by describing how the text interpreter behaves when
                   7000: it is in interpret state, processing input from the user input device --
                   7001: the keyboard. This is the mode that a Forth system is in after it starts
                   7002: up.
                   7003: 
                   7004: @cindex input buffer
                   7005: @cindex terminal input buffer
                   7006: The text interpreter works from an area of memory called the @dfn{input
                   7007: buffer}@footnote{When the text interpreter is processing input from the
                   7008: keyboard, this area of memory is called the @dfn{terminal input buffer}
                   7009: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
                   7010: @code{#TIB}.}, which stores your keyboard input when you press the
1.30      anton    7011: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29      crook    7012: leading spaces (called @dfn{delimiters}) then parses a string (a
                   7013: sequence of non-space characters) until it reaches either a space
                   7014: character or the end of the buffer. Having parsed a string, it makes two
                   7015: attempts to process it:
1.27      crook    7016: 
1.29      crook    7017: @cindex dictionary
1.27      crook    7018: @itemize @bullet
                   7019: @item
1.29      crook    7020: It looks for the string in a @dfn{dictionary} of definitions. If the
                   7021: string is found, the string names a @dfn{definition} (also known as a
                   7022: @dfn{word}) and the dictionary search returns information that allows
                   7023: the text interpreter to perform the word's @dfn{interpretation
                   7024: semantics}. In most cases, this simply means that the word will be
                   7025: executed.
1.27      crook    7026: @item
                   7027: If the string is not found in the dictionary, the text interpreter
1.29      crook    7028: attempts to treat it as a number, using the rules described in
                   7029: @ref{Number Conversion}. If the string represents a legal number in the
                   7030: current radix, the number is pushed onto a parameter stack (the data
                   7031: stack for integers, the floating-point stack for floating-point
                   7032: numbers).
                   7033: @end itemize
                   7034: 
                   7035: If both attempts fail, or if the word is found in the dictionary but has
                   7036: no interpretation semantics@footnote{This happens if the word was
                   7037: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
                   7038: remainder of the input buffer, issues an error message and waits for
                   7039: more input. If one of the attempts succeeds, the text interpreter
                   7040: repeats the parsing process until the whole of the input buffer has been
                   7041: processed, at which point it prints the status message ``@code{ ok}''
                   7042: and waits for more input.
                   7043: 
                   7044: @cindex parse area
                   7045: The text interpreter keeps track of its position in the input buffer by
                   7046: updating a variable called @code{>IN} (pronounced ``to-in''). The value
                   7047: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
                   7048: of the input buffer. The region from offset @code{>IN @@} to the end of
                   7049: the input buffer is called the @dfn{parse area}@footnote{In other words,
                   7050: the text interpreter processes the contents of the input buffer by
                   7051: parsing strings from the parse area until the parse area is empty.}.
                   7052: This example shows how @code{>IN} changes as the text interpreter parses
                   7053: the input buffer:
                   7054: 
                   7055: @example
                   7056: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
                   7057:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
                   7058: 
                   7059: 1 2 3 remaining + remaining . 
                   7060: 
                   7061: : foo 1 2 3 remaining SWAP remaining ;
                   7062: @end example
                   7063: 
                   7064: @noindent
                   7065: The result is:
                   7066: 
                   7067: @example
                   7068: ->+ remaining .<-
                   7069: ->.<-5  ok
                   7070: 
                   7071: ->SWAP remaining ;-<
                   7072: ->;<-  ok
                   7073: @end example
                   7074: 
                   7075: @cindex parsing words
                   7076: The value of @code{>IN} can also be modified by a word in the input
                   7077: buffer that is executed by the text interpreter.  This means that a word
                   7078: can ``trick'' the text interpreter into either skipping a section of the
                   7079: input buffer@footnote{This is how parsing words work.} or into parsing a
                   7080: section twice. For example:
1.27      crook    7081: 
1.29      crook    7082: @example
                   7083: : lat ." <<lat>>" ;
                   7084: : flat ." <<flat>>" >IN DUP @@ 3 - SWAP ! ;
                   7085: @end example
                   7086: 
                   7087: @noindent
                   7088: When @code{flat} is executed, this output is produced@footnote{Exercise
                   7089: for the reader: what would happen if the @code{3} were replaced with
                   7090: @code{4}?}:
                   7091: 
                   7092: @example
                   7093: <<flat>><<lat>>
                   7094: @end example
                   7095: 
                   7096: @noindent
                   7097: Two important notes about the behaviour of the text interpreter:
1.27      crook    7098: 
                   7099: @itemize @bullet
                   7100: @item
                   7101: It processes each input string to completion before parsing additional
1.29      crook    7102: characters from the input buffer.
                   7103: @item
                   7104: It treats the input buffer as a read-only region (and so must your code).
                   7105: @end itemize
                   7106: 
                   7107: @noindent
                   7108: When the text interpreter is in compile state, its behaviour changes in
                   7109: these ways:
                   7110: 
                   7111: @itemize @bullet
                   7112: @item
                   7113: If a parsed string is found in the dictionary, the text interpreter will
                   7114: perform the word's @dfn{compilation semantics}. In most cases, this
                   7115: simply means that the execution semantics of the word will be appended
                   7116: to the current definition.
1.27      crook    7117: @item
1.29      crook    7118: When a number is encountered, it is compiled into the current definition
                   7119: (as a literal) rather than being pushed onto a parameter stack.
                   7120: @item
                   7121: If an error occurs, @code{state} is modified to put the text interpreter
                   7122: back into interpret state.
                   7123: @item
                   7124: Each time a line is entered from the keyboard, Gforth prints
                   7125: ``@code{ compiled}'' rather than `` @code{ok}''.
                   7126: @end itemize
                   7127: 
                   7128: @cindex text interpreter - input sources
                   7129: When the text interpreter is using an input device other than the
                   7130: keyboard, its behaviour changes in these ways:
                   7131: 
                   7132: @itemize @bullet
                   7133: @item
                   7134: When the parse area is empty, the text interpreter attempts to refill
                   7135: the input buffer from the input source. When the input source is
                   7136: exhausted, the input source is set back to the user input device.
                   7137: @item
                   7138: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
                   7139: time the parse area is emptied.
                   7140: @item
                   7141: If an error occurs, the input source is set back to the user input
                   7142: device.
1.27      crook    7143: @end itemize
1.21      crook    7144: 
1.49      anton    7145: You can read about this in more detail in @ref{Input Sources}.
1.44      crook    7146: 
1.26      crook    7147: doc->in
1.27      crook    7148: doc-source
                   7149: 
1.26      crook    7150: doc-tib
                   7151: doc-#tib
1.1       anton    7152: 
1.44      crook    7153: 
1.26      crook    7154: @menu
1.29      crook    7155: * Input Sources::
1.26      crook    7156: * Number Conversion::
                   7157: * Interpret/Compile states::
                   7158: * Literals::
                   7159: * Interpreter Directives::
                   7160: @end menu
1.1       anton    7161: 
1.29      crook    7162: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
                   7163: @subsection Input Sources
                   7164: @cindex input sources
                   7165: @cindex text interpreter - input sources
                   7166: 
1.44      crook    7167: By default, the text interpreter processes input from the user input
1.29      crook    7168: device (the keyboard) when Forth starts up. The text interpreter can
                   7169: process input from any of these sources:
                   7170: 
                   7171: @itemize @bullet
                   7172: @item
                   7173: The user input device -- the keyboard.
                   7174: @item
                   7175: A file, using the words described in @ref{Forth source files}.
                   7176: @item
                   7177: A block, using the words described in @ref{Blocks}.
                   7178: @item
                   7179: A text string, using @code{evaluate}.
                   7180: @end itemize
                   7181: 
                   7182: A program can identify the current input device from the values of
                   7183: @code{source-id} and @code{blk}.
                   7184: 
1.44      crook    7185: 
1.29      crook    7186: doc-source-id
                   7187: doc-blk
                   7188: 
                   7189: doc-save-input
                   7190: doc-restore-input
                   7191: 
                   7192: doc-evaluate
1.1       anton    7193: 
1.29      crook    7194: 
1.44      crook    7195: 
1.29      crook    7196: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26      crook    7197: @subsection Number Conversion
                   7198: @cindex number conversion
                   7199: @cindex double-cell numbers, input format
                   7200: @cindex input format for double-cell numbers
                   7201: @cindex single-cell numbers, input format
                   7202: @cindex input format for single-cell numbers
                   7203: @cindex floating-point numbers, input format
                   7204: @cindex input format for floating-point numbers
1.1       anton    7205: 
1.29      crook    7206: This section describes the rules that the text interpreter uses when it
                   7207: tries to convert a string into a number.
1.1       anton    7208: 
1.26      crook    7209: Let <digit> represent any character that is a legal digit in the current
1.29      crook    7210: number base@footnote{For example, 0-9 when the number base is decimal or
                   7211: 0-9, A-F when the number base is hexadecimal.}.
1.1       anton    7212: 
1.26      crook    7213: Let <decimal digit> represent any character in the range 0-9.
1.1       anton    7214: 
1.29      crook    7215: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
                   7216: in the braces (@i{a} or @i{b} or neither).
1.1       anton    7217: 
1.26      crook    7218: Let * represent any number of instances of the previous character
                   7219: (including none).
1.1       anton    7220: 
1.26      crook    7221: Let any other character represent itself.
1.1       anton    7222: 
1.29      crook    7223: @noindent
1.26      crook    7224: Now, the conversion rules are:
1.21      crook    7225: 
1.26      crook    7226: @itemize @bullet
                   7227: @item
                   7228: A string of the form <digit><digit>* is treated as a single-precision
1.29      crook    7229: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26      crook    7230: @item
                   7231: A string of the form -<digit><digit>* is treated as a single-precision
1.29      crook    7232: (cell-sized) negative integer, and is represented using 2's-complement
1.26      crook    7233: arithmetic. Examples are -45 -5681 -0
                   7234: @item
                   7235: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29      crook    7236: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
                   7237: (all three of these represent the same number).
1.26      crook    7238: @item
                   7239: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29      crook    7240: double-precision (double-cell-sized) negative integer, and is
1.26      crook    7241: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29      crook    7242: -34.65 (all three of these represent the same number).
1.26      crook    7243: @item
1.29      crook    7244: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
                   7245: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35      anton    7246: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29      crook    7247: number) +12.E-4
1.26      crook    7248: @end itemize
1.1       anton    7249: 
1.26      crook    7250: By default, the number base used for integer number conversion is given
1.35      anton    7251: by the contents of the variable @code{base}.  Note that a lot of
                   7252: confusion can result from unexpected values of @code{base}.  If you
                   7253: change @code{base} anywhere, make sure to save the old value and restore
                   7254: it afterwards.  In general I recommend keeping @code{base} decimal, and
                   7255: using the prefixes described below for the popular non-decimal bases.
1.1       anton    7256: 
1.29      crook    7257: doc-dpl
1.26      crook    7258: doc-base
                   7259: doc-hex
                   7260: doc-decimal
1.1       anton    7261: 
1.44      crook    7262: 
1.26      crook    7263: @cindex '-prefix for character strings
                   7264: @cindex &-prefix for decimal numbers
                   7265: @cindex %-prefix for binary numbers
                   7266: @cindex $-prefix for hexadecimal numbers
1.35      anton    7267: Gforth allows you to override the value of @code{base} by using a
1.29      crook    7268: prefix@footnote{Some Forth implementations provide a similar scheme by
                   7269: implementing @code{$} etc. as parsing words that process the subsequent
                   7270: number in the input stream and push it onto the stack. For example, see
                   7271: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
                   7272: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
                   7273: is required between the prefix and the number.} before the first digit
                   7274: of an (integer) number. Four prefixes are supported:
1.1       anton    7275: 
1.26      crook    7276: @itemize @bullet
                   7277: @item
1.35      anton    7278: @code{&} -- decimal
1.26      crook    7279: @item
1.35      anton    7280: @code{%} -- binary
1.26      crook    7281: @item
1.35      anton    7282: @code{$} -- hexadecimal
1.26      crook    7283: @item
1.35      anton    7284: @code{'} -- base @code{max-char+1}
1.26      crook    7285: @end itemize
1.1       anton    7286: 
1.26      crook    7287: Here are some examples, with the equivalent decimal number shown after
                   7288: in braces:
1.1       anton    7289: 
1.26      crook    7290: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
                   7291: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
                   7292: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
                   7293: &905 (905), $abc (2478), $ABC (2478).
1.1       anton    7294: 
1.26      crook    7295: @cindex number conversion - traps for the unwary
1.29      crook    7296: @noindent
1.26      crook    7297: Number conversion has a number of traps for the unwary:
1.1       anton    7298: 
1.26      crook    7299: @itemize @bullet
                   7300: @item
                   7301: You cannot determine the current number base using the code sequence
1.35      anton    7302: @code{base @@ .} -- the number base is always 10 in the current number
                   7303: base. Instead, use something like @code{base @@ dec.}
1.26      crook    7304: @item
                   7305: If the number base is set to a value greater than 14 (for example,
                   7306: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
                   7307: it to be intepreted as either a single-precision integer or a
                   7308: floating-point number (Gforth treats it as an integer). The ambiguity
                   7309: can be resolved by explicitly stating the sign of the mantissa and/or
                   7310: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
                   7311: ambiguity arises; either representation will be treated as a
                   7312: floating-point number.
                   7313: @item
1.29      crook    7314: There is a word @code{bin} but it does @i{not} set the number base!
1.26      crook    7315: It is used to specify file types.
                   7316: @item
                   7317: ANS Forth requires the @code{.} of a double-precision number to
                   7318: be the final character in the string. Allowing the @code{.} to be
                   7319: anywhere after the first digit is a Gforth extension.
                   7320: @item
                   7321: The number conversion process does not check for overflow.
                   7322: @item
                   7323: In Gforth, number conversion to floating-point numbers always use base
1.35      anton    7324: 10, irrespective of the value of @code{base}. In ANS Forth,
1.26      crook    7325: conversion to floating-point numbers whilst the value of
1.35      anton    7326: @code{base} is not 10 is an ambiguous condition.
1.26      crook    7327: @end itemize
1.1       anton    7328: 
1.49      anton    7329: You can read numbers into your programs with the words described in
                   7330: @ref{Input}.
1.1       anton    7331: 
1.26      crook    7332: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
                   7333: @subsection Interpret/Compile states
                   7334: @cindex Interpret/Compile states
1.1       anton    7335: 
1.29      crook    7336: A standard program is not permitted to change @code{state}
                   7337: explicitly. However, it can change @code{state} implicitly, using the
                   7338: words @code{[} and @code{]}. When @code{[} is executed it switches
                   7339: @code{state} to interpret state, and therefore the text interpreter
                   7340: starts interpreting. When @code{]} is executed it switches @code{state}
                   7341: to compile state and therefore the text interpreter starts
1.44      crook    7342: compiling. The most common usage for these words is for switching into
                   7343: interpret state and back from within a colon definition; this technique
1.49      anton    7344: can be used to compile a literal (for an example, @pxref{Literals}) or
                   7345: for conditional compilation (for an example, @pxref{Interpreter
                   7346: Directives}).
1.44      crook    7347: 
1.35      anton    7348: 
                   7349: @c This is a bad example: It's non-standard, and it's not necessary.
                   7350: @c However, I can't think of a good example for switching into compile
                   7351: @c state when there is no current word (@code{state}-smart words are not a
                   7352: @c good reason).  So maybe we should use an example for switching into
                   7353: @c interpret @code{state} in a colon def. - anton
1.44      crook    7354: @c nac-> I agree. I started out by putting in the example, then realised
                   7355: @c that it was non-ANS, so wrote more words around it. I hope this
                   7356: @c re-written version is acceptable to you. I do want to keep the example
                   7357: @c as it is helpful for showing what is and what is not portable, particularly
                   7358: @c where it outlaws a style in common use.
                   7359: 
1.35      anton    7360: 
1.44      crook    7361: @code{[} and @code{]} also give you the ability to switch into compile
                   7362: state and back, but we cannot think of any useful Standard application
                   7363: for this ability. Pre-ANS Forth textbooks have examples like this:
1.29      crook    7364: 
                   7365: @example
                   7366: : AA ." this is A" ;
                   7367: : BB ." this is B" ;
                   7368: : CC ." this is C" ;
                   7369: 
1.44      crook    7370: create table ] aa bb cc [
                   7371: 
1.29      crook    7372: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
                   7373:   cells table + @ execute ;
                   7374: @end example
                   7375: 
1.44      crook    7376: This example builds a jump table; @code{0 go} will display ``@code{this
                   7377: is A}''. Using @code{[} and @code{]} in this example is equivalent to
                   7378: defining @code{table} like this:
1.29      crook    7379: 
                   7380: @example
1.44      crook    7381: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
1.29      crook    7382: @end example
                   7383: 
1.44      crook    7384: The problem with this code is that the definition of @code{table} is not
                   7385: portable -- it @i{compile}s execution tokens into code space. Whilst it
                   7386: @i{may} work on systems where code space and data space co-incide, the
1.29      crook    7387: Standard only allows data space to be assigned for a @code{CREATE}d
                   7388: word. In addition, the Standard only allows @code{@@} to access data
                   7389: space, whilst this example is using it to access code space. The only
                   7390: portable, Standard way to build this table is to build it in data space,
                   7391: like this:
                   7392: 
                   7393: @example
                   7394: create table ' aa , ' bb , ' cc ,
                   7395: @end example
                   7396: 
1.26      crook    7397: doc-state
                   7398: doc-[
                   7399: doc-]
1.1       anton    7400: 
1.44      crook    7401: 
1.26      crook    7402: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
                   7403: @subsection Literals
                   7404: @cindex Literals
1.21      crook    7405: 
1.29      crook    7406: Often, you want to use a number within a colon definition. When you do
                   7407: this, the text interpreter automatically compiles the number as a
                   7408: @i{literal}. A literal is a number whose run-time effect is to be pushed
                   7409: onto the stack.  If you had to do some maths to generate the number, you
                   7410: might write it like this:
                   7411: 
                   7412: @example
                   7413: : HOUR-TO-SEC ( n1 -- n2 )
                   7414:   60 *      \ to minutes
                   7415:   60 * ;    \ to seconds
                   7416: @end example
                   7417: 
                   7418: It is very clear what this definition is doing, but it's inefficient
                   7419: since it is performing 2 multiples at run-time. An alternative would be
                   7420: to write:
                   7421: 
                   7422: @example
                   7423: : HOUR-TO-SEC ( n1 -- n2 )
                   7424:   3600 * ;  \ to seconds
                   7425: @end example
                   7426: 
                   7427: Which does the same thing, and has the advantage of using a single
                   7428: multiply. Ideally, we'd like the efficiency of the second with the
                   7429: readability of the first.
                   7430: 
                   7431: @code{Literal} allows us to achieve that. It takes a number from the
                   7432: stack and lays it down in the current definition just as though the
                   7433: number had been typed directly into the definition. Our first attempt
                   7434: might look like this:
                   7435: 
                   7436: @example
                   7437: 60          \ mins per hour
                   7438: 60 *        \ seconds per minute
                   7439: : HOUR-TO-SEC ( n1 -- n2 )
                   7440:   Literal * ;  \ to seconds
                   7441: @end example
                   7442: 
                   7443: But this produces the error message @code{unstructured}. What happened?
                   7444: The stack notation for @code{:} is (@i{ -- colon-sys}) and the size of
                   7445: @i{colon-sys} is implementation-defined. In other words, once we start a
                   7446: colon definition we can't portably access anything that was on the stack
                   7447: before the definition began@footnote{@cite{Two Problems in ANS Forth},
                   7448: by Thomas Worthington; Forth Dimensions 20(2) pages 32--34 describes
                   7449: some situations where you might want to access stack items above
                   7450: colon-sys, and provides a solution to the problem.}. The correct way of
                   7451: solving this problem in this instance is to use @code{[ ]} like this:
                   7452: 
                   7453: @example
                   7454: : HOUR-TO-SEC ( n1 -- n2 )
                   7455:   [ 60          \ minutes per hour
                   7456:     60 * ]      \ seconds per minute
                   7457:   LITERAL * ;   \ to seconds
                   7458: @end example
1.23      crook    7459: 
1.44      crook    7460: 
1.26      crook    7461: doc-literal
                   7462: doc-]L
                   7463: doc-2literal
                   7464: doc-fliteral
1.1       anton    7465: 
1.44      crook    7466: 
1.48      anton    7467: @node Interpreter Directives,  , Literals, The Text Interpreter
1.26      crook    7468: @subsection Interpreter Directives
                   7469: @cindex interpreter directives
1.1       anton    7470: 
1.29      crook    7471: These words are usually used in interpret state; typically to control
                   7472: which parts of a source file are processed by the text
1.26      crook    7473: interpreter. There are only a few ANS Forth Standard words, but Gforth
                   7474: supplements these with a rich set of immediate control structure words
                   7475: to compensate for the fact that the non-immediate versions can only be
1.29      crook    7476: used in compile state (@pxref{Control Structures}). Typical usages:
                   7477: 
                   7478: @example
                   7479: FALSE Constant ASSEMBLER
                   7480: .
                   7481: .
                   7482: ASSEMBLER [IF]
                   7483: : ASSEMBLER-FEATURE
                   7484:   ...
                   7485: ;
                   7486: [ENDIF]
                   7487: .
                   7488: .
                   7489: : SEE
                   7490:   ... \ general-purpose SEE code
                   7491:   [ ASSEMBLER [IF] ]
                   7492:   ... \ assembler-specific SEE code
                   7493:   [ [ENDIF] ]
                   7494: ;
                   7495: @end example
1.1       anton    7496: 
1.44      crook    7497: 
1.26      crook    7498: doc-[IF]
                   7499: doc-[ELSE]
                   7500: doc-[THEN]
                   7501: doc-[ENDIF]
1.1       anton    7502: 
1.26      crook    7503: doc-[IFDEF]
                   7504: doc-[IFUNDEF]
1.1       anton    7505: 
1.26      crook    7506: doc-[?DO]
                   7507: doc-[DO]
                   7508: doc-[FOR]
                   7509: doc-[LOOP]
                   7510: doc-[+LOOP]
                   7511: doc-[NEXT]
1.1       anton    7512: 
1.26      crook    7513: doc-[BEGIN]
                   7514: doc-[UNTIL]
                   7515: doc-[AGAIN]
                   7516: doc-[WHILE]
                   7517: doc-[REPEAT]
1.1       anton    7518: 
1.27      crook    7519: 
1.26      crook    7520: @c -------------------------------------------------------------
1.47      crook    7521: @node Word Lists, Environmental Queries, The Text Interpreter, Words
1.26      crook    7522: @section Word Lists
                   7523: @cindex word lists
1.32      anton    7524: @cindex header space
1.1       anton    7525: 
1.36      anton    7526: A wordlist is a list of named words; you can add new words and look up
                   7527: words by name (and you can remove words in a restricted way with
                   7528: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
                   7529: 
                   7530: @cindex search order stack
                   7531: The text interpreter searches the wordlists present in the search order
                   7532: (a stack of wordlists), from the top to the bottom.  Within each
                   7533: wordlist, the search starts conceptually at the newest word; i.e., if
                   7534: two words in a wordlist have the same name, the newer word is found.
1.1       anton    7535: 
1.26      crook    7536: @cindex compilation word list
1.36      anton    7537: New words are added to the @dfn{compilation wordlist} (aka current
                   7538: wordlist).
1.1       anton    7539: 
1.36      anton    7540: @cindex wid
                   7541: A word list is identified by a cell-sized word list identifier (@i{wid})
                   7542: in much the same way as a file is identified by a file handle. The
                   7543: numerical value of the wid has no (portable) meaning, and might change
                   7544: from session to session.
1.1       anton    7545: 
1.29      crook    7546: The ANS Forth ``Search order'' word set is intended to provide a set of
                   7547: low-level tools that allow various different schemes to be
1.26      crook    7548: implemented. Gforth provides @code{vocabulary}, a traditional Forth
                   7549: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
1.45      crook    7550: Forth.
1.1       anton    7551: 
1.27      crook    7552: @comment TODO: locals section refers to here, saying that every word list (aka
                   7553: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.1       anton    7554: 
1.45      crook    7555: @comment TODO: document markers, reveal, tables, mappedwordlist
                   7556: 
                   7557: @comment the gforthman- prefix is used to pick out the true definition of a
1.27      crook    7558: @comment word from the source files, rather than some alias.
1.44      crook    7559: 
1.26      crook    7560: doc-forth-wordlist
                   7561: doc-definitions
                   7562: doc-get-current
                   7563: doc-set-current
                   7564: doc-get-order
1.45      crook    7565: doc---gforthman-set-order
1.26      crook    7566: doc-wordlist
1.30      anton    7567: doc-table
1.36      anton    7568: doc-push-order
                   7569: doc-previous
1.26      crook    7570: doc-also
1.45      crook    7571: doc---gforthman-forth
1.26      crook    7572: doc-only
1.45      crook    7573: doc---gforthman-order
1.15      anton    7574: 
1.26      crook    7575: doc-find
                   7576: doc-search-wordlist
1.15      anton    7577: 
1.26      crook    7578: doc-words
                   7579: doc-vlist
1.44      crook    7580: @c doc-words-deferred
1.1       anton    7581: 
1.26      crook    7582: doc-mappedwordlist
                   7583: doc-root
                   7584: doc-vocabulary
                   7585: doc-seal
                   7586: doc-vocs
                   7587: doc-current
                   7588: doc-context
1.1       anton    7589: 
1.44      crook    7590: 
1.26      crook    7591: @menu
                   7592: * Why use word lists?::
                   7593: * Word list examples::
                   7594: @end menu
                   7595: 
                   7596: @node Why use word lists?, Word list examples, Word Lists, Word Lists
                   7597: @subsection Why use word lists?
                   7598: @cindex word lists - why use them?
                   7599: 
1.29      crook    7600: Here are some reasons for using multiple word lists:
1.26      crook    7601: 
                   7602: @itemize @bullet
                   7603: @item
1.32      anton    7604: To improve compilation speed by reducing the number of header space
1.26      crook    7605: entries that must be searched. This is achieved by creating a new
                   7606: word list that contains all of the definitions that are used in the
                   7607: definition of a Forth system but which would not usually be used by
                   7608: programs running on that system. That word list would be on the search
                   7609: list when the Forth system was compiled but would be removed from the
                   7610: search list for normal operation. This can be a useful technique for
                   7611: low-performance systems (for example, 8-bit processors in embedded
                   7612: systems) but is unlikely to be necessary in high-performance desktop
                   7613: systems.
                   7614: @item
                   7615: To prevent a set of words from being used outside the context in which
                   7616: they are valid. Two classic examples of this are an integrated editor
                   7617: (all of the edit commands are defined in a separate word list; the
                   7618: search order is set to the editor word list when the editor is invoked;
                   7619: the old search order is restored when the editor is terminated) and an
                   7620: integrated assembler (the op-codes for the machine are defined in a
                   7621: separate word list which is used when a @code{CODE} word is defined).
                   7622: @item
                   7623: To prevent a name-space clash between multiple definitions with the same
                   7624: name. For example, when building a cross-compiler you might have a word
                   7625: @code{IF} that generates conditional code for your target system. By
                   7626: placing this definition in a different word list you can control whether
                   7627: the host system's @code{IF} or the target system's @code{IF} get used in
                   7628: any particular context by controlling the order of the word lists on the
                   7629: search order stack.
                   7630: @end itemize
1.1       anton    7631: 
1.48      anton    7632: @node Word list examples,  , Why use word lists?, Word Lists
1.26      crook    7633: @subsection Word list examples
                   7634: @cindex word lists - examples
1.1       anton    7635: 
1.26      crook    7636: Here is an example of creating and using a new wordlist using ANS
                   7637: Forth Standard words:
1.1       anton    7638: 
                   7639: @example
1.26      crook    7640: wordlist constant my-new-words-wordlist
                   7641: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
1.21      crook    7642: 
1.26      crook    7643: \ add it to the search order
                   7644: also my-new-words
1.21      crook    7645: 
1.26      crook    7646: \ alternatively, add it to the search order and make it
                   7647: \ the compilation word list
                   7648: also my-new-words definitions
                   7649: \ type "order" to see the problem
1.21      crook    7650: @end example
                   7651: 
1.26      crook    7652: The problem with this example is that @code{order} has no way to
                   7653: associate the name @code{my-new-words} with the wid of the word list (in
                   7654: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
                   7655: that has no associated name). There is no Standard way of associating a
                   7656: name with a wid.
                   7657: 
                   7658: In Gforth, this example can be re-coded using @code{vocabulary}, which
                   7659: associates a name with a wid:
1.21      crook    7660: 
1.26      crook    7661: @example
                   7662: vocabulary my-new-words
1.21      crook    7663: 
1.26      crook    7664: \ add it to the search order
1.45      crook    7665: also my-new-words
1.21      crook    7666: 
1.26      crook    7667: \ alternatively, add it to the search order and make it
                   7668: \ the compilation word list
                   7669: my-new-words definitions
                   7670: \ type "order" to see that the problem is solved
                   7671: @end example
1.23      crook    7672: 
1.26      crook    7673: @c -------------------------------------------------------------
                   7674: @node Environmental Queries, Files, Word Lists, Words
                   7675: @section Environmental Queries
                   7676: @cindex environmental queries
1.21      crook    7677: 
1.26      crook    7678: ANS Forth introduced the idea of ``environmental queries'' as a way
                   7679: for a program running on a system to determine certain characteristics of the system.
                   7680: The Standard specifies a number of strings that might be recognised by a system.
1.21      crook    7681: 
1.32      anton    7682: The Standard requires that the header space used for environmental queries
                   7683: be distinct from the header space used for definitions.
1.21      crook    7684: 
1.26      crook    7685: Typically, environmental queries are supported by creating a set of
1.29      crook    7686: definitions in a word list that is @i{only} used during environmental
1.26      crook    7687: queries; that is what Gforth does. There is no Standard way of adding
                   7688: definitions to the set of recognised environmental queries, but any
                   7689: implementation that supports the loading of optional word sets must have
                   7690: some mechanism for doing this (after loading the word set, the
                   7691: associated environmental query string must return @code{true}). In
                   7692: Gforth, the word list used to honour environmental queries can be
                   7693: manipulated just like any other word list.
1.21      crook    7694: 
1.44      crook    7695: 
1.26      crook    7696: doc-environment?
                   7697: doc-environment-wordlist
1.21      crook    7698: 
1.26      crook    7699: doc-gforth
                   7700: doc-os-class
1.21      crook    7701: 
1.44      crook    7702: 
1.26      crook    7703: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
                   7704: returning two items on the stack, querying it using @code{environment?}
                   7705: will return an additional item; the @code{true} flag that shows that the
                   7706: string was recognised.
1.21      crook    7707: 
1.26      crook    7708: @comment TODO Document the standard strings or note where they are documented herein
1.21      crook    7709: 
1.26      crook    7710: Here are some examples of using environmental queries:
1.21      crook    7711: 
1.26      crook    7712: @example
                   7713: s" address-unit-bits" environment? 0=
                   7714: [IF]
                   7715:      cr .( environmental attribute address-units-bits unknown... ) cr
                   7716: [THEN]
1.21      crook    7717: 
1.26      crook    7718: s" block" environment? [IF] DROP include block.fs [THEN]
1.21      crook    7719: 
1.26      crook    7720: s" gforth" environment? [IF] 2DROP include compat/vocabulary.fs [THEN]
1.21      crook    7721: 
1.26      crook    7722: s" gforth" environment? [IF] .( Gforth version ) TYPE
                   7723:                         [ELSE] .( Not Gforth..) [THEN]
                   7724: @end example
1.21      crook    7725: 
                   7726: 
1.26      crook    7727: Here is an example of adding a definition to the environment word list:
1.21      crook    7728: 
1.26      crook    7729: @example
                   7730: get-current environment-wordlist set-current
                   7731: true constant block
                   7732: true constant block-ext
                   7733: set-current
                   7734: @end example
1.21      crook    7735: 
1.26      crook    7736: You can see what definitions are in the environment word list like this:
1.21      crook    7737: 
1.26      crook    7738: @example
                   7739: get-order 1+ environment-wordlist swap set-order words previous
                   7740: @end example
1.21      crook    7741: 
                   7742: 
1.26      crook    7743: @c -------------------------------------------------------------
                   7744: @node Files, Blocks, Environmental Queries, Words
                   7745: @section Files
1.28      crook    7746: @cindex files
                   7747: @cindex I/O - file-handling
1.21      crook    7748: 
1.26      crook    7749: Gforth provides facilities for accessing files that are stored in the
                   7750: host operating system's file-system. Files that are processed by Gforth
                   7751: can be divided into two categories:
1.21      crook    7752: 
1.23      crook    7753: @itemize @bullet
                   7754: @item
1.29      crook    7755: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23      crook    7756: @item
1.29      crook    7757: Files that are processed by some other program (@dfn{general files}).
1.26      crook    7758: @end itemize
                   7759: 
1.45      crook    7760: doc-loadfilename
                   7761: doc-sourcefilename
                   7762: doc-sourceline#
                   7763: 
1.26      crook    7764: @menu
1.48      anton    7765: * Forth source files::          
                   7766: * General files::               
                   7767: * Search Paths::                
1.26      crook    7768: @end menu
                   7769: 
1.21      crook    7770: 
1.26      crook    7771: @c -------------------------------------------------------------
                   7772: @node Forth source files, General files, Files, Files
                   7773: @subsection Forth source files
                   7774: @cindex including files
                   7775: @cindex Forth source files
1.21      crook    7776: 
1.26      crook    7777: The simplest way to interpret the contents of a file is to use one of
                   7778: these two formats:
1.21      crook    7779: 
1.26      crook    7780: @example
                   7781: include mysource.fs
                   7782: s" mysource.fs" included
                   7783: @end example
1.21      crook    7784: 
1.26      crook    7785: Sometimes you want to include a file only if it is not included already
                   7786: (by, say, another source file). In that case, you can use one of these
1.45      crook    7787: three formats:
1.21      crook    7788: 
1.26      crook    7789: @example
                   7790: require mysource.fs
                   7791: needs mysource.fs
                   7792: s" mysource.fs" required
                   7793: @end example
1.21      crook    7794: 
1.26      crook    7795: @cindex stack effect of included files
                   7796: @cindex including files, stack effect
1.45      crook    7797: It is good practice to write your source files such that interpreting them
                   7798: does not change the stack. Source files designed in this way can be used with
1.26      crook    7799: @code{required} and friends without complications. For example:
1.21      crook    7800: 
1.26      crook    7801: @example
                   7802: 1 require foo.fs drop
                   7803: @end example
1.21      crook    7804: 
1.44      crook    7805: 
1.26      crook    7806: doc-include-file
                   7807: doc-included
1.28      crook    7808: doc-included?
1.26      crook    7809: doc-include
                   7810: doc-required
                   7811: doc-require
                   7812: doc-needs
1.28      crook    7813: doc-init-included-files
1.21      crook    7814: 
1.44      crook    7815: 
1.26      crook    7816: A definition in ANS Forth for @code{required} is provided in
                   7817: @file{compat/required.fs}.
1.21      crook    7818: 
1.26      crook    7819: @c -------------------------------------------------------------
                   7820: @node General files, Search Paths, Forth source files, Files
                   7821: @subsection General files
                   7822: @cindex general files
                   7823: @cindex file-handling
1.21      crook    7824: 
1.26      crook    7825: Files are opened/created by name and type. The following types are
                   7826: recognised:
1.1       anton    7827: 
1.44      crook    7828: 
1.26      crook    7829: doc-r/o
                   7830: doc-r/w
                   7831: doc-w/o
                   7832: doc-bin
1.1       anton    7833: 
1.44      crook    7834: 
1.26      crook    7835: When a file is opened/created, it returns a file identifier,
1.29      crook    7836: @i{wfileid} that is used for all other file commands. All file
                   7837: commands also return a status value, @i{wior}, that is 0 for a
1.26      crook    7838: successful operation and an implementation-defined non-zero value in the
                   7839: case of an error.
1.21      crook    7840: 
1.44      crook    7841: 
1.26      crook    7842: doc-open-file
                   7843: doc-create-file
1.21      crook    7844: 
1.26      crook    7845: doc-close-file
                   7846: doc-delete-file
                   7847: doc-rename-file
                   7848: doc-read-file
                   7849: doc-read-line
                   7850: doc-write-file
                   7851: doc-write-line
                   7852: doc-emit-file
                   7853: doc-flush-file
1.21      crook    7854: 
1.26      crook    7855: doc-file-status
                   7856: doc-file-position
                   7857: doc-reposition-file
                   7858: doc-file-size
                   7859: doc-resize-file
1.21      crook    7860: 
1.44      crook    7861: 
1.26      crook    7862: @c ---------------------------------------------------------
1.48      anton    7863: @node Search Paths,  , General files, Files
1.26      crook    7864: @subsection Search Paths
                   7865: @cindex path for @code{included}
                   7866: @cindex file search path
                   7867: @cindex @code{include} search path
                   7868: @cindex search path for files
1.21      crook    7869: 
1.26      crook    7870: If you specify an absolute filename (i.e., a filename starting with
                   7871: @file{/} or @file{~}, or with @file{:} in the second position (as in
                   7872: @samp{C:...})) for @code{included} and friends, that file is included
                   7873: just as you would expect.
1.21      crook    7874: 
1.26      crook    7875: For relative filenames, Gforth uses a search path similar to Forth's
                   7876: search order (@pxref{Word Lists}). It tries to find the given filename
                   7877: in the directories present in the path, and includes the first one it
                   7878: finds. There are separate search paths for Forth source files and
                   7879: general files.
1.21      crook    7880: 
1.26      crook    7881: If the search path contains the directory @file{.} (as it should), this
                   7882: refers to the directory that the present file was @code{included}
                   7883: from. This allows files to include other files relative to their own
                   7884: position (irrespective of the current working directory or the absolute
                   7885: position).  This feature is essential for libraries consisting of
                   7886: several files, where a file may include other files from the library.
                   7887: It corresponds to @code{#include "..."} in C. If the current input
                   7888: source is not a file, @file{.} refers to the directory of the innermost
                   7889: file being included, or, if there is no file being included, to the
                   7890: current working directory.
1.21      crook    7891: 
1.26      crook    7892: Use @file{~+} to refer to the current working directory (as in the
                   7893: @code{bash}).
1.1       anton    7894: 
1.26      crook    7895: If the filename starts with @file{./}, the search path is not searched
                   7896: (just as with absolute filenames), and the @file{.} has the same meaning
                   7897: as described above.
1.1       anton    7898: 
1.48      anton    7899: @menu
                   7900: * Forth Search Paths::          
                   7901: * General Search Paths::        
                   7902: @end menu
                   7903: 
1.26      crook    7904: @c ---------------------------------------------------------
1.48      anton    7905: @node Forth Search Paths, General Search Paths, Search Paths, Search Paths
1.26      crook    7906: @subsubsection Forth Search Paths
1.28      crook    7907: @cindex search path control - Forth
1.5       anton    7908: 
1.26      crook    7909: The search path is initialized when you start Gforth (@pxref{Invoking
                   7910: Gforth}). You can display it and change it using these words:
1.5       anton    7911: 
1.44      crook    7912: 
1.26      crook    7913: doc-.fpath
                   7914: doc-fpath+
                   7915: doc-fpath=
                   7916: doc-open-fpath-file
1.5       anton    7917: 
1.44      crook    7918: 
                   7919: @noindent
1.26      crook    7920: Here is an example of using @code{fpath} and @code{require}:
1.5       anton    7921: 
1.26      crook    7922: @example
                   7923: fpath= /usr/lib/forth/|./
                   7924: require timer.fs
                   7925: @end example
1.5       anton    7926: 
1.26      crook    7927: @c ---------------------------------------------------------
1.48      anton    7928: @node General Search Paths,  , Forth Search Paths, Search Paths
1.26      crook    7929: @subsubsection General Search Paths
                   7930: @cindex search path control - for user applications
1.5       anton    7931: 
1.26      crook    7932: Your application may need to search files in several directories, like
                   7933: @code{included} does. To facilitate this, Gforth allows you to define
                   7934: and use your own search paths, by providing generic equivalents of the
                   7935: Forth search path words:
1.5       anton    7936: 
1.44      crook    7937: 
1.26      crook    7938: doc-.path
                   7939: doc-path+
                   7940: doc-path=
                   7941: doc-open-path-file
1.5       anton    7942: 
1.44      crook    7943: 
1.26      crook    7944: Here's an example of creating a search path:
1.5       anton    7945: 
1.26      crook    7946: @example
                   7947: \ Make a buffer for the path:
                   7948: create mypath   100 chars ,     \ maximum length (is checked)
                   7949:                 0 ,             \ real len
                   7950:                 100 chars allot \ space for path
                   7951: @end example
1.5       anton    7952: 
1.26      crook    7953: @c -------------------------------------------------------------
                   7954: @node Blocks, Other I/O, Files, Words
                   7955: @section Blocks
1.28      crook    7956: @cindex I/O - blocks
                   7957: @cindex blocks
                   7958: 
                   7959: When you run Gforth on a modern desk-top computer, it runs under the
                   7960: control of an operating system which provides certain services.  One of
                   7961: these services is @var{file services}, which allows Forth source code
                   7962: and data to be stored in files and read into Gforth (@pxref{Files}).
                   7963: 
                   7964: Traditionally, Forth has been an important programming language on
                   7965: systems where it has interfaced directly to the underlying hardware with
                   7966: no intervening operating system. Forth provides a mechanism, called
1.29      crook    7967: @dfn{blocks}, for accessing mass storage on such systems.
1.28      crook    7968: 
                   7969: A block is a 1024-byte data area, which can be used to hold data or
                   7970: Forth source code. No structure is imposed on the contents of the
                   7971: block. A block is identified by its number; blocks are numbered
                   7972: contiguously from 1 to an implementation-defined maximum.
                   7973: 
                   7974: A typical system that used blocks but no operating system might use a
                   7975: single floppy-disk drive for mass storage, with the disks formatted to
                   7976: provide 256-byte sectors. Blocks would be implemented by assigning the
                   7977: first four sectors of the disk to block 1, the second four sectors to
                   7978: block 2 and so on, up to the limit of the capacity of the disk. The disk
                   7979: would not contain any file system information, just the set of blocks.
                   7980: 
1.29      crook    7981: @cindex blocks file
1.28      crook    7982: On systems that do provide file services, blocks are typically
1.29      crook    7983: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28      crook    7984: file}.  The size of the blocks file will be an exact multiple of 1024
                   7985: bytes, corresponding to the number of blocks it contains. This is the
                   7986: mechanism that Gforth uses.
                   7987: 
1.29      crook    7988: @cindex @file{blocks.fb}
1.28      crook    7989: Only 1 blocks file can be open at a time. If you use block words without
                   7990: having specified a blocks file, Gforth defaults to the blocks file
                   7991: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
                   7992: locate a blocks file (@pxref{Forth Search Paths}).
                   7993: 
1.29      crook    7994: @cindex block buffers
1.28      crook    7995: When you read and write blocks under program control, Gforth uses a
1.29      crook    7996: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28      crook    7997: not used when you use @code{load} to interpret the contents of a block.
                   7998: 
                   7999: The behaviour of the block buffers is directly analagous to that of a
                   8000: cache. Each block buffer has three states:
                   8001: 
                   8002: @itemize @bullet
                   8003: @item
                   8004: Unassigned
                   8005: @item
                   8006: Assigned-clean
                   8007: @item
                   8008: Assigned-dirty
                   8009: @end itemize
                   8010: 
1.29      crook    8011: Initially, all block buffers are @i{unassigned}. In order to access a
1.28      crook    8012: block, the block (specified by its block number) must be assigned to a
                   8013: block buffer.
                   8014: 
                   8015: The assignment of a block to a block buffer is performed by @code{block}
                   8016: or @code{buffer}. Use @code{block} when you wish to modify the existing
                   8017: contents of a block. Use @code{buffer} when you don't care about the
                   8018: existing contents of the block@footnote{The ANS Forth definition of
1.35      anton    8019: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28      crook    8020: with the particular block is already stored in a block buffer due to an
                   8021: earlier @code{block} command, @code{buffer} will return that block
                   8022: buffer and the existing contents of the block will be
                   8023: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29      crook    8024: block buffer for the block.}.
1.28      crook    8025: 
1.47      crook    8026: Once a block has been assigned to a block buffer using @code{block} or
                   8027: @code{buffer}, that block buffer becomes the @i{current block buffer}
                   8028: and its state changes to @i{assigned-clean}. Data may only be
                   8029: manipulated (read or written) within the current block buffer.
                   8030: 
                   8031: When the contents of the current block buffer has been modified it is
1.48      anton    8032: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
                   8033: either abandon the changes (by doing nothing) or commit the changes,
                   8034: using @code{update}. Using @code{update} does not change the blocks
                   8035: file; it simply changes a block buffer's state to @i{assigned-dirty}.
1.28      crook    8036: 
1.29      crook    8037: The word @code{flush} causes all @i{assigned-dirty} blocks to be
1.28      crook    8038: written back to the blocks file on disk. Leaving Gforth using @code{bye}
                   8039: also causes a @code{flush} to be performed.
                   8040: 
1.29      crook    8041: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28      crook    8042: algorithm to assign a block buffer to a block. That means that any
                   8043: particular block can only be assigned to one specific block buffer,
1.29      crook    8044: called (for the particular operation) the @i{victim buffer}. If the
1.47      crook    8045: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
                   8046: the new block immediately. If it is @i{assigned-dirty} its current
                   8047: contents are written back to the blocks file on disk before it is
1.28      crook    8048: allocated to the new block.
                   8049: 
                   8050: Although no structure is imposed on the contents of a block, it is
                   8051: traditional to display the contents as 16 lines each of 64 characters.  A
                   8052: block provides a single, continuous stream of input (for example, it
                   8053: acts as a single parse area) -- there are no end-of-line characters
                   8054: within a block, and no end-of-file character at the end of a
                   8055: block. There are two consequences of this:
1.26      crook    8056: 
1.28      crook    8057: @itemize @bullet
                   8058: @item
                   8059: The last character of one line wraps straight into the first character
                   8060: of the following line
                   8061: @item
                   8062: The word @code{\} -- comment to end of line -- requires special
                   8063: treatment; in the context of a block it causes all characters until the
                   8064: end of the current 64-character ``line'' to be ignored.
                   8065: @end itemize
                   8066: 
                   8067: In Gforth, when you use @code{block} with a non-existent block number,
1.45      crook    8068: the current blocks file will be extended to the appropriate size and the
1.28      crook    8069: block buffer will be initialised with spaces.
                   8070: 
1.47      crook    8071: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
                   8072: for details) but doesn't encourage the use of blocks; the mechanism is
                   8073: only provided for backward compatibility -- ANS Forth requires blocks to
                   8074: be available when files are.
1.28      crook    8075: 
                   8076: Common techniques that are used when working with blocks include:
                   8077: 
                   8078: @itemize @bullet
                   8079: @item
                   8080: A screen editor that allows you to edit blocks without leaving the Forth
                   8081: environment.
                   8082: @item
                   8083: Shadow screens; where every code block has an associated block
                   8084: containing comments (for example: code in odd block numbers, comments in
                   8085: even block numbers). Typically, the block editor provides a convenient
                   8086: mechanism to toggle between code and comments.
                   8087: @item
                   8088: Load blocks; a single block (typically block 1) contains a number of
                   8089: @code{thru} commands which @code{load} the whole of the application.
                   8090: @end itemize
1.26      crook    8091: 
1.29      crook    8092: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
                   8093: integrated into a Forth programming environment.
1.26      crook    8094: 
                   8095: @comment TODO what about errors on open-blocks?
1.44      crook    8096: 
1.26      crook    8097: doc-open-blocks
                   8098: doc-use
                   8099: doc-get-block-fid
                   8100: doc-block-position
1.28      crook    8101: 
                   8102: doc-scr
                   8103: doc-list
                   8104: 
1.45      crook    8105: doc---gforthman-block
1.28      crook    8106: doc-buffer
                   8107: 
1.26      crook    8108: doc-update
1.28      crook    8109: doc-updated?
1.26      crook    8110: doc-save-buffers
                   8111: doc-empty-buffers
                   8112: doc-empty-buffer
                   8113: doc-flush
1.28      crook    8114: 
1.26      crook    8115: doc-load
                   8116: doc-thru
                   8117: doc-+load
                   8118: doc-+thru
1.45      crook    8119: doc---gforthman--->
1.26      crook    8120: doc-block-included
                   8121: 
1.44      crook    8122: 
1.26      crook    8123: @c -------------------------------------------------------------
                   8124: @node Other I/O, Programming Tools, Blocks, Words
                   8125: @section Other I/O
1.28      crook    8126: @cindex I/O - keyboard and display
1.26      crook    8127: 
                   8128: @menu
                   8129: * Simple numeric output::       Predefined formats
                   8130: * Formatted numeric output::    Formatted (pictured) output
                   8131: * String Formats::              How Forth stores strings in memory
                   8132: * Displaying characters and strings:: Other stuff
                   8133: * Input::                       Input
                   8134: @end menu
                   8135: 
                   8136: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
                   8137: @subsection Simple numeric output
1.28      crook    8138: @cindex numeric output - simple/free-format
1.5       anton    8139: 
1.26      crook    8140: The simplest output functions are those that display numbers from the
                   8141: data or floating-point stacks. Floating-point output is always displayed
                   8142: using base 10. Numbers displayed from the data stack use the value stored
                   8143: in @code{base}.
1.5       anton    8144: 
1.44      crook    8145: 
1.26      crook    8146: doc-.
                   8147: doc-dec.
                   8148: doc-hex.
                   8149: doc-u.
                   8150: doc-.r
                   8151: doc-u.r
                   8152: doc-d.
                   8153: doc-ud.
                   8154: doc-d.r
                   8155: doc-ud.r
                   8156: doc-f.
                   8157: doc-fe.
                   8158: doc-fs.
1.5       anton    8159: 
1.44      crook    8160: 
1.26      crook    8161: Examples of printing the number 1234.5678E23 in the different floating-point output
                   8162: formats are shown below:
1.5       anton    8163: 
                   8164: @example
1.26      crook    8165: f. 123456779999999000000000000.
                   8166: fe. 123.456779999999E24
                   8167: fs. 1.23456779999999E26
1.5       anton    8168: @end example
                   8169: 
                   8170: 
1.26      crook    8171: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
                   8172: @subsection Formatted numeric output
1.28      crook    8173: @cindex formatted numeric output
1.26      crook    8174: @cindex pictured numeric output
1.28      crook    8175: @cindex numeric output - formatted
1.26      crook    8176: 
1.29      crook    8177: Forth traditionally uses a technique called @dfn{pictured numeric
1.26      crook    8178: output} for formatted printing of integers.  In this technique, digits
                   8179: are extracted from the number (using the current output radix defined by
                   8180: @code{base}), converted to ASCII codes and appended to a string that is
                   8181: built in a scratch-pad area of memory (@pxref{core-idef,
                   8182: Implementation-defined options, Implementation-defined
                   8183: options}). Arbitrary characters can be appended to the string during the
                   8184: extraction process. The completed string is specified by an address
                   8185: and length and can be manipulated (@code{TYPE}ed, copied, modified)
                   8186: under program control.
1.5       anton    8187: 
1.26      crook    8188: All of the words described in the previous section for simple numeric
                   8189: output are implemented in Gforth using pictured numeric output.
1.5       anton    8190: 
1.47      crook    8191: Three important things to remember about pictured numeric output:
1.5       anton    8192: 
1.26      crook    8193: @itemize @bullet
                   8194: @item
1.28      crook    8195: It always operates on double-precision numbers; to display a
1.49      anton    8196: single-precision number, convert it first (for ways of doing this
                   8197: @pxref{Double precision}).
1.26      crook    8198: @item
1.28      crook    8199: It always treats the double-precision number as though it were
                   8200: unsigned. The examples below show ways of printing signed numbers.
1.26      crook    8201: @item
                   8202: The string is built up from right to left; least significant digit first.
                   8203: @end itemize
1.5       anton    8204: 
1.44      crook    8205: 
1.26      crook    8206: doc-<#
1.47      crook    8207: doc-<<#
1.26      crook    8208: doc-#
                   8209: doc-#s
                   8210: doc-hold
                   8211: doc-sign
                   8212: doc-#>
1.47      crook    8213: doc-#>>
1.5       anton    8214: 
1.26      crook    8215: doc-represent
1.5       anton    8216: 
1.44      crook    8217: 
                   8218: @noindent
1.26      crook    8219: Here are some examples of using pictured numeric output:
1.5       anton    8220: 
                   8221: @example
1.26      crook    8222: : my-u. ( u -- )
                   8223:   \ Simplest use of pns.. behaves like Standard u. 
                   8224:   0              \ convert to unsigned double
                   8225:   <#             \ start conversion
                   8226:   #s             \ convert all digits
                   8227:   #>             \ complete conversion
                   8228:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    8229: 
1.26      crook    8230: : cents-only ( u -- )
                   8231:   0              \ convert to unsigned double
                   8232:   <#             \ start conversion
                   8233:   # #            \ convert two least-significant digits
                   8234:   #>             \ complete conversion, discard other digits
                   8235:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    8236: 
1.26      crook    8237: : dollars-and-cents ( u -- )
                   8238:   0              \ convert to unsigned double
                   8239:   <#             \ start conversion
                   8240:   # #            \ convert two least-significant digits
                   8241:   [char] . hold  \ insert decimal point
                   8242:   #s             \ convert remaining digits
                   8243:   [char] $ hold  \ append currency symbol
                   8244:   #>             \ complete conversion
                   8245:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    8246: 
1.26      crook    8247: : my-. ( n -- )
                   8248:   \ handling negatives.. behaves like Standard .
                   8249:   s>d            \ convert to signed double
                   8250:   swap over dabs \ leave sign byte followed by unsigned double
                   8251:   <#             \ start conversion
                   8252:   #s             \ convert all digits
                   8253:   rot sign       \ get at sign byte, append "-" if needed
                   8254:   #>             \ complete conversion
                   8255:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    8256: 
1.26      crook    8257: : account. ( n -- )
                   8258:   \ accountants don't like minus signs, they use braces
                   8259:   \ for negative numbers
                   8260:   s>d            \ convert to signed double
                   8261:   swap over dabs \ leave sign byte followed by unsigned double
                   8262:   <#             \ start conversion
                   8263:   2 pick         \ get copy of sign byte
                   8264:   0< IF [char] ) hold THEN \ right-most character of output
                   8265:   #s             \ convert all digits
                   8266:   rot            \ get at sign byte
                   8267:   0< IF [char] ( hold THEN
                   8268:   #>             \ complete conversion
                   8269:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    8270: @end example
                   8271: 
1.26      crook    8272: Here are some examples of using these words:
1.5       anton    8273: 
                   8274: @example
1.26      crook    8275: 1 my-u. 1
                   8276: hex -1 my-u. decimal FFFFFFFF
                   8277: 1 cents-only 01
                   8278: 1234 cents-only 34
                   8279: 2 dollars-and-cents $0.02
                   8280: 1234 dollars-and-cents $12.34
                   8281: 123 my-. 123
                   8282: -123 my. -123
                   8283: 123 account. 123
                   8284: -456 account. (456)
1.5       anton    8285: @end example
                   8286: 
                   8287: 
1.26      crook    8288: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
                   8289: @subsection String Formats
1.27      crook    8290: @cindex strings - see character strings
                   8291: @cindex character strings - formats
1.28      crook    8292: @cindex I/O - see character strings
1.26      crook    8293: 
1.27      crook    8294: Forth commonly uses two different methods for representing character
                   8295: strings:
1.26      crook    8296: 
                   8297: @itemize @bullet
                   8298: @item
                   8299: @cindex address of counted string
1.45      crook    8300: @cindex counted string
1.29      crook    8301: As a @dfn{counted string}, represented by a @i{c-addr}. The char
                   8302: addressed by @i{c-addr} contains a character-count, @i{n}, of the
                   8303: string and the string occupies the subsequent @i{n} char addresses in
1.26      crook    8304: memory.
                   8305: @item
1.29      crook    8306: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
                   8307: of the string in characters, and @i{c-addr} is the address of the
1.26      crook    8308: first byte of the string.
                   8309: @end itemize
                   8310: 
                   8311: ANS Forth encourages the use of the second format when representing
                   8312: strings on the stack, whilst conceeding that the counted string format
                   8313: remains useful as a way of storing strings in memory.
                   8314: 
1.44      crook    8315: 
1.26      crook    8316: doc-count
                   8317: 
1.44      crook    8318: 
1.49      anton    8319: For words that move, copy and search for strings see @ref{Memory
                   8320: Blocks}. For words that display characters and strings see
                   8321: @ref{Displaying characters and strings}.
1.26      crook    8322: 
                   8323: @node Displaying characters and strings, Input, String Formats, Other I/O
                   8324: @subsection Displaying characters and strings
1.27      crook    8325: @cindex characters - compiling and displaying
                   8326: @cindex character strings - compiling and displaying
1.26      crook    8327: 
                   8328: This section starts with a glossary of Forth words and ends with a set
                   8329: of examples.
                   8330: 
1.44      crook    8331: 
1.26      crook    8332: doc-bl
                   8333: doc-space
                   8334: doc-spaces
                   8335: doc-emit
                   8336: doc-toupper
                   8337: doc-."
                   8338: doc-.(
                   8339: doc-type
1.44      crook    8340: doc-typewhite
1.26      crook    8341: doc-cr
1.27      crook    8342: @cindex cursor control
1.26      crook    8343: doc-at-xy
                   8344: doc-page
                   8345: doc-s"
                   8346: doc-c"
                   8347: doc-char
                   8348: doc-[char]
                   8349: doc-sliteral
                   8350: 
1.44      crook    8351: 
                   8352: @noindent
1.26      crook    8353: As an example, consider the following text, stored in a file @file{test.fs}:
1.5       anton    8354: 
                   8355: @example
1.26      crook    8356: .( text-1)
                   8357: : my-word
                   8358:   ." text-2" cr
                   8359:   .( text-3)
                   8360: ;
                   8361: 
                   8362: ." text-4"
                   8363: 
                   8364: : my-char
                   8365:   [char] ALPHABET emit
                   8366:   char emit
                   8367: ;
1.5       anton    8368: @end example
                   8369: 
1.26      crook    8370: When you load this code into Gforth, the following output is generated:
1.5       anton    8371: 
1.26      crook    8372: @example
1.30      anton    8373: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26      crook    8374: @end example
1.5       anton    8375: 
1.26      crook    8376: @itemize @bullet
                   8377: @item
                   8378: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
                   8379: is an immediate word; it behaves in the same way whether it is used inside
                   8380: or outside a colon definition.
                   8381: @item
                   8382: Message @code{text-4} is displayed because of Gforth's added interpretation
                   8383: semantics for @code{."}.
                   8384: @item
1.29      crook    8385: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26      crook    8386: performs the compilation semantics for @code{."} within the definition of
                   8387: @code{my-word}.
                   8388: @end itemize
1.5       anton    8389: 
1.26      crook    8390: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5       anton    8391: 
1.26      crook    8392: @example
1.30      anton    8393: @kbd{my-word @key{RET}} text-2
1.26      crook    8394:  ok
1.30      anton    8395: @kbd{my-char fred @key{RET}} Af ok
                   8396: @kbd{my-char jim @key{RET}} Aj ok
1.26      crook    8397: @end example
1.5       anton    8398: 
                   8399: @itemize @bullet
                   8400: @item
1.26      crook    8401: Message @code{text-2} is displayed because of the run-time behaviour of
                   8402: @code{."}.
                   8403: @item
                   8404: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
                   8405: on the stack at run-time. @code{emit} always displays the character
                   8406: when @code{my-char} is executed.
                   8407: @item
                   8408: @code{char} parses a string at run-time and the second @code{emit} displays
                   8409: the first character of the string.
1.5       anton    8410: @item
1.26      crook    8411: If you type @code{see my-char} you can see that @code{[char]} discarded
                   8412: the text ``LPHABET'' and only compiled the display code for ``A'' into the
                   8413: definition of @code{my-char}.
1.5       anton    8414: @end itemize
                   8415: 
                   8416: 
                   8417: 
1.48      anton    8418: @node Input,  , Displaying characters and strings, Other I/O
1.26      crook    8419: @subsection Input
                   8420: @cindex input
1.28      crook    8421: @cindex I/O - see input
                   8422: @cindex parsing a string
1.5       anton    8423: 
1.49      anton    8424: For ways of storing character strings in memory see @ref{String Formats}.
1.5       anton    8425: 
1.27      crook    8426: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29      crook    8427: @comment then index them
1.27      crook    8428: 
1.44      crook    8429: 
1.27      crook    8430: doc-key
                   8431: doc-key?
1.45      crook    8432: doc-ekey
                   8433: doc-ekey?
                   8434: doc-ekey>char
1.26      crook    8435: doc->number
                   8436: doc->float
                   8437: doc-accept
1.27      crook    8438: doc-pad
                   8439: doc-parse
                   8440: doc-word
                   8441: doc-sword
1.44      crook    8442: doc-(name)
1.27      crook    8443: doc-refill
                   8444: @comment obsolescent words..
                   8445: doc-convert
1.26      crook    8446: doc-query
                   8447: doc-expect
1.27      crook    8448: doc-span
1.5       anton    8449: 
                   8450: 
1.44      crook    8451: 
1.5       anton    8452: @c -------------------------------------------------------------
1.26      crook    8453: @node Programming Tools, Assembler and Code Words, Other I/O, Words
                   8454: @section Programming Tools
                   8455: @cindex programming tools
1.12      anton    8456: 
                   8457: @menu
1.26      crook    8458: * Debugging::                   Simple and quick.
                   8459: * Assertions::                  Making your programs self-checking.
1.46      pazsan   8460: * Singlestep Debugger::         Executing your program word by word.
1.5       anton    8461: @end menu
                   8462: 
1.26      crook    8463: @node Debugging, Assertions, Programming Tools, Programming Tools
                   8464: @subsection Debugging
                   8465: @cindex debugging
1.5       anton    8466: 
1.26      crook    8467: Languages with a slow edit/compile/link/test development loop tend to
                   8468: require sophisticated tracing/stepping debuggers to facilate
                   8469: productive debugging.
1.5       anton    8470: 
1.26      crook    8471: A much better (faster) way in fast-compiling languages is to add
                   8472: printing code at well-selected places, let the program run, look at
                   8473: the output, see where things went wrong, add more printing code, etc.,
                   8474: until the bug is found.
1.5       anton    8475: 
1.26      crook    8476: The simple debugging aids provided in @file{debugs.fs}
                   8477: are meant to support this style of debugging. In addition, there are
                   8478: words for non-destructively inspecting the stack and memory:
1.5       anton    8479: 
1.44      crook    8480: 
1.26      crook    8481: doc-.s
                   8482: doc-f.s
1.5       anton    8483: 
1.44      crook    8484: 
1.29      crook    8485: There is a word @code{.r} but it does @i{not} display the return
1.26      crook    8486: stack! It is used for formatted numeric output.
1.5       anton    8487: 
1.44      crook    8488: 
1.26      crook    8489: doc-depth
                   8490: doc-fdepth
                   8491: doc-clearstack
                   8492: doc-?
                   8493: doc-dump
1.5       anton    8494: 
1.44      crook    8495: 
1.26      crook    8496: The word @code{~~} prints debugging information (by default the source
                   8497: location and the stack contents). It is easy to insert. If you use Emacs
                   8498: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
                   8499: query-replace them with nothing). The deferred words
                   8500: @code{printdebugdata} and @code{printdebugline} control the output of
                   8501: @code{~~}. The default source location output format works well with
                   8502: Emacs' compilation mode, so you can step through the program at the
                   8503: source level using @kbd{C-x `} (the advantage over a stepping debugger
                   8504: is that you can step in any direction and you know where the crash has
                   8505: happened or where the strange data has occurred).
1.5       anton    8506: 
1.26      crook    8507: The default actions of @code{~~} clobber the contents of the pictured
                   8508: numeric output string, so you should not use @code{~~}, e.g., between
                   8509: @code{<#} and @code{#>}.
1.5       anton    8510: 
1.44      crook    8511: 
1.26      crook    8512: doc-~~
                   8513: doc-printdebugdata
                   8514: doc-printdebugline
1.5       anton    8515: 
1.26      crook    8516: doc-see
                   8517: doc-marker
1.5       anton    8518: 
1.44      crook    8519: 
1.26      crook    8520: Here's an example of using @code{marker} at the start of a source file
                   8521: that you are debugging; it ensures that you only ever have one copy of
                   8522: the file's definitions compiled at any time:
1.5       anton    8523: 
1.26      crook    8524: @example
                   8525: [IFDEF] my-code
                   8526:     my-code
                   8527: [ENDIF]
1.5       anton    8528: 
1.26      crook    8529: marker my-code
1.28      crook    8530: init-included-files
1.5       anton    8531: 
1.26      crook    8532: \ .. definitions start here
                   8533: \ .
                   8534: \ .
                   8535: \ end
                   8536: @end example
1.5       anton    8537: 
                   8538: 
                   8539: 
1.26      crook    8540: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
                   8541: @subsection Assertions
                   8542: @cindex assertions
1.5       anton    8543: 
1.26      crook    8544: It is a good idea to make your programs self-checking, especially if you
                   8545: make an assumption that may become invalid during maintenance (for
                   8546: example, that a certain field of a data structure is never zero). Gforth
1.29      crook    8547: supports @dfn{assertions} for this purpose. They are used like this:
1.23      crook    8548: 
1.26      crook    8549: @example
1.29      crook    8550: assert( @i{flag} )
1.26      crook    8551: @end example
1.23      crook    8552: 
1.26      crook    8553: The code between @code{assert(} and @code{)} should compute a flag, that
                   8554: should be true if everything is alright and false otherwise. It should
                   8555: not change anything else on the stack. The overall stack effect of the
                   8556: assertion is @code{( -- )}. E.g.
1.23      crook    8557: 
1.26      crook    8558: @example
                   8559: assert( 1 1 + 2 = ) \ what we learn in school
                   8560: assert( dup 0<> ) \ assert that the top of stack is not zero
                   8561: assert( false ) \ this code should not be reached
                   8562: @end example
1.23      crook    8563: 
1.26      crook    8564: The need for assertions is different at different times. During
                   8565: debugging, we want more checking, in production we sometimes care more
                   8566: for speed. Therefore, assertions can be turned off, i.e., the assertion
                   8567: becomes a comment. Depending on the importance of an assertion and the
                   8568: time it takes to check it, you may want to turn off some assertions and
                   8569: keep others turned on. Gforth provides several levels of assertions for
                   8570: this purpose:
1.23      crook    8571: 
1.44      crook    8572: 
1.26      crook    8573: doc-assert0(
                   8574: doc-assert1(
                   8575: doc-assert2(
                   8576: doc-assert3(
                   8577: doc-assert(
                   8578: doc-)
1.23      crook    8579: 
1.44      crook    8580: 
1.26      crook    8581: The variable @code{assert-level} specifies the highest assertions that
                   8582: are turned on. I.e., at the default @code{assert-level} of one,
                   8583: @code{assert0(} and @code{assert1(} assertions perform checking, while
                   8584: @code{assert2(} and @code{assert3(} assertions are treated as comments.
                   8585: 
                   8586: The value of @code{assert-level} is evaluated at compile-time, not at
                   8587: run-time. Therefore you cannot turn assertions on or off at run-time;
                   8588: you have to set the @code{assert-level} appropriately before compiling a
                   8589: piece of code. You can compile different pieces of code at different
                   8590: @code{assert-level}s (e.g., a trusted library at level 1 and
                   8591: newly-written code at level 3).
1.23      crook    8592: 
1.44      crook    8593: 
1.26      crook    8594: doc-assert-level
1.23      crook    8595: 
1.44      crook    8596: 
1.26      crook    8597: If an assertion fails, a message compatible with Emacs' compilation mode
                   8598: is produced and the execution is aborted (currently with @code{ABORT"}.
                   8599: If there is interest, we will introduce a special throw code. But if you
                   8600: intend to @code{catch} a specific condition, using @code{throw} is
                   8601: probably more appropriate than an assertion).
1.23      crook    8602: 
1.26      crook    8603: Definitions in ANS Forth for these assertion words are provided
                   8604: in @file{compat/assert.fs}.
1.23      crook    8605: 
                   8606: 
1.48      anton    8607: @node Singlestep Debugger,  , Assertions, Programming Tools
1.26      crook    8608: @subsection Singlestep Debugger
                   8609: @cindex singlestep Debugger
                   8610: @cindex debugging Singlestep
1.23      crook    8611: 
1.26      crook    8612: When you create a new word there's often the need to check whether it
                   8613: behaves correctly or not. You can do this by typing @code{dbg
                   8614: badword}. A debug session might look like this:
1.23      crook    8615: 
1.26      crook    8616: @example
                   8617: : badword 0 DO i . LOOP ;  ok
                   8618: 2 dbg badword 
                   8619: : badword  
                   8620: Scanning code...
1.23      crook    8621: 
1.26      crook    8622: Nesting debugger ready!
1.23      crook    8623: 
1.26      crook    8624: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
                   8625: 400D4740  8049F68 DO             -> [ 0 ] 
                   8626: 400D4744  804A0C8 i              -> [ 1 ] 00000 
                   8627: 400D4748 400C5E60 .              -> 0 [ 0 ] 
                   8628: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   8629: 400D4744  804A0C8 i              -> [ 1 ] 00001 
                   8630: 400D4748 400C5E60 .              -> 1 [ 0 ] 
                   8631: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   8632: 400D4758  804B384 ;              ->  ok
                   8633: @end example
1.23      crook    8634: 
1.26      crook    8635: Each line displayed is one step. You always have to hit return to
                   8636: execute the next word that is displayed. If you don't want to execute
                   8637: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
                   8638: an overview what keys are available:
1.23      crook    8639: 
1.26      crook    8640: @table @i
1.23      crook    8641: 
1.30      anton    8642: @item @key{RET}
1.26      crook    8643: Next; Execute the next word.
1.23      crook    8644: 
1.26      crook    8645: @item n
                   8646: Nest; Single step through next word.
1.5       anton    8647: 
1.26      crook    8648: @item u
                   8649: Unnest; Stop debugging and execute rest of word. If we got to this word
                   8650: with nest, continue debugging with the calling word.
1.5       anton    8651: 
1.26      crook    8652: @item d
                   8653: Done; Stop debugging and execute rest.
1.5       anton    8654: 
1.26      crook    8655: @item s
                   8656: Stop; Abort immediately.
1.5       anton    8657: 
1.26      crook    8658: @end table
1.5       anton    8659: 
1.26      crook    8660: Debugging large application with this mechanism is very difficult, because
                   8661: you have to nest very deeply into the program before the interesting part
                   8662: begins. This takes a lot of time. 
1.5       anton    8663: 
1.26      crook    8664: To do it more directly put a @code{BREAK:} command into your source code.
                   8665: When program execution reaches @code{BREAK:} the single step debugger is
                   8666: invoked and you have all the features described above.
1.23      crook    8667: 
1.26      crook    8668: If you have more than one part to debug it is useful to know where the
                   8669: program has stopped at the moment. You can do this by the 
                   8670: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
                   8671: string is typed out when the ``breakpoint'' is reached.
                   8672: 
1.44      crook    8673: 
1.26      crook    8674: doc-dbg
1.45      crook    8675: doc-break:
                   8676: doc-break"
1.26      crook    8677: 
                   8678: 
1.44      crook    8679: 
1.26      crook    8680: @c -------------------------------------------------------------
                   8681: @node Assembler and Code Words, Threading Words, Programming Tools, Words
                   8682: @section Assembler and Code Words
                   8683: @cindex assembler
                   8684: @cindex code words
1.5       anton    8685: 
1.52      anton    8686: @menu
1.53      anton    8687: * Code and ;code::              
                   8688: * Common Assembler::            Assembler Syntax
1.52      anton    8689: * Common Disassembler::         
                   8690: * 386 Assembler::               Deviations and special cases
                   8691: * Alpha Assembler::             Deviations and special cases
                   8692: * MIPS assembler::              Deviations and special cases
1.53      anton    8693: * Other assemblers::            How to write them
1.52      anton    8694: @end menu
                   8695: 
1.53      anton    8696: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
                   8697: @subsection @code{Code} and @code{;code}
1.52      anton    8698: 
1.26      crook    8699: Gforth provides some words for defining primitives (words written in
1.29      crook    8700: machine code), and for defining the machine-code equivalent of
1.26      crook    8701: @code{DOES>}-based defining words. However, the machine-independent
                   8702: nature of Gforth poses a few problems: First of all, Gforth runs on
                   8703: several architectures, so it can provide no standard assembler. What's
                   8704: worse is that the register allocation not only depends on the processor,
                   8705: but also on the @code{gcc} version and options used.
1.5       anton    8706: 
1.29      crook    8707: The words that Gforth offers encapsulate some system dependences (e.g.,
                   8708: the header structure), so a system-independent assembler may be used in
1.26      crook    8709: Gforth. If you do not have an assembler, you can compile machine code
1.29      crook    8710: directly with @code{,} and @code{c,}@footnote{This isn't portable,
                   8711: because these words emit stuff in @i{data} space; it works because
                   8712: Gforth has unified code/data spaces. Assembler isn't likely to be
                   8713: portable anyway.}.
1.5       anton    8714: 
1.44      crook    8715: 
1.26      crook    8716: doc-assembler
1.45      crook    8717: doc-init-asm
1.26      crook    8718: doc-code
                   8719: doc-end-code
                   8720: doc-;code
                   8721: doc-flush-icache
1.5       anton    8722: 
1.44      crook    8723: 
1.26      crook    8724: If @code{flush-icache} does not work correctly, @code{code} words
                   8725: etc. will not work (reliably), either.
1.5       anton    8726: 
1.29      crook    8727: The typical usage of these @code{code} words can be shown most easily by
                   8728: analogy to the equivalent high-level defining words:
                   8729: 
                   8730: @example
1.53      anton    8731: : foo                              code foo
                   8732:    <high-level Forth words>              <assembler>
                   8733: ;                                  end-code
                   8734:                                 
                   8735: : bar                              : bar
                   8736:    <high-level Forth words>           <high-level Forth words>
                   8737:    CREATE                             CREATE
                   8738:       <high-level Forth words>           <high-level Forth words>
                   8739:    DOES>                              ;code
                   8740:       <high-level Forth words>           <assembler>
                   8741: ;                                  end-code
1.29      crook    8742: @end example
                   8743: 
1.26      crook    8744: @code{flush-icache} is always present. The other words are rarely used
                   8745: and reside in @code{code.fs}, which is usually not loaded. You can load
                   8746: it with @code{require code.fs}.
1.5       anton    8747: 
1.26      crook    8748: @cindex registers of the inner interpreter
                   8749: In the assembly code you will want to refer to the inner interpreter's
                   8750: registers (e.g., the data stack pointer) and you may want to use other
                   8751: registers for temporary storage. Unfortunately, the register allocation
                   8752: is installation-dependent.
1.5       anton    8753: 
1.26      crook    8754: The easiest solution is to use explicit register declarations
                   8755: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
                   8756: GNU C Manual}) for all of the inner interpreter's registers: You have to
                   8757: compile Gforth with @code{-DFORCE_REG} (configure option
                   8758: @code{--enable-force-reg}) and the appropriate declarations must be
                   8759: present in the @code{machine.h} file (see @code{mips.h} for an example;
                   8760: you can find a full list of all declarable register symbols with
                   8761: @code{grep register engine.c}). If you give explicit registers to all
                   8762: variables that are declared at the beginning of @code{engine()}, you
                   8763: should be able to use the other caller-saved registers for temporary
                   8764: storage. Alternatively, you can use the @code{gcc} option
                   8765: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
                   8766: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
                   8767: (however, this restriction on register allocation may slow Gforth
                   8768: significantly).
1.5       anton    8769: 
1.26      crook    8770: If this solution is not viable (e.g., because @code{gcc} does not allow
                   8771: you to explicitly declare all the registers you need), you have to find
                   8772: out by looking at the code where the inner interpreter's registers
                   8773: reside and which registers can be used for temporary storage. You can
                   8774: get an assembly listing of the engine's code with @code{make engine.s}.
1.5       anton    8775: 
1.26      crook    8776: In any case, it is good practice to abstract your assembly code from the
                   8777: actual register allocation. E.g., if the data stack pointer resides in
                   8778: register @code{$17}, create an alias for this register called @code{sp},
                   8779: and use that in your assembly code.
1.5       anton    8780: 
1.26      crook    8781: @cindex code words, portable
                   8782: Another option for implementing normal and defining words efficiently
                   8783: is to add the desired functionality to the source of Gforth. For normal
                   8784: words you just have to edit @file{primitives} (@pxref{Automatic
                   8785: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
                   8786: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
                   8787: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.5       anton    8788: 
1.53      anton    8789: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
                   8790: @subsection Common Assembler
                   8791: 
                   8792: The assemblers in Gforth generally use a postfix syntax, i.e., the
                   8793: instruction name follows the operands.
                   8794: 
                   8795: The operands are passed in the usual order (the same that is used in the
                   8796: manual of the architecture).  Since they all are Forth words, they have
                   8797: to be separated by spaces; you can also use Forth words to compute the
                   8798: operands.
                   8799: 
                   8800: The instruction names usually end with a @code{,}.  This makes it easier
                   8801: to visually separate instructions if you put several of them on one
                   8802: line; it also avoids shadowing other Forth words (e.g., @code{and}).
                   8803: 
1.55      anton    8804: Registers are usually specified by number; e.g., (decimal) @code{11}
                   8805: specifies registers R11 and F11 on the Alpha architecture (which one,
                   8806: depends on the instruction).  The usual names are also available, e.g.,
                   8807: @code{s2} for R11 on Alpha.
                   8808: 
1.53      anton    8809: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
                   8810: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
                   8811: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
                   8812: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
                   8813: conditions are specified in a way specific to each assembler.
                   8814: 
1.57      anton    8815: Note that the register assignments of the Gforth engine can change
                   8816: between Gforth versions, or even between different compilations of the
                   8817: same Gforth version (e.g., if you use a different GCC version).  So if
                   8818: you want to refer to Gforth's registers (e.g., the stack pointer or
                   8819: TOS), I recommend defining your own words for refering to these
                   8820: registers, and using them later on; then you can easily adapt to a
                   8821: changed register assignment.  The stability of the register assignment
                   8822: is usually better if you build Gforth with @code{--enable-force-reg}.
                   8823: 
                   8824: In particular, the resturn stack pointer and the instruction pointer are
                   8825: in memory in @code{gforth}, and usually in registers in
                   8826: @code{gforth-fast}.  The most common use of these registers is to
                   8827: dispatch to the next word (the @code{next} routine).  A portable way to
                   8828: do this is to jump to @code{' noop >code-address} (of course, this is
                   8829: less efficient than integrating the @code{next} code and scheduling it
                   8830: well).
                   8831: 
1.52      anton    8832: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
                   8833: @subsection Common Disassembler
                   8834: 
                   8835: You can disassemble a @code{code} word with @code{see}
                   8836: (@pxref{Debugging}).  You can disassemble a section of memory with
                   8837: 
                   8838: doc-disasm
                   8839: 
                   8840: The disassembler generally produces output that can be fed into the
                   8841: assembler (i.e., same syntax, etc.).  It also includes additional
1.53      anton    8842: information in comments.  In particular, the address of the instruction
                   8843: is given in a comment before the instruction.
                   8844: 
                   8845: @code{See} may display more or less than the actual code of the word,
                   8846: because the recognition of the end of the code is unreliable.  You can
                   8847: use @code{disasm} if it did not display enough.  It may display more, if
                   8848: the code word is not immediately followed by a named word.  If you have
                   8849: something else there, you can follow the word with @code{align last @ ,}
                   8850: to ensure that the end is recognized.
1.52      anton    8851: 
                   8852: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
                   8853: @subsection 386 Assembler
                   8854: 
                   8855: The 386 assembler and disassembler included in Gforth was written by
                   8856: Andrew McKewan; it is in the public domain.
1.57      anton    8857: 
                   8858: The disassembler displays code in prefix Intel syntax.
                   8859: 
                   8860: The assembler uses an Intel-inspired postfix syntax with reversed
                   8861: parameters.  As usual, a @code{,} is appended to the instruction names
                   8862: (including @code{rep,} etc.).
                   8863: 
                   8864: The assembler is somewhat meager, missing a number of instructions
                   8865: (including FP) and absolute memory addressing modes.
                   8866: 
                   8867: The registers have their usual names @code{eax} etc.  Immediate values
                   8868: are indicated by postfixing them with @code{#}, e.g., @code{3 #}.  Here
                   8869: are some examples of addressing modes:
                   8870: 
                   8871: @example
                   8872: 3 #
                   8873: eax
                   8874: 100 [edi]
                   8875: 4 [ebx] [ecx]
                   8876: 0 [edi] [eax] *4 \ base register required!
                   8877: @end example
                   8878: 
                   8879: Some example of instructions are:
                   8880: 
                   8881: @example
                   8882: EAX EBX MOV,             \ move ebx,eax
                   8883: 3 # EAX MOV,             \ mov eax,3
                   8884: 100 [EDI] EAX MOV,       \ mov eax,100[edi]
                   8885: 4 [EBX] [ECX] EAX MOV,   \ mov eax,4[ebx][ecx]
                   8886: 16: EAX EBX MOV,         \ mov bx,ax
                   8887: @end example
                   8888: 
                   8889: You cannot use the prefix @code{16:} with immediate operands.  The
                   8890: following forms are supported for binary instructions:
                   8891: 
                   8892: @example
                   8893: <reg> <reg> <inst>
                   8894: <n> # <reg> <inst>
                   8895: <mem> <reg> <inst>
                   8896: <reg> <mem> <inst>
                   8897: @end example
                   8898: 
                   8899: Immediate to memory is not supported.  The shift/rotate syntax is:
                   8900: 
                   8901: @example
                   8902: <reg/mem> shl,
                   8903: <reg/mem> 4 shl,
                   8904: <reg/mem> cl shl,
                   8905: @end example
                   8906: 
                   8907: Precede string instructions (@code{movs,} etc.) with @code{byte} to get
                   8908: the byte version.
                   8909: 
                   8910: The control structure words @code{if,} @code{until,} etc. must be
                   8911: preceded by one of these conditions: @code{0= 0< u< u> < > ov ecx0<>}.
                   8912: You can invert the condition with @code{not} (Note that most of these
                   8913: words shadow some Forth words when @code{assembler} is before
                   8914: @code{forth} in the search path, e.g., in code words).  Currently the
                   8915: control structure words use one stack item, so you have to use
                   8916: @code{roll} instead of @code{cs-roll} to shuffle them (you can also use
                   8917: @code{swap} etc.).
1.52      anton    8918: 
                   8919: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
                   8920: @subsection Alpha Assembler
                   8921: 
1.55      anton    8922: The Alpha assembler and disassembler were originally written by Bernd
                   8923: Thallner.
                   8924: 
                   8925: The register names @code{a0}--@code{a5} are not available to avoid
                   8926: shadowing hex numbers.
                   8927: 
                   8928: Immediate forms of arithmetic instructions are distinguished by a
                   8929: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
                   8930: does not count as arithmetic instruction).
                   8931: 
                   8932: You have to specify all operands to an instruction, even those that
                   8933: other assemblers consider optional, e.g., the destination register for
                   8934: @code{br,}, or the destination register and hint for @code{jmp,}.
                   8935: 
                   8936: You can specify conditions for @code{if,} by removing the first @code{b}
                   8937: and the trailing @code{,} from a branch with a corresponding name; e.g.,
                   8938: 
                   8939: @example
                   8940: 11 fgt if, \ if F11>0e
                   8941:   ...
                   8942: endif,
1.56      anton    8943: @end example
1.55      anton    8944: 
                   8945: @code{fbgt,} gives @code{fgt}.  
1.52      anton    8946: 
1.53      anton    8947: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
1.52      anton    8948: @subsection MIPS assembler
                   8949: 
                   8950: The MIPS assembler was originally written by Christian Pirker.
                   8951: 
                   8952: Currently the assembler and disassembler only cover the MIPS-I
                   8953: architecture (R3000), and don't support FP instructions.
                   8954: 
1.55      anton    8955: The register names @code{$a0}--@code{$a3} are not available to avoid
                   8956: shadowing hex numbers.
1.52      anton    8957: 
                   8958: Because there is no way to distinguish registers from immediate values,
                   8959: you have to explicitly use the immediate forms of instructions, i.e.,
                   8960: @code{addiu,}, not just @code{addu,} (@command{as} does this
                   8961: implicitly).
                   8962: 
                   8963: If the architecture manual specifies several formats for the instruction
                   8964: (e.g., for @code{jalr,}), you usually have to use the one with more
                   8965: arguments (i.e., two for @code{jalr,}).  When in doubt, see
                   8966: @code{arch/mips/testasm.fs} for an example of correct use.
                   8967: 
1.53      anton    8968: Branches and jumps in the MIPS architecture have a delay slot.  You have
                   8969: to fill it yourself (the simplest way is to use @code{nop,}), the
                   8970: assembler does not do it for you (unlike @command{as}).  Even
                   8971: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
                   8972: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
                   8973: and @code{then,} just specify branch targets, they are not affected.
                   8974: 
                   8975: Note that you must not put branches, jumps, or @code{li,} into the delay
                   8976: slot: @code{li,} may expand to several instructions, and control flow
                   8977: instructions may not be put into the branch delay slot in any case.
1.52      anton    8978: 
                   8979: For branches the argument specifying the target is a relative address;
                   8980: You have to add the address of the delay slot to get the absolute
                   8981: address.
1.53      anton    8982: 
                   8983: The MIPS architecture also has load delay slots and restrictions on
                   8984: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
                   8985: yourself to satisfy these restrictions, the assembler does not do it for
                   8986: you.
                   8987: 
                   8988: You can specify the conditions for @code{if,} etc. by taking a
                   8989: conditional branch and leaving away the @code{b} at the start and the
                   8990: @code{,} at the end.  E.g.,
                   8991: 
                   8992: @example
                   8993: 4 5 eq if,
                   8994:   ... \ do something if $4 equals $5
                   8995: then,
                   8996: @end example
                   8997: 
                   8998: @node Other assemblers,  , MIPS assembler, Assembler and Code Words
                   8999: @subsection Other assemblers
                   9000: 
                   9001: If you want to contribute another assembler/disassembler, please contact
                   9002: us (@email{bug-gforth@@gnu.org}) to check if we have such an assembler
                   9003: already.  If you are writing them from scratch, please use a similar
                   9004: syntax style as the one we use (i.e., postfix, commas at the end of the
                   9005: instruction names, @pxref{Common Assembler}); make the output of the
                   9006: disassembler be valid input for the assembler, and keep the style
                   9007: similar to the style we used.
                   9008: 
                   9009: Hints on implementation: The most important part is to have a good test
                   9010: suite that contains all instructions.  Once you have that, the rest is
                   9011: easy.  For actual coding you can take a look at
                   9012: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
                   9013: the assembler and disassembler, avoiding redundancy and some potential
1.59      anton    9014: bugs.  You can also look at that file (and @pxref{Advanced does> usage
                   9015: example}) to get ideas how to factor a disassembler.
1.5       anton    9016: 
1.54      anton    9017: Start with the disassembler, because it's easier to reuse data from the
                   9018: disassembler for the assembler than the other way round.
                   9019: 
                   9020: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
                   9021: how simple it can be.
                   9022: 
1.26      crook    9023: @c -------------------------------------------------------------
                   9024: @node Threading Words, Locals, Assembler and Code Words, Words
                   9025: @section Threading Words
                   9026: @cindex threading words
1.5       anton    9027: 
1.26      crook    9028: @cindex code address
                   9029: These words provide access to code addresses and other threading stuff
                   9030: in Gforth (and, possibly, other interpretive Forths). It more or less
                   9031: abstracts away the differences between direct and indirect threading
                   9032: (and, for direct threading, the machine dependences). However, at
                   9033: present this wordset is still incomplete. It is also pretty low-level;
                   9034: some day it will hopefully be made unnecessary by an internals wordset
                   9035: that abstracts implementation details away completely.
1.5       anton    9036: 
1.44      crook    9037: 
1.26      crook    9038: doc-threading-method
                   9039: doc->code-address
                   9040: doc->does-code
                   9041: doc-code-address!
                   9042: doc-does-code!
                   9043: doc-does-handler!
                   9044: doc-/does-handler
1.5       anton    9045: 
1.44      crook    9046: 
1.26      crook    9047: The code addresses produced by various defining words are produced by
                   9048: the following words:
1.5       anton    9049: 
1.44      crook    9050: 
1.26      crook    9051: doc-docol:
                   9052: doc-docon:
                   9053: doc-dovar:
                   9054: doc-douser:
                   9055: doc-dodefer:
                   9056: doc-dofield:
1.5       anton    9057: 
1.44      crook    9058: 
1.26      crook    9059: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
                   9060: with @code{>does-code}. If the word was defined in that way, the value
                   9061: returned is non-zero and identifies the @code{DOES>} used by the
                   9062: defining word.
                   9063: @comment TODO should that be ``identifies the xt of the DOES> ??''
1.5       anton    9064: 
1.26      crook    9065: @c -------------------------------------------------------------
                   9066: @node Locals, Structures, Threading Words, Words
                   9067: @section Locals
                   9068: @cindex locals
1.5       anton    9069: 
1.26      crook    9070: Local variables can make Forth programming more enjoyable and Forth
                   9071: programs easier to read. Unfortunately, the locals of ANS Forth are
                   9072: laden with restrictions. Therefore, we provide not only the ANS Forth
                   9073: locals wordset, but also our own, more powerful locals wordset (we
                   9074: implemented the ANS Forth locals wordset through our locals wordset).
1.5       anton    9075: 
1.26      crook    9076: The ideas in this section have also been published in the paper
                   9077: @cite{Automatic Scoping of Local Variables} by M. Anton Ertl, presented
                   9078: at EuroForth '94; it is available at
1.47      crook    9079: @*@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz}.
1.5       anton    9080: 
1.26      crook    9081: @menu
                   9082: * Gforth locals::               
                   9083: * ANS Forth locals::            
                   9084: @end menu
1.5       anton    9085: 
1.26      crook    9086: @node Gforth locals, ANS Forth locals, Locals, Locals
                   9087: @subsection Gforth locals
                   9088: @cindex Gforth locals
                   9089: @cindex locals, Gforth style
1.5       anton    9090: 
1.26      crook    9091: Locals can be defined with
1.5       anton    9092: 
                   9093: @example
1.26      crook    9094: @{ local1 local2 ... -- comment @}
                   9095: @end example
                   9096: or
                   9097: @example
                   9098: @{ local1 local2 ... @}
1.5       anton    9099: @end example
                   9100: 
1.26      crook    9101: E.g.,
1.5       anton    9102: @example
1.26      crook    9103: : max @{ n1 n2 -- n3 @}
                   9104:  n1 n2 > if
                   9105:    n1
                   9106:  else
                   9107:    n2
                   9108:  endif ;
1.5       anton    9109: @end example
                   9110: 
1.26      crook    9111: The similarity of locals definitions with stack comments is intended. A
                   9112: locals definition often replaces the stack comment of a word. The order
                   9113: of the locals corresponds to the order in a stack comment and everything
                   9114: after the @code{--} is really a comment.
1.5       anton    9115: 
1.26      crook    9116: This similarity has one disadvantage: It is too easy to confuse locals
                   9117: declarations with stack comments, causing bugs and making them hard to
                   9118: find. However, this problem can be avoided by appropriate coding
                   9119: conventions: Do not use both notations in the same program. If you do,
                   9120: they should be distinguished using additional means, e.g. by position.
                   9121: 
                   9122: @cindex types of locals
                   9123: @cindex locals types
                   9124: The name of the local may be preceded by a type specifier, e.g.,
                   9125: @code{F:} for a floating point value:
                   9126: 
                   9127: @example
                   9128: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
                   9129: \ complex multiplication
                   9130:  Ar Br f* Ai Bi f* f-
                   9131:  Ar Bi f* Ai Br f* f+ ;
                   9132: @end example
                   9133: 
                   9134: @cindex flavours of locals
                   9135: @cindex locals flavours
                   9136: @cindex value-flavoured locals
                   9137: @cindex variable-flavoured locals
                   9138: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
                   9139: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
                   9140: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
                   9141: with @code{W:}, @code{D:} etc.) produces its value and can be changed
                   9142: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
                   9143: produces its address (which becomes invalid when the variable's scope is
                   9144: left). E.g., the standard word @code{emit} can be defined in terms of
                   9145: @code{type} like this:
1.5       anton    9146: 
                   9147: @example
1.26      crook    9148: : emit @{ C^ char* -- @}
                   9149:     char* 1 type ;
1.5       anton    9150: @end example
                   9151: 
1.26      crook    9152: @cindex default type of locals
                   9153: @cindex locals, default type
                   9154: A local without type specifier is a @code{W:} local. Both flavours of
                   9155: locals are initialized with values from the data or FP stack.
1.5       anton    9156: 
1.26      crook    9157: Currently there is no way to define locals with user-defined data
                   9158: structures, but we are working on it.
1.5       anton    9159: 
1.26      crook    9160: Gforth allows defining locals everywhere in a colon definition. This
                   9161: poses the following questions:
1.5       anton    9162: 
1.26      crook    9163: @menu
                   9164: * Where are locals visible by name?::  
                   9165: * How long do locals live?::    
                   9166: * Programming Style::           
                   9167: * Implementation::              
                   9168: @end menu
1.5       anton    9169: 
1.26      crook    9170: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
                   9171: @subsubsection Where are locals visible by name?
                   9172: @cindex locals visibility
                   9173: @cindex visibility of locals
                   9174: @cindex scope of locals
1.5       anton    9175: 
1.26      crook    9176: Basically, the answer is that locals are visible where you would expect
                   9177: it in block-structured languages, and sometimes a little longer. If you
                   9178: want to restrict the scope of a local, enclose its definition in
                   9179: @code{SCOPE}...@code{ENDSCOPE}.
1.5       anton    9180: 
1.44      crook    9181: 
1.26      crook    9182: doc-scope
                   9183: doc-endscope
1.5       anton    9184: 
1.44      crook    9185: 
1.26      crook    9186: These words behave like control structure words, so you can use them
                   9187: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
                   9188: arbitrary ways.
1.5       anton    9189: 
1.26      crook    9190: If you want a more exact answer to the visibility question, here's the
                   9191: basic principle: A local is visible in all places that can only be
                   9192: reached through the definition of the local@footnote{In compiler
                   9193: construction terminology, all places dominated by the definition of the
                   9194: local.}. In other words, it is not visible in places that can be reached
                   9195: without going through the definition of the local. E.g., locals defined
                   9196: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
                   9197: defined in @code{BEGIN}...@code{UNTIL} are visible after the
                   9198: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.5       anton    9199: 
1.26      crook    9200: The reasoning behind this solution is: We want to have the locals
                   9201: visible as long as it is meaningful. The user can always make the
                   9202: visibility shorter by using explicit scoping. In a place that can
                   9203: only be reached through the definition of a local, the meaning of a
                   9204: local name is clear. In other places it is not: How is the local
                   9205: initialized at the control flow path that does not contain the
                   9206: definition? Which local is meant, if the same name is defined twice in
                   9207: two independent control flow paths?
1.5       anton    9208: 
1.26      crook    9209: This should be enough detail for nearly all users, so you can skip the
                   9210: rest of this section. If you really must know all the gory details and
                   9211: options, read on.
1.5       anton    9212: 
1.26      crook    9213: In order to implement this rule, the compiler has to know which places
                   9214: are unreachable. It knows this automatically after @code{AHEAD},
                   9215: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
                   9216: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
                   9217: compiler that the control flow never reaches that place. If
                   9218: @code{UNREACHABLE} is not used where it could, the only consequence is
                   9219: that the visibility of some locals is more limited than the rule above
                   9220: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
                   9221: lie to the compiler), buggy code will be produced.
1.5       anton    9222: 
1.44      crook    9223: 
1.26      crook    9224: doc-unreachable
1.5       anton    9225: 
1.44      crook    9226: 
1.26      crook    9227: Another problem with this rule is that at @code{BEGIN}, the compiler
                   9228: does not know which locals will be visible on the incoming
                   9229: back-edge. All problems discussed in the following are due to this
                   9230: ignorance of the compiler (we discuss the problems using @code{BEGIN}
                   9231: loops as examples; the discussion also applies to @code{?DO} and other
                   9232: loops). Perhaps the most insidious example is:
1.5       anton    9233: @example
1.26      crook    9234: AHEAD
                   9235: BEGIN
                   9236:   x
                   9237: [ 1 CS-ROLL ] THEN
                   9238:   @{ x @}
                   9239:   ...
                   9240: UNTIL
                   9241: @end example
1.5       anton    9242: 
1.26      crook    9243: This should be legal according to the visibility rule. The use of
                   9244: @code{x} can only be reached through the definition; but that appears
                   9245: textually below the use.
1.5       anton    9246: 
1.26      crook    9247: From this example it is clear that the visibility rules cannot be fully
                   9248: implemented without major headaches. Our implementation treats common
                   9249: cases as advertised and the exceptions are treated in a safe way: The
                   9250: compiler makes a reasonable guess about the locals visible after a
                   9251: @code{BEGIN}; if it is too pessimistic, the
                   9252: user will get a spurious error about the local not being defined; if the
                   9253: compiler is too optimistic, it will notice this later and issue a
                   9254: warning. In the case above the compiler would complain about @code{x}
                   9255: being undefined at its use. You can see from the obscure examples in
                   9256: this section that it takes quite unusual control structures to get the
                   9257: compiler into trouble, and even then it will often do fine.
1.5       anton    9258: 
1.26      crook    9259: If the @code{BEGIN} is reachable from above, the most optimistic guess
                   9260: is that all locals visible before the @code{BEGIN} will also be
                   9261: visible after the @code{BEGIN}. This guess is valid for all loops that
                   9262: are entered only through the @code{BEGIN}, in particular, for normal
                   9263: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
                   9264: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
                   9265: compiler. When the branch to the @code{BEGIN} is finally generated by
                   9266: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
                   9267: warns the user if it was too optimistic:
                   9268: @example
                   9269: IF
                   9270:   @{ x @}
                   9271: BEGIN
                   9272:   \ x ? 
                   9273: [ 1 cs-roll ] THEN
                   9274:   ...
                   9275: UNTIL
1.5       anton    9276: @end example
                   9277: 
1.26      crook    9278: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
                   9279: optimistically assumes that it lives until the @code{THEN}. It notices
                   9280: this difference when it compiles the @code{UNTIL} and issues a
                   9281: warning. The user can avoid the warning, and make sure that @code{x}
                   9282: is not used in the wrong area by using explicit scoping:
                   9283: @example
                   9284: IF
                   9285:   SCOPE
                   9286:   @{ x @}
                   9287:   ENDSCOPE
                   9288: BEGIN
                   9289: [ 1 cs-roll ] THEN
                   9290:   ...
                   9291: UNTIL
                   9292: @end example
1.5       anton    9293: 
1.26      crook    9294: Since the guess is optimistic, there will be no spurious error messages
                   9295: about undefined locals.
1.5       anton    9296: 
1.26      crook    9297: If the @code{BEGIN} is not reachable from above (e.g., after
                   9298: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
                   9299: optimistic guess, as the locals visible after the @code{BEGIN} may be
                   9300: defined later. Therefore, the compiler assumes that no locals are
                   9301: visible after the @code{BEGIN}. However, the user can use
                   9302: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
                   9303: visible at the BEGIN as at the point where the top control-flow stack
                   9304: item was created.
1.5       anton    9305: 
1.44      crook    9306: 
1.26      crook    9307: doc-assume-live
1.5       anton    9308: 
1.44      crook    9309: 
                   9310: @noindent
1.26      crook    9311: E.g.,
1.5       anton    9312: @example
1.26      crook    9313: @{ x @}
                   9314: AHEAD
                   9315: ASSUME-LIVE
                   9316: BEGIN
                   9317:   x
                   9318: [ 1 CS-ROLL ] THEN
                   9319:   ...
                   9320: UNTIL
1.5       anton    9321: @end example
                   9322: 
1.26      crook    9323: Other cases where the locals are defined before the @code{BEGIN} can be
                   9324: handled by inserting an appropriate @code{CS-ROLL} before the
                   9325: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
                   9326: behind the @code{ASSUME-LIVE}).
1.5       anton    9327: 
1.26      crook    9328: Cases where locals are defined after the @code{BEGIN} (but should be
                   9329: visible immediately after the @code{BEGIN}) can only be handled by
                   9330: rearranging the loop. E.g., the ``most insidious'' example above can be
                   9331: arranged into:
1.5       anton    9332: @example
1.26      crook    9333: BEGIN
                   9334:   @{ x @}
                   9335:   ... 0=
                   9336: WHILE
                   9337:   x
                   9338: REPEAT
1.5       anton    9339: @end example
                   9340: 
1.26      crook    9341: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
                   9342: @subsubsection How long do locals live?
                   9343: @cindex locals lifetime
                   9344: @cindex lifetime of locals
1.5       anton    9345: 
1.26      crook    9346: The right answer for the lifetime question would be: A local lives at
                   9347: least as long as it can be accessed. For a value-flavoured local this
                   9348: means: until the end of its visibility. However, a variable-flavoured
                   9349: local could be accessed through its address far beyond its visibility
                   9350: scope. Ultimately, this would mean that such locals would have to be
                   9351: garbage collected. Since this entails un-Forth-like implementation
                   9352: complexities, I adopted the same cowardly solution as some other
                   9353: languages (e.g., C): The local lives only as long as it is visible;
                   9354: afterwards its address is invalid (and programs that access it
                   9355: afterwards are erroneous).
1.5       anton    9356: 
1.26      crook    9357: @node Programming Style, Implementation, How long do locals live?, Gforth locals
                   9358: @subsubsection Programming Style
                   9359: @cindex locals programming style
                   9360: @cindex programming style, locals
1.5       anton    9361: 
1.26      crook    9362: The freedom to define locals anywhere has the potential to change
                   9363: programming styles dramatically. In particular, the need to use the
                   9364: return stack for intermediate storage vanishes. Moreover, all stack
                   9365: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
                   9366: determined arguments) can be eliminated: If the stack items are in the
                   9367: wrong order, just write a locals definition for all of them; then
                   9368: write the items in the order you want.
1.5       anton    9369: 
1.26      crook    9370: This seems a little far-fetched and eliminating stack manipulations is
                   9371: unlikely to become a conscious programming objective. Still, the number
                   9372: of stack manipulations will be reduced dramatically if local variables
1.49      anton    9373: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
1.26      crook    9374: a traditional implementation of @code{max}).
1.5       anton    9375: 
1.26      crook    9376: This shows one potential benefit of locals: making Forth programs more
                   9377: readable. Of course, this benefit will only be realized if the
                   9378: programmers continue to honour the principle of factoring instead of
                   9379: using the added latitude to make the words longer.
1.5       anton    9380: 
1.26      crook    9381: @cindex single-assignment style for locals
                   9382: Using @code{TO} can and should be avoided.  Without @code{TO},
                   9383: every value-flavoured local has only a single assignment and many
                   9384: advantages of functional languages apply to Forth. I.e., programs are
                   9385: easier to analyse, to optimize and to read: It is clear from the
                   9386: definition what the local stands for, it does not turn into something
                   9387: different later.
1.5       anton    9388: 
1.26      crook    9389: E.g., a definition using @code{TO} might look like this:
1.5       anton    9390: @example
1.26      crook    9391: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9392:  u1 u2 min 0
                   9393:  ?do
                   9394:    addr1 c@@ addr2 c@@ -
                   9395:    ?dup-if
                   9396:      unloop exit
                   9397:    then
                   9398:    addr1 char+ TO addr1
                   9399:    addr2 char+ TO addr2
                   9400:  loop
                   9401:  u1 u2 - ;
1.5       anton    9402: @end example
1.26      crook    9403: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
                   9404: every loop iteration. @code{strcmp} is a typical example of the
                   9405: readability problems of using @code{TO}. When you start reading
                   9406: @code{strcmp}, you think that @code{addr1} refers to the start of the
                   9407: string. Only near the end of the loop you realize that it is something
                   9408: else.
1.5       anton    9409: 
1.26      crook    9410: This can be avoided by defining two locals at the start of the loop that
                   9411: are initialized with the right value for the current iteration.
1.5       anton    9412: @example
1.26      crook    9413: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9414:  addr1 addr2
                   9415:  u1 u2 min 0 
                   9416:  ?do @{ s1 s2 @}
                   9417:    s1 c@@ s2 c@@ -
                   9418:    ?dup-if
                   9419:      unloop exit
                   9420:    then
                   9421:    s1 char+ s2 char+
                   9422:  loop
                   9423:  2drop
                   9424:  u1 u2 - ;
1.5       anton    9425: @end example
1.26      crook    9426: Here it is clear from the start that @code{s1} has a different value
                   9427: in every loop iteration.
1.5       anton    9428: 
1.26      crook    9429: @node Implementation,  , Programming Style, Gforth locals
                   9430: @subsubsection Implementation
                   9431: @cindex locals implementation
                   9432: @cindex implementation of locals
1.5       anton    9433: 
1.26      crook    9434: @cindex locals stack
                   9435: Gforth uses an extra locals stack. The most compelling reason for
                   9436: this is that the return stack is not float-aligned; using an extra stack
                   9437: also eliminates the problems and restrictions of using the return stack
                   9438: as locals stack. Like the other stacks, the locals stack grows toward
                   9439: lower addresses. A few primitives allow an efficient implementation:
1.5       anton    9440: 
1.44      crook    9441: 
1.26      crook    9442: doc-@local#
                   9443: doc-f@local#
                   9444: doc-laddr#
                   9445: doc-lp+!#
                   9446: doc-lp!
                   9447: doc->l
                   9448: doc-f>l
1.5       anton    9449: 
1.44      crook    9450: 
1.26      crook    9451: In addition to these primitives, some specializations of these
                   9452: primitives for commonly occurring inline arguments are provided for
                   9453: efficiency reasons, e.g., @code{@@local0} as specialization of
                   9454: @code{@@local#} for the inline argument 0. The following compiling words
                   9455: compile the right specialized version, or the general version, as
                   9456: appropriate:
1.6       pazsan   9457: 
1.44      crook    9458: 
1.26      crook    9459: doc-compile-@local
                   9460: doc-compile-f@local
                   9461: doc-compile-lp+!
1.12      anton    9462: 
1.44      crook    9463: 
1.26      crook    9464: Combinations of conditional branches and @code{lp+!#} like
                   9465: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
                   9466: is taken) are provided for efficiency and correctness in loops.
1.6       pazsan   9467: 
1.26      crook    9468: A special area in the dictionary space is reserved for keeping the
                   9469: local variable names. @code{@{} switches the dictionary pointer to this
                   9470: area and @code{@}} switches it back and generates the locals
                   9471: initializing code. @code{W:} etc.@ are normal defining words. This
                   9472: special area is cleared at the start of every colon definition.
1.6       pazsan   9473: 
1.26      crook    9474: @cindex word list for defining locals
                   9475: A special feature of Gforth's dictionary is used to implement the
                   9476: definition of locals without type specifiers: every word list (aka
                   9477: vocabulary) has its own methods for searching
                   9478: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
                   9479: with a special search method: When it is searched for a word, it
                   9480: actually creates that word using @code{W:}. @code{@{} changes the search
                   9481: order to first search the word list containing @code{@}}, @code{W:} etc.,
                   9482: and then the word list for defining locals without type specifiers.
1.12      anton    9483: 
1.26      crook    9484: The lifetime rules support a stack discipline within a colon
                   9485: definition: The lifetime of a local is either nested with other locals
                   9486: lifetimes or it does not overlap them.
1.6       pazsan   9487: 
1.26      crook    9488: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
                   9489: pointer manipulation is generated. Between control structure words
                   9490: locals definitions can push locals onto the locals stack. @code{AGAIN}
                   9491: is the simplest of the other three control flow words. It has to
                   9492: restore the locals stack depth of the corresponding @code{BEGIN}
                   9493: before branching. The code looks like this:
                   9494: @format
                   9495: @code{lp+!#} current-locals-size @minus{} dest-locals-size
                   9496: @code{branch} <begin>
                   9497: @end format
1.6       pazsan   9498: 
1.26      crook    9499: @code{UNTIL} is a little more complicated: If it branches back, it
                   9500: must adjust the stack just like @code{AGAIN}. But if it falls through,
                   9501: the locals stack must not be changed. The compiler generates the
                   9502: following code:
                   9503: @format
                   9504: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
                   9505: @end format
                   9506: The locals stack pointer is only adjusted if the branch is taken.
1.6       pazsan   9507: 
1.26      crook    9508: @code{THEN} can produce somewhat inefficient code:
                   9509: @format
                   9510: @code{lp+!#} current-locals-size @minus{} orig-locals-size
                   9511: <orig target>:
                   9512: @code{lp+!#} orig-locals-size @minus{} new-locals-size
                   9513: @end format
                   9514: The second @code{lp+!#} adjusts the locals stack pointer from the
1.29      crook    9515: level at the @i{orig} point to the level after the @code{THEN}. The
1.26      crook    9516: first @code{lp+!#} adjusts the locals stack pointer from the current
                   9517: level to the level at the orig point, so the complete effect is an
                   9518: adjustment from the current level to the right level after the
                   9519: @code{THEN}.
1.6       pazsan   9520: 
1.26      crook    9521: @cindex locals information on the control-flow stack
                   9522: @cindex control-flow stack items, locals information
                   9523: In a conventional Forth implementation a dest control-flow stack entry
                   9524: is just the target address and an orig entry is just the address to be
                   9525: patched. Our locals implementation adds a word list to every orig or dest
                   9526: item. It is the list of locals visible (or assumed visible) at the point
                   9527: described by the entry. Our implementation also adds a tag to identify
                   9528: the kind of entry, in particular to differentiate between live and dead
                   9529: (reachable and unreachable) orig entries.
1.6       pazsan   9530: 
1.26      crook    9531: A few unusual operations have to be performed on locals word lists:
1.6       pazsan   9532: 
1.44      crook    9533: 
1.26      crook    9534: doc-common-list
                   9535: doc-sub-list?
                   9536: doc-list-size
1.6       pazsan   9537: 
1.44      crook    9538: 
1.26      crook    9539: Several features of our locals word list implementation make these
                   9540: operations easy to implement: The locals word lists are organised as
                   9541: linked lists; the tails of these lists are shared, if the lists
                   9542: contain some of the same locals; and the address of a name is greater
                   9543: than the address of the names behind it in the list.
1.6       pazsan   9544: 
1.26      crook    9545: Another important implementation detail is the variable
                   9546: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
                   9547: determine if they can be reached directly or only through the branch
                   9548: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
                   9549: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
                   9550: definition, by @code{BEGIN} and usually by @code{THEN}.
1.6       pazsan   9551: 
1.26      crook    9552: Counted loops are similar to other loops in most respects, but
                   9553: @code{LEAVE} requires special attention: It performs basically the same
                   9554: service as @code{AHEAD}, but it does not create a control-flow stack
                   9555: entry. Therefore the information has to be stored elsewhere;
                   9556: traditionally, the information was stored in the target fields of the
                   9557: branches created by the @code{LEAVE}s, by organizing these fields into a
                   9558: linked list. Unfortunately, this clever trick does not provide enough
                   9559: space for storing our extended control flow information. Therefore, we
                   9560: introduce another stack, the leave stack. It contains the control-flow
                   9561: stack entries for all unresolved @code{LEAVE}s.
1.6       pazsan   9562: 
1.26      crook    9563: Local names are kept until the end of the colon definition, even if
                   9564: they are no longer visible in any control-flow path. In a few cases
                   9565: this may lead to increased space needs for the locals name area, but
                   9566: usually less than reclaiming this space would cost in code size.
1.6       pazsan   9567: 
                   9568: 
1.26      crook    9569: @node ANS Forth locals,  , Gforth locals, Locals
                   9570: @subsection ANS Forth locals
                   9571: @cindex locals, ANS Forth style
1.6       pazsan   9572: 
1.26      crook    9573: The ANS Forth locals wordset does not define a syntax for locals, but
                   9574: words that make it possible to define various syntaxes. One of the
                   9575: possible syntaxes is a subset of the syntax we used in the Gforth locals
                   9576: wordset, i.e.:
1.6       pazsan   9577: 
                   9578: @example
1.26      crook    9579: @{ local1 local2 ... -- comment @}
1.6       pazsan   9580: @end example
1.23      crook    9581: @noindent
1.26      crook    9582: or
1.6       pazsan   9583: @example
1.26      crook    9584: @{ local1 local2 ... @}
1.6       pazsan   9585: @end example
                   9586: 
1.26      crook    9587: The order of the locals corresponds to the order in a stack comment. The
                   9588: restrictions are:
1.6       pazsan   9589: 
                   9590: @itemize @bullet
                   9591: @item
1.26      crook    9592: Locals can only be cell-sized values (no type specifiers are allowed).
1.6       pazsan   9593: @item
1.26      crook    9594: Locals can be defined only outside control structures.
1.6       pazsan   9595: @item
1.26      crook    9596: Locals can interfere with explicit usage of the return stack. For the
                   9597: exact (and long) rules, see the standard. If you don't use return stack
                   9598: accessing words in a definition using locals, you will be all right. The
                   9599: purpose of this rule is to make locals implementation on the return
                   9600: stack easier.
1.6       pazsan   9601: @item
1.26      crook    9602: The whole definition must be in one line.
                   9603: @end itemize
1.6       pazsan   9604: 
1.44      crook    9605: Locals defined in this way behave like @code{VALUE}s
1.49      anton    9606: (@pxref{Values}). I.e., they are initialized from the stack. Using their
1.26      crook    9607: name produces their value. Their value can be changed using @code{TO}.
1.6       pazsan   9608: 
1.26      crook    9609: Since this syntax is supported by Gforth directly, you need not do
                   9610: anything to use it. If you want to port a program using this syntax to
                   9611: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
                   9612: syntax on the other system.
1.6       pazsan   9613: 
1.26      crook    9614: Note that a syntax shown in the standard, section A.13 looks
                   9615: similar, but is quite different in having the order of locals
                   9616: reversed. Beware!
1.6       pazsan   9617: 
1.26      crook    9618: The ANS Forth locals wordset itself consists of a word:
1.6       pazsan   9619: 
1.44      crook    9620: 
1.26      crook    9621: doc-(local)
1.6       pazsan   9622: 
1.44      crook    9623: 
1.26      crook    9624: The ANS Forth locals extension wordset defines a syntax using @code{locals|}, but it is so
                   9625: awful that we strongly recommend not to use it. We have implemented this
                   9626: syntax to make porting to Gforth easy, but do not document it here. The
                   9627: problem with this syntax is that the locals are defined in an order
                   9628: reversed with respect to the standard stack comment notation, making
                   9629: programs harder to read, and easier to misread and miswrite. The only
                   9630: merit of this syntax is that it is easy to implement using the ANS Forth
                   9631: locals wordset.
1.7       pazsan   9632: 
                   9633: 
1.26      crook    9634: @c ----------------------------------------------------------
                   9635: @node Structures, Object-oriented Forth, Locals, Words
                   9636: @section  Structures
                   9637: @cindex structures
                   9638: @cindex records
1.7       pazsan   9639: 
1.26      crook    9640: This section presents the structure package that comes with Gforth. A
                   9641: version of the package implemented in ANS Forth is available in
                   9642: @file{compat/struct.fs}. This package was inspired by a posting on
                   9643: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
                   9644: possibly John Hayes). A version of this section has been published in
                   9645: ???. Marcel Hendrix provided helpful comments.
1.7       pazsan   9646: 
1.26      crook    9647: @menu
                   9648: * Why explicit structure support?::  
                   9649: * Structure Usage::             
                   9650: * Structure Naming Convention::  
                   9651: * Structure Implementation::    
                   9652: * Structure Glossary::          
                   9653: @end menu
1.7       pazsan   9654: 
1.26      crook    9655: @node Why explicit structure support?, Structure Usage, Structures, Structures
                   9656: @subsection Why explicit structure support?
1.7       pazsan   9657: 
1.26      crook    9658: @cindex address arithmetic for structures
                   9659: @cindex structures using address arithmetic
                   9660: If we want to use a structure containing several fields, we could simply
                   9661: reserve memory for it, and access the fields using address arithmetic
1.32      anton    9662: (@pxref{Address arithmetic}). As an example, consider a structure with
1.26      crook    9663: the following fields
1.7       pazsan   9664: 
1.26      crook    9665: @table @code
                   9666: @item a
                   9667: is a float
                   9668: @item b
                   9669: is a cell
                   9670: @item c
                   9671: is a float
                   9672: @end table
1.7       pazsan   9673: 
1.26      crook    9674: Given the (float-aligned) base address of the structure we get the
                   9675: address of the field
1.13      pazsan   9676: 
1.26      crook    9677: @table @code
                   9678: @item a
                   9679: without doing anything further.
                   9680: @item b
                   9681: with @code{float+}
                   9682: @item c
                   9683: with @code{float+ cell+ faligned}
                   9684: @end table
1.13      pazsan   9685: 
1.26      crook    9686: It is easy to see that this can become quite tiring. 
1.13      pazsan   9687: 
1.26      crook    9688: Moreover, it is not very readable, because seeing a
                   9689: @code{cell+} tells us neither which kind of structure is
                   9690: accessed nor what field is accessed; we have to somehow infer the kind
                   9691: of structure, and then look up in the documentation, which field of
                   9692: that structure corresponds to that offset.
1.13      pazsan   9693: 
1.26      crook    9694: Finally, this kind of address arithmetic also causes maintenance
                   9695: troubles: If you add or delete a field somewhere in the middle of the
                   9696: structure, you have to find and change all computations for the fields
                   9697: afterwards.
1.13      pazsan   9698: 
1.26      crook    9699: So, instead of using @code{cell+} and friends directly, how
                   9700: about storing the offsets in constants:
1.13      pazsan   9701: 
                   9702: @example
1.26      crook    9703: 0 constant a-offset
                   9704: 0 float+ constant b-offset
                   9705: 0 float+ cell+ faligned c-offset
1.13      pazsan   9706: @end example
                   9707: 
1.26      crook    9708: Now we can get the address of field @code{x} with @code{x-offset
                   9709: +}. This is much better in all respects. Of course, you still
                   9710: have to change all later offset definitions if you add a field. You can
                   9711: fix this by declaring the offsets in the following way:
1.13      pazsan   9712: 
                   9713: @example
1.26      crook    9714: 0 constant a-offset
                   9715: a-offset float+ constant b-offset
                   9716: b-offset cell+ faligned constant c-offset
1.13      pazsan   9717: @end example
                   9718: 
1.26      crook    9719: Since we always use the offsets with @code{+}, we could use a defining
                   9720: word @code{cfield} that includes the @code{+} in the action of the
                   9721: defined word:
1.8       pazsan   9722: 
                   9723: @example
1.26      crook    9724: : cfield ( n "name" -- )
                   9725:     create ,
                   9726: does> ( name execution: addr1 -- addr2 )
                   9727:     @@ + ;
1.13      pazsan   9728: 
1.26      crook    9729: 0 cfield a
                   9730: 0 a float+ cfield b
                   9731: 0 b cell+ faligned cfield c
1.13      pazsan   9732: @end example
                   9733: 
1.26      crook    9734: Instead of @code{x-offset +}, we now simply write @code{x}.
                   9735: 
                   9736: The structure field words now can be used quite nicely. However,
                   9737: their definition is still a bit cumbersome: We have to repeat the
                   9738: name, the information about size and alignment is distributed before
                   9739: and after the field definitions etc.  The structure package presented
                   9740: here addresses these problems.
                   9741: 
                   9742: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
                   9743: @subsection Structure Usage
                   9744: @cindex structure usage
1.13      pazsan   9745: 
1.26      crook    9746: @cindex @code{field} usage
                   9747: @cindex @code{struct} usage
                   9748: @cindex @code{end-struct} usage
                   9749: You can define a structure for a (data-less) linked list with:
1.13      pazsan   9750: @example
1.26      crook    9751: struct
                   9752:     cell% field list-next
                   9753: end-struct list%
1.13      pazsan   9754: @end example
                   9755: 
1.26      crook    9756: With the address of the list node on the stack, you can compute the
                   9757: address of the field that contains the address of the next node with
                   9758: @code{list-next}. E.g., you can determine the length of a list
                   9759: with:
1.13      pazsan   9760: 
                   9761: @example
1.26      crook    9762: : list-length ( list -- n )
                   9763: \ "list" is a pointer to the first element of a linked list
                   9764: \ "n" is the length of the list
                   9765:     0 BEGIN ( list1 n1 )
                   9766:         over
                   9767:     WHILE ( list1 n1 )
                   9768:         1+ swap list-next @@ swap
                   9769:     REPEAT
                   9770:     nip ;
1.13      pazsan   9771: @end example
                   9772: 
1.26      crook    9773: You can reserve memory for a list node in the dictionary with
                   9774: @code{list% %allot}, which leaves the address of the list node on the
                   9775: stack. For the equivalent allocation on the heap you can use @code{list%
                   9776: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
                   9777: use @code{list% %allocate}). You can get the the size of a list
                   9778: node with @code{list% %size} and its alignment with @code{list%
                   9779: %alignment}.
1.13      pazsan   9780: 
1.26      crook    9781: Note that in ANS Forth the body of a @code{create}d word is
                   9782: @code{aligned} but not necessarily @code{faligned};
                   9783: therefore, if you do a:
1.13      pazsan   9784: @example
1.26      crook    9785: create @emph{name} foo% %allot
1.8       pazsan   9786: @end example
                   9787: 
1.26      crook    9788: @noindent
                   9789: then the memory alloted for @code{foo%} is
                   9790: guaranteed to start at the body of @code{@emph{name}} only if
                   9791: @code{foo%} contains only character, cell and double fields.
1.20      pazsan   9792: 
1.45      crook    9793: @cindex structures containing structures
1.26      crook    9794: You can include a structure @code{foo%} as a field of
                   9795: another structure, like this:
1.20      pazsan   9796: @example
1.26      crook    9797: struct
                   9798: ...
                   9799:     foo% field ...
                   9800: ...
                   9801: end-struct ...
1.20      pazsan   9802: @end example
                   9803: 
1.26      crook    9804: @cindex structure extension
                   9805: @cindex extended records
                   9806: Instead of starting with an empty structure, you can extend an
                   9807: existing structure. E.g., a plain linked list without data, as defined
                   9808: above, is hardly useful; You can extend it to a linked list of integers,
                   9809: like this:@footnote{This feature is also known as @emph{extended
                   9810: records}. It is the main innovation in the Oberon language; in other
                   9811: words, adding this feature to Modula-2 led Wirth to create a new
                   9812: language, write a new compiler etc.  Adding this feature to Forth just
                   9813: required a few lines of code.}
1.20      pazsan   9814: 
                   9815: @example
1.26      crook    9816: list%
                   9817:     cell% field intlist-int
                   9818: end-struct intlist%
1.20      pazsan   9819: @end example
                   9820: 
1.26      crook    9821: @code{intlist%} is a structure with two fields:
                   9822: @code{list-next} and @code{intlist-int}.
1.20      pazsan   9823: 
1.26      crook    9824: @cindex structures containing arrays
                   9825: You can specify an array type containing @emph{n} elements of
                   9826: type @code{foo%} like this:
1.20      pazsan   9827: 
                   9828: @example
1.26      crook    9829: foo% @emph{n} *
1.20      pazsan   9830: @end example
                   9831: 
1.26      crook    9832: You can use this array type in any place where you can use a normal
                   9833: type, e.g., when defining a @code{field}, or with
                   9834: @code{%allot}.
1.20      pazsan   9835: 
1.26      crook    9836: @cindex first field optimization
                   9837: The first field is at the base address of a structure and the word
                   9838: for this field (e.g., @code{list-next}) actually does not change
                   9839: the address on the stack. You may be tempted to leave it away in the
                   9840: interest of run-time and space efficiency. This is not necessary,
                   9841: because the structure package optimizes this case and compiling such
                   9842: words does not generate any code. So, in the interest of readability
                   9843: and maintainability you should include the word for the field when
                   9844: accessing the field.
1.20      pazsan   9845: 
1.26      crook    9846: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
                   9847: @subsection Structure Naming Convention
                   9848: @cindex structure naming convention
1.20      pazsan   9849: 
1.26      crook    9850: The field names that come to (my) mind are often quite generic, and,
                   9851: if used, would cause frequent name clashes. E.g., many structures
                   9852: probably contain a @code{counter} field. The structure names
                   9853: that come to (my) mind are often also the logical choice for the names
                   9854: of words that create such a structure.
1.20      pazsan   9855: 
1.26      crook    9856: Therefore, I have adopted the following naming conventions: 
1.20      pazsan   9857: 
1.26      crook    9858: @itemize @bullet
                   9859: @cindex field naming convention
                   9860: @item
                   9861: The names of fields are of the form
                   9862: @code{@emph{struct}-@emph{field}}, where
                   9863: @code{@emph{struct}} is the basic name of the structure, and
                   9864: @code{@emph{field}} is the basic name of the field. You can
                   9865: think of field words as converting the (address of the)
                   9866: structure into the (address of the) field.
1.20      pazsan   9867: 
1.26      crook    9868: @cindex structure naming convention
                   9869: @item
                   9870: The names of structures are of the form
                   9871: @code{@emph{struct}%}, where
                   9872: @code{@emph{struct}} is the basic name of the structure.
                   9873: @end itemize
1.20      pazsan   9874: 
1.26      crook    9875: This naming convention does not work that well for fields of extended
                   9876: structures; e.g., the integer list structure has a field
                   9877: @code{intlist-int}, but has @code{list-next}, not
                   9878: @code{intlist-next}.
1.20      pazsan   9879: 
1.26      crook    9880: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
                   9881: @subsection Structure Implementation
                   9882: @cindex structure implementation
                   9883: @cindex implementation of structures
1.20      pazsan   9884: 
1.26      crook    9885: The central idea in the implementation is to pass the data about the
                   9886: structure being built on the stack, not in some global
                   9887: variable. Everything else falls into place naturally once this design
                   9888: decision is made.
1.20      pazsan   9889: 
1.26      crook    9890: The type description on the stack is of the form @emph{align
                   9891: size}. Keeping the size on the top-of-stack makes dealing with arrays
                   9892: very simple.
1.20      pazsan   9893: 
1.26      crook    9894: @code{field} is a defining word that uses @code{Create}
                   9895: and @code{DOES>}. The body of the field contains the offset
                   9896: of the field, and the normal @code{DOES>} action is simply:
1.20      pazsan   9897: 
                   9898: @example
1.48      anton    9899: @@ +
1.20      pazsan   9900: @end example
                   9901: 
1.23      crook    9902: @noindent
1.26      crook    9903: i.e., add the offset to the address, giving the stack effect
1.29      crook    9904: @i{addr1 -- addr2} for a field.
1.20      pazsan   9905: 
1.26      crook    9906: @cindex first field optimization, implementation
                   9907: This simple structure is slightly complicated by the optimization
                   9908: for fields with offset 0, which requires a different
                   9909: @code{DOES>}-part (because we cannot rely on there being
                   9910: something on the stack if such a field is invoked during
                   9911: compilation). Therefore, we put the different @code{DOES>}-parts
                   9912: in separate words, and decide which one to invoke based on the
                   9913: offset. For a zero offset, the field is basically a noop; it is
                   9914: immediate, and therefore no code is generated when it is compiled.
1.20      pazsan   9915: 
1.26      crook    9916: @node Structure Glossary,  , Structure Implementation, Structures
                   9917: @subsection Structure Glossary
                   9918: @cindex structure glossary
1.20      pazsan   9919: 
1.44      crook    9920: 
1.26      crook    9921: doc-%align
                   9922: doc-%alignment
                   9923: doc-%alloc
                   9924: doc-%allocate
                   9925: doc-%allot
                   9926: doc-cell%
                   9927: doc-char%
                   9928: doc-dfloat%
                   9929: doc-double%
                   9930: doc-end-struct
                   9931: doc-field
                   9932: doc-float%
                   9933: doc-naligned
                   9934: doc-sfloat%
                   9935: doc-%size
                   9936: doc-struct
1.23      crook    9937: 
1.44      crook    9938: 
1.26      crook    9939: @c -------------------------------------------------------------
                   9940: @node Object-oriented Forth, Passing Commands to the OS, Structures, Words
                   9941: @section Object-oriented Forth
1.20      pazsan   9942: 
1.26      crook    9943: Gforth comes with three packages for object-oriented programming:
                   9944: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
                   9945: is preloaded, so you have to @code{include} them before use. The most
                   9946: important differences between these packages (and others) are discussed
                   9947: in @ref{Comparison with other object models}. All packages are written
                   9948: in ANS Forth and can be used with any other ANS Forth.
1.20      pazsan   9949: 
1.26      crook    9950: @menu
1.48      anton    9951: * Why object-oriented programming?::  
                   9952: * Object-Oriented Terminology::  
                   9953: * Objects::                     
                   9954: * OOF::                         
                   9955: * Mini-OOF::                    
1.26      crook    9956: * Comparison with other object models::  
                   9957: @end menu
1.20      pazsan   9958: 
1.48      anton    9959: @c ----------------------------------------------------------------
                   9960: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
                   9961: @subsection Why object-oriented programming?
1.26      crook    9962: @cindex object-oriented programming motivation
                   9963: @cindex motivation for object-oriented programming
1.23      crook    9964: 
1.26      crook    9965: Often we have to deal with several data structures (@emph{objects}),
                   9966: that have to be treated similarly in some respects, but differently in
                   9967: others. Graphical objects are the textbook example: circles, triangles,
                   9968: dinosaurs, icons, and others, and we may want to add more during program
                   9969: development. We want to apply some operations to any graphical object,
                   9970: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
                   9971: has to do something different for every kind of object.
                   9972: @comment TODO add some other operations eg perimeter, area
                   9973: @comment and tie in to concrete examples later..
1.23      crook    9974: 
1.26      crook    9975: We could implement @code{draw} as a big @code{CASE}
                   9976: control structure that executes the appropriate code depending on the
                   9977: kind of object to be drawn. This would be not be very elegant, and,
                   9978: moreover, we would have to change @code{draw} every time we add
                   9979: a new kind of graphical object (say, a spaceship).
1.23      crook    9980: 
1.26      crook    9981: What we would rather do is: When defining spaceships, we would tell
                   9982: the system: ``Here's how you @code{draw} a spaceship; you figure
                   9983: out the rest''.
1.23      crook    9984: 
1.26      crook    9985: This is the problem that all systems solve that (rightfully) call
                   9986: themselves object-oriented; the object-oriented packages presented here
                   9987: solve this problem (and not much else).
                   9988: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.23      crook    9989: 
1.48      anton    9990: @c ------------------------------------------------------------------------
1.26      crook    9991: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
1.48      anton    9992: @subsection Object-Oriented Terminology
1.26      crook    9993: @cindex object-oriented terminology
                   9994: @cindex terminology for object-oriented programming
1.23      crook    9995: 
1.26      crook    9996: This section is mainly for reference, so you don't have to understand
                   9997: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
                   9998: short:
1.23      crook    9999: 
1.26      crook    10000: @table @emph
                   10001: @cindex class
                   10002: @item class
                   10003: a data structure definition with some extras.
1.23      crook    10004: 
1.26      crook    10005: @cindex object
                   10006: @item object
                   10007: an instance of the data structure described by the class definition.
1.23      crook    10008: 
1.26      crook    10009: @cindex instance variables
                   10010: @item instance variables
                   10011: fields of the data structure.
1.23      crook    10012: 
1.26      crook    10013: @cindex selector
                   10014: @cindex method selector
                   10015: @cindex virtual function
                   10016: @item selector
                   10017: (or @emph{method selector}) a word (e.g.,
                   10018: @code{draw}) that performs an operation on a variety of data
                   10019: structures (classes). A selector describes @emph{what} operation to
                   10020: perform. In C++ terminology: a (pure) virtual function.
1.23      crook    10021: 
1.26      crook    10022: @cindex method
                   10023: @item method
                   10024: the concrete definition that performs the operation
                   10025: described by the selector for a specific class. A method specifies
                   10026: @emph{how} the operation is performed for a specific class.
1.23      crook    10027: 
1.26      crook    10028: @cindex selector invocation
                   10029: @cindex message send
                   10030: @cindex invoking a selector
                   10031: @item selector invocation
                   10032: a call of a selector. One argument of the call (the TOS (top-of-stack))
                   10033: is used for determining which method is used. In Smalltalk terminology:
                   10034: a message (consisting of the selector and the other arguments) is sent
                   10035: to the object.
1.1       anton    10036: 
1.26      crook    10037: @cindex receiving object
                   10038: @item receiving object
                   10039: the object used for determining the method executed by a selector
                   10040: invocation. In the @file{objects.fs} model, it is the object that is on
                   10041: the TOS when the selector is invoked. (@emph{Receiving} comes from
                   10042: the Smalltalk @emph{message} terminology.)
1.1       anton    10043: 
1.26      crook    10044: @cindex child class
                   10045: @cindex parent class
                   10046: @cindex inheritance
                   10047: @item child class
                   10048: a class that has (@emph{inherits}) all properties (instance variables,
                   10049: selectors, methods) from a @emph{parent class}. In Smalltalk
                   10050: terminology: The subclass inherits from the superclass. In C++
                   10051: terminology: The derived class inherits from the base class.
1.1       anton    10052: 
1.26      crook    10053: @end table
1.21      crook    10054: 
1.26      crook    10055: @c If you wonder about the message sending terminology, it comes from
                   10056: @c a time when each object had it's own task and objects communicated via
                   10057: @c message passing; eventually the Smalltalk developers realized that
                   10058: @c they can do most things through simple (indirect) calls. They kept the
                   10059: @c terminology.
1.1       anton    10060: 
1.48      anton    10061: @c --------------------------------------------------------------
1.26      crook    10062: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
                   10063: @subsection The @file{objects.fs} model
                   10064: @cindex objects
                   10065: @cindex object-oriented programming
1.1       anton    10066: 
1.26      crook    10067: @cindex @file{objects.fs}
                   10068: @cindex @file{oof.fs}
1.1       anton    10069: 
1.37      anton    10070: This section describes the @file{objects.fs} package. This material also
                   10071: has been published in @cite{Yet Another Forth Objects Package} by Anton
                   10072: Ertl and appeared in Forth Dimensions 19(2), pages 37--43
1.47      crook    10073: (@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html}).
1.26      crook    10074: @c McKewan's and Zsoter's packages
1.1       anton    10075: 
1.26      crook    10076: This section assumes that you have read @ref{Structures}.
1.1       anton    10077: 
1.26      crook    10078: The techniques on which this model is based have been used to implement
                   10079: the parser generator, Gray, and have also been used in Gforth for
                   10080: implementing the various flavours of word lists (hashed or not,
                   10081: case-sensitive or not, special-purpose word lists for locals etc.).
1.1       anton    10082: 
                   10083: 
1.26      crook    10084: @menu
                   10085: * Properties of the Objects model::  
                   10086: * Basic Objects Usage::         
1.37      anton    10087: * The Objects base class::      
1.26      crook    10088: * Creating objects::            
                   10089: * Object-Oriented Programming Style::  
                   10090: * Class Binding::               
                   10091: * Method conveniences::         
                   10092: * Classes and Scoping::         
1.37      anton    10093: * Dividing classes::            
1.26      crook    10094: * Object Interfaces::           
                   10095: * Objects Implementation::      
                   10096: * Objects Glossary::            
                   10097: @end menu
1.1       anton    10098: 
1.26      crook    10099: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
                   10100: and Bernd Paysan helped me with the related works section.
1.1       anton    10101: 
1.26      crook    10102: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
                   10103: @subsubsection Properties of the @file{objects.fs} model
                   10104: @cindex @file{objects.fs} properties
1.1       anton    10105: 
1.26      crook    10106: @itemize @bullet
                   10107: @item
                   10108: It is straightforward to pass objects on the stack. Passing
                   10109: selectors on the stack is a little less convenient, but possible.
1.1       anton    10110: 
1.26      crook    10111: @item
                   10112: Objects are just data structures in memory, and are referenced by their
                   10113: address. You can create words for objects with normal defining words
                   10114: like @code{constant}. Likewise, there is no difference between instance
                   10115: variables that contain objects and those that contain other data.
1.1       anton    10116: 
1.26      crook    10117: @item
                   10118: Late binding is efficient and easy to use.
1.21      crook    10119: 
1.26      crook    10120: @item
                   10121: It avoids parsing, and thus avoids problems with state-smartness
                   10122: and reduced extensibility; for convenience there are a few parsing
                   10123: words, but they have non-parsing counterparts. There are also a few
                   10124: defining words that parse. This is hard to avoid, because all standard
                   10125: defining words parse (except @code{:noname}); however, such
                   10126: words are not as bad as many other parsing words, because they are not
                   10127: state-smart.
1.21      crook    10128: 
1.26      crook    10129: @item
                   10130: It does not try to incorporate everything. It does a few things and does
                   10131: them well (IMO). In particular, this model was not designed to support
                   10132: information hiding (although it has features that may help); you can use
                   10133: a separate package for achieving this.
1.21      crook    10134: 
1.26      crook    10135: @item
                   10136: It is layered; you don't have to learn and use all features to use this
1.49      anton    10137: model. Only a few features are necessary (@pxref{Basic Objects Usage},
                   10138: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
1.26      crook    10139: are optional and independent of each other.
1.21      crook    10140: 
1.26      crook    10141: @item
                   10142: An implementation in ANS Forth is available.
1.21      crook    10143: 
1.26      crook    10144: @end itemize
1.21      crook    10145: 
                   10146: 
1.26      crook    10147: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
                   10148: @subsubsection Basic @file{objects.fs} Usage
                   10149: @cindex basic objects usage
                   10150: @cindex objects, basic usage
1.21      crook    10151: 
1.26      crook    10152: You can define a class for graphical objects like this:
1.21      crook    10153: 
1.26      crook    10154: @cindex @code{class} usage
                   10155: @cindex @code{end-class} usage
                   10156: @cindex @code{selector} usage
                   10157: @example
                   10158: object class \ "object" is the parent class
                   10159:   selector draw ( x y graphical -- )
                   10160: end-class graphical
                   10161: @end example
1.21      crook    10162: 
1.26      crook    10163: This code defines a class @code{graphical} with an
                   10164: operation @code{draw}.  We can perform the operation
                   10165: @code{draw} on any @code{graphical} object, e.g.:
1.21      crook    10166: 
1.26      crook    10167: @example
                   10168: 100 100 t-rex draw
                   10169: @end example
1.21      crook    10170: 
1.26      crook    10171: @noindent
                   10172: where @code{t-rex} is a word (say, a constant) that produces a
                   10173: graphical object.
1.21      crook    10174: 
1.29      crook    10175: @comment TODO add a 2nd operation eg perimeter.. and use for
1.26      crook    10176: @comment a concrete example
1.21      crook    10177: 
1.26      crook    10178: @cindex abstract class
                   10179: How do we create a graphical object? With the present definitions,
                   10180: we cannot create a useful graphical object. The class
                   10181: @code{graphical} describes graphical objects in general, but not
                   10182: any concrete graphical object type (C++ users would call it an
                   10183: @emph{abstract class}); e.g., there is no method for the selector
                   10184: @code{draw} in the class @code{graphical}.
1.21      crook    10185: 
1.26      crook    10186: For concrete graphical objects, we define child classes of the
                   10187: class @code{graphical}, e.g.:
1.21      crook    10188: 
1.26      crook    10189: @cindex @code{overrides} usage
                   10190: @cindex @code{field} usage in class definition
                   10191: @example
                   10192: graphical class \ "graphical" is the parent class
                   10193:   cell% field circle-radius
1.21      crook    10194: 
1.26      crook    10195: :noname ( x y circle -- )
                   10196:   circle-radius @@ draw-circle ;
                   10197: overrides draw
1.21      crook    10198: 
1.26      crook    10199: :noname ( n-radius circle -- )
                   10200:   circle-radius ! ;
                   10201: overrides construct
1.21      crook    10202: 
1.26      crook    10203: end-class circle
1.21      crook    10204: @end example
                   10205: 
1.26      crook    10206: Here we define a class @code{circle} as a child of @code{graphical},
                   10207: with field @code{circle-radius} (which behaves just like a field
                   10208: (@pxref{Structures}); it defines (using @code{overrides}) new methods
                   10209: for the selectors @code{draw} and @code{construct} (@code{construct} is
                   10210: defined in @code{object}, the parent class of @code{graphical}).
1.21      crook    10211: 
1.26      crook    10212: Now we can create a circle on the heap (i.e.,
                   10213: @code{allocate}d memory) with:
1.21      crook    10214: 
1.26      crook    10215: @cindex @code{heap-new} usage
1.21      crook    10216: @example
1.26      crook    10217: 50 circle heap-new constant my-circle
                   10218: @end example
1.21      crook    10219: 
1.26      crook    10220: @noindent
                   10221: @code{heap-new} invokes @code{construct}, thus
                   10222: initializing the field @code{circle-radius} with 50. We can draw
                   10223: this new circle at (100,100) with:
1.21      crook    10224: 
1.26      crook    10225: @example
                   10226: 100 100 my-circle draw
1.21      crook    10227: @end example
                   10228: 
1.26      crook    10229: @cindex selector invocation, restrictions
                   10230: @cindex class definition, restrictions
                   10231: Note: You can only invoke a selector if the object on the TOS
                   10232: (the receiving object) belongs to the class where the selector was
                   10233: defined or one of its descendents; e.g., you can invoke
                   10234: @code{draw} only for objects belonging to @code{graphical}
                   10235: or its descendents (e.g., @code{circle}).  Immediately before
                   10236: @code{end-class}, the search order has to be the same as
                   10237: immediately after @code{class}.
1.21      crook    10238: 
1.26      crook    10239: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
                   10240: @subsubsection The @file{object.fs} base class
                   10241: @cindex @code{object} class
1.21      crook    10242: 
1.26      crook    10243: When you define a class, you have to specify a parent class.  So how do
                   10244: you start defining classes? There is one class available from the start:
                   10245: @code{object}. It is ancestor for all classes and so is the
                   10246: only class that has no parent. It has two selectors: @code{construct}
                   10247: and @code{print}.
1.21      crook    10248: 
1.26      crook    10249: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
                   10250: @subsubsection Creating objects
                   10251: @cindex creating objects
                   10252: @cindex object creation
                   10253: @cindex object allocation options
1.21      crook    10254: 
1.26      crook    10255: @cindex @code{heap-new} discussion
                   10256: @cindex @code{dict-new} discussion
                   10257: @cindex @code{construct} discussion
                   10258: You can create and initialize an object of a class on the heap with
                   10259: @code{heap-new} ( ... class -- object ) and in the dictionary
                   10260: (allocation with @code{allot}) with @code{dict-new} (
                   10261: ... class -- object ). Both words invoke @code{construct}, which
                   10262: consumes the stack items indicated by "..." above.
1.21      crook    10263: 
1.26      crook    10264: @cindex @code{init-object} discussion
                   10265: @cindex @code{class-inst-size} discussion
                   10266: If you want to allocate memory for an object yourself, you can get its
                   10267: alignment and size with @code{class-inst-size 2@@} ( class --
                   10268: align size ). Once you have memory for an object, you can initialize
                   10269: it with @code{init-object} ( ... class object -- );
                   10270: @code{construct} does only a part of the necessary work.
1.21      crook    10271: 
1.26      crook    10272: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
                   10273: @subsubsection Object-Oriented Programming Style
                   10274: @cindex object-oriented programming style
1.47      crook    10275: @cindex programming style, object-oriented
1.21      crook    10276: 
1.26      crook    10277: This section is not exhaustive.
1.1       anton    10278: 
1.26      crook    10279: @cindex stack effects of selectors
                   10280: @cindex selectors and stack effects
                   10281: In general, it is a good idea to ensure that all methods for the
                   10282: same selector have the same stack effect: when you invoke a selector,
                   10283: you often have no idea which method will be invoked, so, unless all
                   10284: methods have the same stack effect, you will not know the stack effect
                   10285: of the selector invocation.
1.21      crook    10286: 
1.26      crook    10287: One exception to this rule is methods for the selector
                   10288: @code{construct}. We know which method is invoked, because we
                   10289: specify the class to be constructed at the same place. Actually, I
                   10290: defined @code{construct} as a selector only to give the users a
                   10291: convenient way to specify initialization. The way it is used, a
                   10292: mechanism different from selector invocation would be more natural
                   10293: (but probably would take more code and more space to explain).
1.21      crook    10294: 
1.26      crook    10295: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
                   10296: @subsubsection Class Binding
                   10297: @cindex class binding
                   10298: @cindex early binding
1.21      crook    10299: 
1.26      crook    10300: @cindex late binding
                   10301: Normal selector invocations determine the method at run-time depending
                   10302: on the class of the receiving object. This run-time selection is called
1.29      crook    10303: @i{late binding}.
1.21      crook    10304: 
1.26      crook    10305: Sometimes it's preferable to invoke a different method. For example,
                   10306: you might want to use the simple method for @code{print}ing
                   10307: @code{object}s instead of the possibly long-winded @code{print} method
                   10308: of the receiver class. You can achieve this by replacing the invocation
                   10309: of @code{print} with:
1.21      crook    10310: 
1.26      crook    10311: @cindex @code{[bind]} usage
                   10312: @example
                   10313: [bind] object print
1.21      crook    10314: @end example
                   10315: 
1.26      crook    10316: @noindent
                   10317: in compiled code or:
1.21      crook    10318: 
1.26      crook    10319: @cindex @code{bind} usage
1.21      crook    10320: @example
1.26      crook    10321: bind object print
1.21      crook    10322: @end example
                   10323: 
1.26      crook    10324: @cindex class binding, alternative to
                   10325: @noindent
                   10326: in interpreted code. Alternatively, you can define the method with a
                   10327: name (e.g., @code{print-object}), and then invoke it through the
                   10328: name. Class binding is just a (often more convenient) way to achieve
                   10329: the same effect; it avoids name clutter and allows you to invoke
                   10330: methods directly without naming them first.
                   10331: 
                   10332: @cindex superclass binding
                   10333: @cindex parent class binding
                   10334: A frequent use of class binding is this: When we define a method
                   10335: for a selector, we often want the method to do what the selector does
                   10336: in the parent class, and a little more. There is a special word for
                   10337: this purpose: @code{[parent]}; @code{[parent]
                   10338: @emph{selector}} is equivalent to @code{[bind] @emph{parent
                   10339: selector}}, where @code{@emph{parent}} is the parent
                   10340: class of the current class. E.g., a method definition might look like:
1.21      crook    10341: 
1.26      crook    10342: @cindex @code{[parent]} usage
1.21      crook    10343: @example
1.26      crook    10344: :noname
                   10345:   dup [parent] foo \ do parent's foo on the receiving object
                   10346:   ... \ do some more
                   10347: ; overrides foo
1.21      crook    10348: @end example
                   10349: 
1.26      crook    10350: @cindex class binding as optimization
                   10351: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
                   10352: March 1997), Andrew McKewan presents class binding as an optimization
                   10353: technique. I recommend not using it for this purpose unless you are in
                   10354: an emergency. Late binding is pretty fast with this model anyway, so the
                   10355: benefit of using class binding is small; the cost of using class binding
                   10356: where it is not appropriate is reduced maintainability.
1.21      crook    10357: 
1.26      crook    10358: While we are at programming style questions: You should bind
                   10359: selectors only to ancestor classes of the receiving object. E.g., say,
                   10360: you know that the receiving object is of class @code{foo} or its
                   10361: descendents; then you should bind only to @code{foo} and its
                   10362: ancestors.
1.21      crook    10363: 
1.26      crook    10364: @node Method conveniences, Classes and Scoping, Class Binding, Objects
                   10365: @subsubsection Method conveniences
                   10366: @cindex method conveniences
1.1       anton    10367: 
1.26      crook    10368: In a method you usually access the receiving object pretty often.  If
                   10369: you define the method as a plain colon definition (e.g., with
                   10370: @code{:noname}), you may have to do a lot of stack
                   10371: gymnastics. To avoid this, you can define the method with @code{m:
                   10372: ... ;m}. E.g., you could define the method for
                   10373: @code{draw}ing a @code{circle} with
1.20      pazsan   10374: 
1.26      crook    10375: @cindex @code{this} usage
                   10376: @cindex @code{m:} usage
                   10377: @cindex @code{;m} usage
                   10378: @example
                   10379: m: ( x y circle -- )
                   10380:   ( x y ) this circle-radius @@ draw-circle ;m
                   10381: @end example
1.20      pazsan   10382: 
1.26      crook    10383: @cindex @code{exit} in @code{m: ... ;m}
                   10384: @cindex @code{exitm} discussion
                   10385: @cindex @code{catch} in @code{m: ... ;m}
                   10386: When this method is executed, the receiver object is removed from the
                   10387: stack; you can access it with @code{this} (admittedly, in this
                   10388: example the use of @code{m: ... ;m} offers no advantage). Note
                   10389: that I specify the stack effect for the whole method (i.e. including
                   10390: the receiver object), not just for the code between @code{m:}
                   10391: and @code{;m}. You cannot use @code{exit} in
                   10392: @code{m:...;m}; instead, use
                   10393: @code{exitm}.@footnote{Moreover, for any word that calls
                   10394: @code{catch} and was defined before loading
                   10395: @code{objects.fs}, you have to redefine it like I redefined
                   10396: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.20      pazsan   10397: 
1.26      crook    10398: @cindex @code{inst-var} usage
                   10399: You will frequently use sequences of the form @code{this
                   10400: @emph{field}} (in the example above: @code{this
                   10401: circle-radius}). If you use the field only in this way, you can
                   10402: define it with @code{inst-var} and eliminate the
                   10403: @code{this} before the field name. E.g., the @code{circle}
                   10404: class above could also be defined with:
1.20      pazsan   10405: 
1.26      crook    10406: @example
                   10407: graphical class
                   10408:   cell% inst-var radius
1.20      pazsan   10409: 
1.26      crook    10410: m: ( x y circle -- )
                   10411:   radius @@ draw-circle ;m
                   10412: overrides draw
1.20      pazsan   10413: 
1.26      crook    10414: m: ( n-radius circle -- )
                   10415:   radius ! ;m
                   10416: overrides construct
1.12      anton    10417: 
1.26      crook    10418: end-class circle
                   10419: @end example
1.12      anton    10420: 
1.26      crook    10421: @code{radius} can only be used in @code{circle} and its
                   10422: descendent classes and inside @code{m:...;m}.
1.12      anton    10423: 
1.26      crook    10424: @cindex @code{inst-value} usage
                   10425: You can also define fields with @code{inst-value}, which is
                   10426: to @code{inst-var} what @code{value} is to
                   10427: @code{variable}.  You can change the value of such a field with
                   10428: @code{[to-inst]}.  E.g., we could also define the class
                   10429: @code{circle} like this:
1.12      anton    10430: 
1.26      crook    10431: @example
                   10432: graphical class
                   10433:   inst-value radius
1.12      anton    10434: 
1.26      crook    10435: m: ( x y circle -- )
                   10436:   radius draw-circle ;m
                   10437: overrides draw
1.12      anton    10438: 
1.26      crook    10439: m: ( n-radius circle -- )
                   10440:   [to-inst] radius ;m
                   10441: overrides construct
1.21      crook    10442: 
1.26      crook    10443: end-class circle
1.12      anton    10444: @end example
                   10445: 
1.38      anton    10446: Finally, you can define named methods with @code{:m}.  One use of this
                   10447: feature is the definition of words that occur only in one class and are
                   10448: not intended to be overridden, but which still need method context
                   10449: (e.g., for accessing @code{inst-var}s).  Another use is for methods that
                   10450: would be bound frequently, if defined anonymously.
                   10451: 
1.12      anton    10452: 
1.37      anton    10453: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
1.26      crook    10454: @subsubsection Classes and Scoping
                   10455: @cindex classes and scoping
                   10456: @cindex scoping and classes
1.12      anton    10457: 
1.26      crook    10458: Inheritance is frequent, unlike structure extension. This exacerbates
                   10459: the problem with the field name convention (@pxref{Structure Naming
                   10460: Convention}): One always has to remember in which class the field was
                   10461: originally defined; changing a part of the class structure would require
                   10462: changes for renaming in otherwise unaffected code.
1.12      anton    10463: 
1.26      crook    10464: @cindex @code{inst-var} visibility
                   10465: @cindex @code{inst-value} visibility
                   10466: To solve this problem, I added a scoping mechanism (which was not in my
                   10467: original charter): A field defined with @code{inst-var} (or
                   10468: @code{inst-value}) is visible only in the class where it is defined and in
                   10469: the descendent classes of this class.  Using such fields only makes
                   10470: sense in @code{m:}-defined methods in these classes anyway.
1.12      anton    10471: 
1.26      crook    10472: This scoping mechanism allows us to use the unadorned field name,
                   10473: because name clashes with unrelated words become much less likely.
1.12      anton    10474: 
1.26      crook    10475: @cindex @code{protected} discussion
                   10476: @cindex @code{private} discussion
                   10477: Once we have this mechanism, we can also use it for controlling the
                   10478: visibility of other words: All words defined after
                   10479: @code{protected} are visible only in the current class and its
                   10480: descendents. @code{public} restores the compilation
                   10481: (i.e. @code{current}) word list that was in effect before. If you
                   10482: have several @code{protected}s without an intervening
                   10483: @code{public} or @code{set-current}, @code{public}
                   10484: will restore the compilation word list in effect before the first of
                   10485: these @code{protected}s.
1.12      anton    10486: 
1.37      anton    10487: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
                   10488: @subsubsection Dividing classes
                   10489: @cindex Dividing classes
                   10490: @cindex @code{methods}...@code{end-methods}
                   10491: 
                   10492: You may want to do the definition of methods separate from the
                   10493: definition of the class, its selectors, fields, and instance variables,
                   10494: i.e., separate the implementation from the definition.  You can do this
                   10495: in the following way:
                   10496: 
                   10497: @example
                   10498: graphical class
                   10499:   inst-value radius
                   10500: end-class circle
                   10501: 
                   10502: ... \ do some other stuff
                   10503: 
                   10504: circle methods \ now we are ready
                   10505: 
                   10506: m: ( x y circle -- )
                   10507:   radius draw-circle ;m
                   10508: overrides draw
                   10509: 
                   10510: m: ( n-radius circle -- )
                   10511:   [to-inst] radius ;m
                   10512: overrides construct
                   10513: 
                   10514: end-methods
                   10515: @end example
                   10516: 
                   10517: You can use several @code{methods}...@code{end-methods} sections.  The
                   10518: only things you can do to the class in these sections are: defining
                   10519: methods, and overriding the class's selectors.  You must not define new
                   10520: selectors or fields.
                   10521: 
                   10522: Note that you often have to override a selector before using it.  In
                   10523: particular, you usually have to override @code{construct} with a new
                   10524: method before you can invoke @code{heap-new} and friends.  E.g., you
                   10525: must not create a circle before the @code{overrides construct} sequence
                   10526: in the example above.
                   10527: 
                   10528: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
1.26      crook    10529: @subsubsection Object Interfaces
                   10530: @cindex object interfaces
                   10531: @cindex interfaces for objects
1.12      anton    10532: 
1.26      crook    10533: In this model you can only call selectors defined in the class of the
                   10534: receiving objects or in one of its ancestors. If you call a selector
                   10535: with a receiving object that is not in one of these classes, the
                   10536: result is undefined; if you are lucky, the program crashes
                   10537: immediately.
1.12      anton    10538: 
1.26      crook    10539: @cindex selectors common to hardly-related classes
                   10540: Now consider the case when you want to have a selector (or several)
                   10541: available in two classes: You would have to add the selector to a
                   10542: common ancestor class, in the worst case to @code{object}. You
                   10543: may not want to do this, e.g., because someone else is responsible for
                   10544: this ancestor class.
1.12      anton    10545: 
1.26      crook    10546: The solution for this problem is interfaces. An interface is a
                   10547: collection of selectors. If a class implements an interface, the
                   10548: selectors become available to the class and its descendents. A class
                   10549: can implement an unlimited number of interfaces. For the problem
                   10550: discussed above, we would define an interface for the selector(s), and
                   10551: both classes would implement the interface.
1.12      anton    10552: 
1.26      crook    10553: As an example, consider an interface @code{storage} for
                   10554: writing objects to disk and getting them back, and a class
                   10555: @code{foo} that implements it. The code would look like this:
1.12      anton    10556: 
1.26      crook    10557: @cindex @code{interface} usage
                   10558: @cindex @code{end-interface} usage
                   10559: @cindex @code{implementation} usage
                   10560: @example
                   10561: interface
                   10562:   selector write ( file object -- )
                   10563:   selector read1 ( file object -- )
                   10564: end-interface storage
1.12      anton    10565: 
1.26      crook    10566: bar class
                   10567:   storage implementation
1.12      anton    10568: 
1.26      crook    10569: ... overrides write
1.37      anton    10570: ... overrides read1
1.26      crook    10571: ...
                   10572: end-class foo
1.12      anton    10573: @end example
                   10574: 
1.26      crook    10575: @noindent
1.29      crook    10576: (I would add a word @code{read} @i{( file -- object )} that uses
1.26      crook    10577: @code{read1} internally, but that's beyond the point illustrated
                   10578: here.)
1.12      anton    10579: 
1.26      crook    10580: Note that you cannot use @code{protected} in an interface; and
                   10581: of course you cannot define fields.
1.12      anton    10582: 
1.26      crook    10583: In the Neon model, all selectors are available for all classes;
                   10584: therefore it does not need interfaces. The price you pay in this model
                   10585: is slower late binding, and therefore, added complexity to avoid late
                   10586: binding.
1.12      anton    10587: 
1.26      crook    10588: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
                   10589: @subsubsection @file{objects.fs} Implementation
                   10590: @cindex @file{objects.fs} implementation
1.12      anton    10591: 
1.26      crook    10592: @cindex @code{object-map} discussion
                   10593: An object is a piece of memory, like one of the data structures
                   10594: described with @code{struct...end-struct}. It has a field
                   10595: @code{object-map} that points to the method map for the object's
                   10596: class.
1.12      anton    10597: 
1.26      crook    10598: @cindex method map
                   10599: @cindex virtual function table
                   10600: The @emph{method map}@footnote{This is Self terminology; in C++
                   10601: terminology: virtual function table.} is an array that contains the
1.29      crook    10602: execution tokens (@i{xt}s) of the methods for the object's class. Each
1.26      crook    10603: selector contains an offset into a method map.
1.12      anton    10604: 
1.26      crook    10605: @cindex @code{selector} implementation, class
                   10606: @code{selector} is a defining word that uses
                   10607: @code{CREATE} and @code{DOES>}. The body of the
1.44      crook    10608: selector contains the offset; the @code{DOES>} action for a
1.26      crook    10609: class selector is, basically:
1.21      crook    10610: 
1.26      crook    10611: @example
                   10612: ( object addr ) @@ over object-map @@ + @@ execute
                   10613: @end example
1.12      anton    10614: 
1.26      crook    10615: Since @code{object-map} is the first field of the object, it
                   10616: does not generate any code. As you can see, calling a selector has a
                   10617: small, constant cost.
1.12      anton    10618: 
1.26      crook    10619: @cindex @code{current-interface} discussion
                   10620: @cindex class implementation and representation
                   10621: A class is basically a @code{struct} combined with a method
                   10622: map. During the class definition the alignment and size of the class
                   10623: are passed on the stack, just as with @code{struct}s, so
                   10624: @code{field} can also be used for defining class
                   10625: fields. However, passing more items on the stack would be
                   10626: inconvenient, so @code{class} builds a data structure in memory,
                   10627: which is accessed through the variable
                   10628: @code{current-interface}. After its definition is complete, the
                   10629: class is represented on the stack by a pointer (e.g., as parameter for
                   10630: a child class definition).
1.1       anton    10631: 
1.26      crook    10632: A new class starts off with the alignment and size of its parent,
                   10633: and a copy of the parent's method map. Defining new fields extends the
                   10634: size and alignment; likewise, defining new selectors extends the
1.29      crook    10635: method map. @code{overrides} just stores a new @i{xt} in the method
1.26      crook    10636: map at the offset given by the selector.
1.20      pazsan   10637: 
1.26      crook    10638: @cindex class binding, implementation
1.29      crook    10639: Class binding just gets the @i{xt} at the offset given by the selector
1.26      crook    10640: from the class's method map and @code{compile,}s (in the case of
                   10641: @code{[bind]}) it.
1.21      crook    10642: 
1.26      crook    10643: @cindex @code{this} implementation
                   10644: @cindex @code{catch} and @code{this}
                   10645: @cindex @code{this} and @code{catch}
                   10646: I implemented @code{this} as a @code{value}. At the
                   10647: start of an @code{m:...;m} method the old @code{this} is
                   10648: stored to the return stack and restored at the end; and the object on
                   10649: the TOS is stored @code{TO this}. This technique has one
                   10650: disadvantage: If the user does not leave the method via
                   10651: @code{;m}, but via @code{throw} or @code{exit},
                   10652: @code{this} is not restored (and @code{exit} may
                   10653: crash). To deal with the @code{throw} problem, I have redefined
                   10654: @code{catch} to save and restore @code{this}; the same
                   10655: should be done with any word that can catch an exception. As for
                   10656: @code{exit}, I simply forbid it (as a replacement, there is
                   10657: @code{exitm}).
1.21      crook    10658: 
1.26      crook    10659: @cindex @code{inst-var} implementation
                   10660: @code{inst-var} is just the same as @code{field}, with
                   10661: a different @code{DOES>} action:
                   10662: @example
                   10663: @@ this +
                   10664: @end example
                   10665: Similar for @code{inst-value}.
1.21      crook    10666: 
1.26      crook    10667: @cindex class scoping implementation
                   10668: Each class also has a word list that contains the words defined with
                   10669: @code{inst-var} and @code{inst-value}, and its protected
                   10670: words. It also has a pointer to its parent. @code{class} pushes
                   10671: the word lists of the class and all its ancestors onto the search order stack,
                   10672: and @code{end-class} drops them.
1.21      crook    10673: 
1.26      crook    10674: @cindex interface implementation
                   10675: An interface is like a class without fields, parent and protected
                   10676: words; i.e., it just has a method map. If a class implements an
                   10677: interface, its method map contains a pointer to the method map of the
                   10678: interface. The positive offsets in the map are reserved for class
                   10679: methods, therefore interface map pointers have negative
                   10680: offsets. Interfaces have offsets that are unique throughout the
                   10681: system, unlike class selectors, whose offsets are only unique for the
                   10682: classes where the selector is available (invokable).
1.21      crook    10683: 
1.26      crook    10684: This structure means that interface selectors have to perform one
                   10685: indirection more than class selectors to find their method. Their body
                   10686: contains the interface map pointer offset in the class method map, and
                   10687: the method offset in the interface method map. The
                   10688: @code{does>} action for an interface selector is, basically:
1.21      crook    10689: 
                   10690: @example
1.26      crook    10691: ( object selector-body )
                   10692: 2dup selector-interface @@ ( object selector-body object interface-offset )
                   10693: swap object-map @@ + @@ ( object selector-body map )
                   10694: swap selector-offset @@ + @@ execute
1.21      crook    10695: @end example
                   10696: 
1.26      crook    10697: where @code{object-map} and @code{selector-offset} are
                   10698: first fields and generate no code.
                   10699: 
                   10700: As a concrete example, consider the following code:
1.21      crook    10701: 
1.26      crook    10702: @example
                   10703: interface
                   10704:   selector if1sel1
                   10705:   selector if1sel2
                   10706: end-interface if1
1.21      crook    10707: 
1.26      crook    10708: object class
                   10709:   if1 implementation
                   10710:   selector cl1sel1
                   10711:   cell% inst-var cl1iv1
1.21      crook    10712: 
1.26      crook    10713: ' m1 overrides construct
                   10714: ' m2 overrides if1sel1
                   10715: ' m3 overrides if1sel2
                   10716: ' m4 overrides cl1sel2
                   10717: end-class cl1
1.21      crook    10718: 
1.26      crook    10719: create obj1 object dict-new drop
                   10720: create obj2 cl1    dict-new drop
                   10721: @end example
1.21      crook    10722: 
1.26      crook    10723: The data structure created by this code (including the data structure
                   10724: for @code{object}) is shown in the <a
                   10725: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
1.29      crook    10726: @comment TODO add this diagram..
1.21      crook    10727: 
1.26      crook    10728: @node Objects Glossary,  , Objects Implementation, Objects
                   10729: @subsubsection @file{objects.fs} Glossary
                   10730: @cindex @file{objects.fs} Glossary
1.21      crook    10731: 
1.44      crook    10732: 
1.26      crook    10733: doc---objects-bind
                   10734: doc---objects-<bind>
                   10735: doc---objects-bind'
                   10736: doc---objects-[bind]
                   10737: doc---objects-class
                   10738: doc---objects-class->map
                   10739: doc---objects-class-inst-size
                   10740: doc---objects-class-override!
                   10741: doc---objects-construct
                   10742: doc---objects-current'
                   10743: doc---objects-[current]
                   10744: doc---objects-current-interface
                   10745: doc---objects-dict-new
                   10746: doc---objects-drop-order
                   10747: doc---objects-end-class
                   10748: doc---objects-end-class-noname
                   10749: doc---objects-end-interface
                   10750: doc---objects-end-interface-noname
1.37      anton    10751: doc---objects-end-methods
1.26      crook    10752: doc---objects-exitm
                   10753: doc---objects-heap-new
                   10754: doc---objects-implementation
                   10755: doc---objects-init-object
                   10756: doc---objects-inst-value
                   10757: doc---objects-inst-var
                   10758: doc---objects-interface
1.38      anton    10759: doc---objects-m:
                   10760: doc---objects-:m
1.26      crook    10761: doc---objects-;m
                   10762: doc---objects-method
1.37      anton    10763: doc---objects-methods
1.26      crook    10764: doc---objects-object
                   10765: doc---objects-overrides
                   10766: doc---objects-[parent]
                   10767: doc---objects-print
                   10768: doc---objects-protected
                   10769: doc---objects-public
                   10770: doc---objects-push-order
                   10771: doc---objects-selector
                   10772: doc---objects-this
                   10773: doc---objects-<to-inst>
                   10774: doc---objects-[to-inst]
                   10775: doc---objects-to-this
                   10776: doc---objects-xt-new
1.21      crook    10777: 
1.44      crook    10778: 
1.26      crook    10779: @c -------------------------------------------------------------
                   10780: @node OOF, Mini-OOF, Objects, Object-oriented Forth
                   10781: @subsection The @file{oof.fs} model
                   10782: @cindex oof
                   10783: @cindex object-oriented programming
1.21      crook    10784: 
1.26      crook    10785: @cindex @file{objects.fs}
                   10786: @cindex @file{oof.fs}
1.21      crook    10787: 
1.26      crook    10788: This section describes the @file{oof.fs} package.
1.21      crook    10789: 
1.26      crook    10790: The package described in this section has been used in bigFORTH since 1991, and
                   10791: used for two large applications: a chromatographic system used to
                   10792: create new medicaments, and a graphic user interface library (MINOS).
1.21      crook    10793: 
1.26      crook    10794: You can find a description (in German) of @file{oof.fs} in @cite{Object
                   10795: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
                   10796: 10(2), 1994.
1.21      crook    10797: 
1.26      crook    10798: @menu
                   10799: * Properties of the OOF model::
                   10800: * Basic OOF Usage::
                   10801: * The OOF base class::
                   10802: * Class Declaration::
                   10803: * Class Implementation::
                   10804: @end menu
1.21      crook    10805: 
1.26      crook    10806: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
                   10807: @subsubsection Properties of the @file{oof.fs} model
                   10808: @cindex @file{oof.fs} properties
1.21      crook    10809: 
1.26      crook    10810: @itemize @bullet
                   10811: @item
                   10812: This model combines object oriented programming with information
                   10813: hiding. It helps you writing large application, where scoping is
                   10814: necessary, because it provides class-oriented scoping.
1.21      crook    10815: 
1.26      crook    10816: @item
                   10817: Named objects, object pointers, and object arrays can be created,
                   10818: selector invocation uses the ``object selector'' syntax. Selector invocation
                   10819: to objects and/or selectors on the stack is a bit less convenient, but
                   10820: possible.
1.21      crook    10821: 
1.26      crook    10822: @item
                   10823: Selector invocation and instance variable usage of the active object is
                   10824: straightforward, since both make use of the active object.
1.21      crook    10825: 
1.26      crook    10826: @item
                   10827: Late binding is efficient and easy to use.
1.21      crook    10828: 
1.26      crook    10829: @item
                   10830: State-smart objects parse selectors. However, extensibility is provided
                   10831: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.21      crook    10832: 
                   10833: @item
1.26      crook    10834: An implementation in ANS Forth is available.
                   10835: 
1.21      crook    10836: @end itemize
                   10837: 
                   10838: 
1.26      crook    10839: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
                   10840: @subsubsection Basic @file{oof.fs} Usage
                   10841: @cindex @file{oof.fs} usage
                   10842: 
                   10843: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.21      crook    10844: 
1.26      crook    10845: You can define a class for graphical objects like this:
1.21      crook    10846: 
1.26      crook    10847: @cindex @code{class} usage
                   10848: @cindex @code{class;} usage
                   10849: @cindex @code{method} usage
                   10850: @example
                   10851: object class graphical \ "object" is the parent class
                   10852:   method draw ( x y graphical -- )
                   10853: class;
                   10854: @end example
1.21      crook    10855: 
1.26      crook    10856: This code defines a class @code{graphical} with an
                   10857: operation @code{draw}.  We can perform the operation
                   10858: @code{draw} on any @code{graphical} object, e.g.:
1.21      crook    10859: 
1.26      crook    10860: @example
                   10861: 100 100 t-rex draw
                   10862: @end example
1.21      crook    10863: 
1.26      crook    10864: @noindent
                   10865: where @code{t-rex} is an object or object pointer, created with e.g.
                   10866: @code{graphical : t-rex}.
1.21      crook    10867: 
1.26      crook    10868: @cindex abstract class
                   10869: How do we create a graphical object? With the present definitions,
                   10870: we cannot create a useful graphical object. The class
                   10871: @code{graphical} describes graphical objects in general, but not
                   10872: any concrete graphical object type (C++ users would call it an
                   10873: @emph{abstract class}); e.g., there is no method for the selector
                   10874: @code{draw} in the class @code{graphical}.
1.21      crook    10875: 
1.26      crook    10876: For concrete graphical objects, we define child classes of the
                   10877: class @code{graphical}, e.g.:
1.21      crook    10878: 
                   10879: @example
1.26      crook    10880: graphical class circle \ "graphical" is the parent class
                   10881:   cell var circle-radius
                   10882: how:
                   10883:   : draw ( x y -- )
                   10884:     circle-radius @@ draw-circle ;
                   10885: 
                   10886:   : init ( n-radius -- (
                   10887:     circle-radius ! ;
                   10888: class;
                   10889: @end example
                   10890: 
                   10891: Here we define a class @code{circle} as a child of @code{graphical},
                   10892: with a field @code{circle-radius}; it defines new methods for the
                   10893: selectors @code{draw} and @code{init} (@code{init} is defined in
                   10894: @code{object}, the parent class of @code{graphical}).
1.21      crook    10895: 
1.26      crook    10896: Now we can create a circle in the dictionary with:
1.21      crook    10897: 
1.26      crook    10898: @example
                   10899: 50 circle : my-circle
1.21      crook    10900: @end example
                   10901: 
1.26      crook    10902: @noindent
                   10903: @code{:} invokes @code{init}, thus initializing the field
                   10904: @code{circle-radius} with 50. We can draw this new circle at (100,100)
                   10905: with:
1.21      crook    10906: 
                   10907: @example
1.26      crook    10908: 100 100 my-circle draw
1.21      crook    10909: @end example
                   10910: 
1.26      crook    10911: @cindex selector invocation, restrictions
                   10912: @cindex class definition, restrictions
                   10913: Note: You can only invoke a selector if the receiving object belongs to
                   10914: the class where the selector was defined or one of its descendents;
                   10915: e.g., you can invoke @code{draw} only for objects belonging to
                   10916: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
                   10917: mechanism will check if you try to invoke a selector that is not
                   10918: defined in this class hierarchy, so you'll get an error at compilation
                   10919: time.
                   10920: 
                   10921: 
                   10922: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
                   10923: @subsubsection The @file{oof.fs} base class
                   10924: @cindex @file{oof.fs} base class
                   10925: 
                   10926: When you define a class, you have to specify a parent class.  So how do
                   10927: you start defining classes? There is one class available from the start:
                   10928: @code{object}. You have to use it as ancestor for all classes. It is the
                   10929: only class that has no parent. Classes are also objects, except that
                   10930: they don't have instance variables; class manipulation such as
                   10931: inheritance or changing definitions of a class is handled through
                   10932: selectors of the class @code{object}.
                   10933: 
                   10934: @code{object} provides a number of selectors:
                   10935: 
1.21      crook    10936: @itemize @bullet
                   10937: @item
1.26      crook    10938: @code{class} for subclassing, @code{definitions} to add definitions
                   10939: later on, and @code{class?} to get type informations (is the class a
                   10940: subclass of the class passed on the stack?).
1.44      crook    10941: 
1.26      crook    10942: doc---object-class
                   10943: doc---object-definitions
                   10944: doc---object-class?
                   10945: 
1.44      crook    10946: 
1.21      crook    10947: @item
1.26      crook    10948: @code{init} and @code{dispose} as constructor and destructor of the
                   10949: object. @code{init} is invocated after the object's memory is allocated,
                   10950: while @code{dispose} also handles deallocation. Thus if you redefine
                   10951: @code{dispose}, you have to call the parent's dispose with @code{super
                   10952: dispose}, too.
1.44      crook    10953: 
1.26      crook    10954: doc---object-init
                   10955: doc---object-dispose
                   10956: 
1.44      crook    10957: 
1.21      crook    10958: @item
1.26      crook    10959: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
                   10960: @code{[]} to create named and unnamed objects and object arrays or
                   10961: object pointers.
1.44      crook    10962: 
1.26      crook    10963: doc---object-new
                   10964: doc---object-new[]
                   10965: doc---object-:
                   10966: doc---object-ptr
                   10967: doc---object-asptr
                   10968: doc---object-[]
1.21      crook    10969: 
1.44      crook    10970: 
1.26      crook    10971: @item
                   10972: @code{::} and @code{super} for explicit scoping. You should use explicit
                   10973: scoping only for super classes or classes with the same set of instance
                   10974: variables. Explicitly-scoped selectors use early binding.
1.44      crook    10975: 
1.26      crook    10976: doc---object-::
                   10977: doc---object-super
1.21      crook    10978: 
1.44      crook    10979: 
1.26      crook    10980: @item
                   10981: @code{self} to get the address of the object
1.44      crook    10982: 
1.26      crook    10983: doc---object-self
1.21      crook    10984: 
1.44      crook    10985: 
1.21      crook    10986: @item
1.26      crook    10987: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
                   10988: pointers and instance defers.
1.44      crook    10989: 
1.26      crook    10990: doc---object-bind
                   10991: doc---object-bound
                   10992: doc---object-link
                   10993: doc---object-is
                   10994: 
1.44      crook    10995: 
1.21      crook    10996: @item
1.26      crook    10997: @code{'} to obtain selector tokens, @code{send} to invocate selectors
                   10998: form the stack, and @code{postpone} to generate selector invocation code.
1.44      crook    10999: 
1.26      crook    11000: doc---object-'
                   11001: doc---object-postpone
                   11002: 
1.44      crook    11003: 
1.21      crook    11004: @item
1.26      crook    11005: @code{with} and @code{endwith} to select the active object from the
                   11006: stack, and enable its scope. Using @code{with} and @code{endwith}
                   11007: also allows you to create code using selector @code{postpone} without being
                   11008: trapped by the state-smart objects.
1.44      crook    11009: 
1.26      crook    11010: doc---object-with
                   11011: doc---object-endwith
                   11012: 
1.44      crook    11013: 
1.21      crook    11014: @end itemize
                   11015: 
1.26      crook    11016: @node Class Declaration, Class Implementation, The OOF base class, OOF
                   11017: @subsubsection Class Declaration
                   11018: @cindex class declaration
                   11019: 
                   11020: @itemize @bullet
                   11021: @item
                   11022: Instance variables
1.44      crook    11023: 
1.26      crook    11024: doc---oof-var
1.21      crook    11025: 
1.44      crook    11026: 
1.26      crook    11027: @item
                   11028: Object pointers
1.44      crook    11029: 
1.26      crook    11030: doc---oof-ptr
                   11031: doc---oof-asptr
1.21      crook    11032: 
1.44      crook    11033: 
1.26      crook    11034: @item
                   11035: Instance defers
1.44      crook    11036: 
1.26      crook    11037: doc---oof-defer
1.21      crook    11038: 
1.44      crook    11039: 
1.26      crook    11040: @item
                   11041: Method selectors
1.44      crook    11042: 
1.26      crook    11043: doc---oof-early
                   11044: doc---oof-method
1.21      crook    11045: 
1.44      crook    11046: 
1.26      crook    11047: @item
                   11048: Class-wide variables
1.44      crook    11049: 
1.26      crook    11050: doc---oof-static
1.21      crook    11051: 
1.44      crook    11052: 
1.26      crook    11053: @item
                   11054: End declaration
1.44      crook    11055: 
1.26      crook    11056: doc---oof-how:
                   11057: doc---oof-class;
1.21      crook    11058: 
1.44      crook    11059: 
1.26      crook    11060: @end itemize
1.21      crook    11061: 
1.26      crook    11062: @c -------------------------------------------------------------
                   11063: @node Class Implementation,  , Class Declaration, OOF
                   11064: @subsubsection Class Implementation
                   11065: @cindex class implementation
1.21      crook    11066: 
1.26      crook    11067: @c -------------------------------------------------------------
                   11068: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
                   11069: @subsection The @file{mini-oof.fs} model
                   11070: @cindex mini-oof
1.1       anton    11071: 
1.26      crook    11072: Gforth's third object oriented Forth package is a 12-liner. It uses a
                   11073: mixture of the @file{object.fs} and the @file{oof.fs} syntax,
                   11074: and reduces to the bare minimum of features. This is based on a posting
                   11075: of Bernd Paysan in comp.arch.
1.1       anton    11076: 
                   11077: @menu
1.48      anton    11078: * Basic Mini-OOF Usage::        
                   11079: * Mini-OOF Example::            
                   11080: * Mini-OOF Implementation::     
                   11081: * Comparison with other object models::  
1.1       anton    11082: @end menu
                   11083: 
1.26      crook    11084: @c -------------------------------------------------------------
1.48      anton    11085: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
1.26      crook    11086: @subsubsection Basic @file{mini-oof.fs} Usage
                   11087: @cindex mini-oof usage
1.1       anton    11088: 
1.28      crook    11089: There is a base class (@code{class}, which allocates one cell for the
                   11090: object pointer) plus seven other words: to define a method, a variable,
                   11091: a class; to end a class, to resolve binding, to allocate an object and
                   11092: to compile a class method.
1.26      crook    11093: @comment TODO better description of the last one
1.1       anton    11094: 
1.44      crook    11095: 
1.26      crook    11096: doc-object
                   11097: doc-method
                   11098: doc-var
                   11099: doc-class
                   11100: doc-end-class
                   11101: doc-defines
                   11102: doc-new
                   11103: doc-::
1.1       anton    11104: 
1.21      crook    11105: 
1.44      crook    11106: 
1.26      crook    11107: @c -------------------------------------------------------------
                   11108: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
                   11109: @subsubsection Mini-OOF Example
                   11110: @cindex mini-oof example
1.21      crook    11111: 
1.26      crook    11112: A short example shows how to use this package. This example, in slightly
                   11113: extended form, is supplied as @file{moof-exm.fs}
1.29      crook    11114: @comment TODO could flesh this out with some comments from the Forthwrite article
1.21      crook    11115: 
1.26      crook    11116: @example
                   11117: object class
                   11118:   method init
                   11119:   method draw
                   11120: end-class graphical
                   11121: @end example
1.21      crook    11122: 
1.26      crook    11123: This code defines a class @code{graphical} with an
                   11124: operation @code{draw}.  We can perform the operation
                   11125: @code{draw} on any @code{graphical} object, e.g.:
1.1       anton    11126: 
1.26      crook    11127: @example
                   11128: 100 100 t-rex draw
                   11129: @end example
1.1       anton    11130: 
1.26      crook    11131: where @code{t-rex} is an object or object pointer, created with e.g.
                   11132: @code{graphical new Constant t-rex}.
1.1       anton    11133: 
1.26      crook    11134: For concrete graphical objects, we define child classes of the
                   11135: class @code{graphical}, e.g.:
1.21      crook    11136: 
                   11137: @example
1.26      crook    11138: graphical class
                   11139:   cell var circle-radius
                   11140: end-class circle \ "graphical" is the parent class
1.21      crook    11141: 
1.26      crook    11142: :noname ( x y -- )
                   11143:   circle-radius @@ draw-circle ; circle defines draw
                   11144: :noname ( r -- )
                   11145:   circle-radius ! ; circle defines init
1.21      crook    11146: @end example
                   11147: 
1.26      crook    11148: There is no implicit init method, so we have to define one. The creation
                   11149: code of the object now has to call init explicitely.
1.21      crook    11150: 
1.26      crook    11151: @example
                   11152: circle new Constant my-circle
                   11153: 50 my-circle init
                   11154: @end example
1.21      crook    11155: 
1.26      crook    11156: It is also possible to add a function to create named objects with
                   11157: automatic call of @code{init}, given that all objects have @code{init}
                   11158: on the same place:
1.1       anton    11159: 
                   11160: @example
1.26      crook    11161: : new: ( .. o "name" -- )
                   11162:     new dup Constant init ;
                   11163: 80 circle new: large-circle
1.1       anton    11164: @end example
                   11165: 
1.26      crook    11166: We can draw this new circle at (100,100) with:
1.1       anton    11167: 
                   11168: @example
1.26      crook    11169: 100 100 my-circle draw
1.1       anton    11170: @end example
                   11171: 
1.48      anton    11172: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
1.26      crook    11173: @subsubsection @file{mini-oof.fs} Implementation
1.1       anton    11174: 
1.26      crook    11175: Object-oriented systems with late binding typically use a
                   11176: ``vtable''-approach: the first variable in each object is a pointer to a
                   11177: table, which contains the methods as function pointers. The vtable
                   11178: may also contain other information.
1.1       anton    11179: 
1.26      crook    11180: So first, let's declare methods:
1.1       anton    11181: 
1.26      crook    11182: @example
                   11183: : method ( m v -- m' v ) Create  over , swap cell+ swap
                   11184:   DOES> ( ... o -- ... ) @ over @ + @ execute ;
                   11185: @end example
1.1       anton    11186: 
1.26      crook    11187: During method declaration, the number of methods and instance
                   11188: variables is on the stack (in address units). @code{method} creates
                   11189: one method and increments the method number. To execute a method, it
                   11190: takes the object, fetches the vtable pointer, adds the offset, and
1.29      crook    11191: executes the @i{xt} stored there. Each method takes the object it is
1.26      crook    11192: invoked from as top of stack parameter. The method itself should
                   11193: consume that object.
1.1       anton    11194: 
1.26      crook    11195: Now, we also have to declare instance variables
1.21      crook    11196: 
1.26      crook    11197: @example
                   11198: : var ( m v size -- m v' ) Create  over , +
                   11199:   DOES> ( o -- addr ) @ + ;
                   11200: @end example
1.21      crook    11201: 
1.26      crook    11202: As before, a word is created with the current offset. Instance
                   11203: variables can have different sizes (cells, floats, doubles, chars), so
                   11204: all we do is take the size and add it to the offset. If your machine
                   11205: has alignment restrictions, put the proper @code{aligned} or
                   11206: @code{faligned} before the variable, to adjust the variable
                   11207: offset. That's why it is on the top of stack.
1.2       jwilke   11208: 
1.26      crook    11209: We need a starting point (the base object) and some syntactic sugar:
1.21      crook    11210: 
1.26      crook    11211: @example
                   11212: Create object  1 cells , 2 cells ,
                   11213: : class ( class -- class methods vars ) dup 2@ ;
                   11214: @end example
1.21      crook    11215: 
1.26      crook    11216: For inheritance, the vtable of the parent object has to be
                   11217: copied when a new, derived class is declared. This gives all the
                   11218: methods of the parent class, which can be overridden, though.
1.21      crook    11219: 
1.2       jwilke   11220: @example
1.26      crook    11221: : end-class  ( class methods vars -- )
                   11222:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
                   11223:   cell+ dup cell+ r> rot @ 2 cells /string move ;
                   11224: @end example
                   11225: 
                   11226: The first line creates the vtable, initialized with
                   11227: @code{noop}s. The second line is the inheritance mechanism, it
                   11228: copies the xts from the parent vtable.
1.2       jwilke   11229: 
1.26      crook    11230: We still have no way to define new methods, let's do that now:
1.2       jwilke   11231: 
1.26      crook    11232: @example
                   11233: : defines ( xt class -- ) ' >body @ + ! ;
1.2       jwilke   11234: @end example
                   11235: 
1.26      crook    11236: To allocate a new object, we need a word, too:
1.2       jwilke   11237: 
1.26      crook    11238: @example
                   11239: : new ( class -- o )  here over @ allot swap over ! ;
                   11240: @end example
1.2       jwilke   11241: 
1.26      crook    11242: Sometimes derived classes want to access the method of the
                   11243: parent object. There are two ways to achieve this with Mini-OOF:
                   11244: first, you could use named words, and second, you could look up the
                   11245: vtable of the parent object.
1.2       jwilke   11246: 
1.26      crook    11247: @example
                   11248: : :: ( class "name" -- ) ' >body @ + @ compile, ;
                   11249: @end example
1.2       jwilke   11250: 
                   11251: 
1.26      crook    11252: Nothing can be more confusing than a good example, so here is
                   11253: one. First let's declare a text object (called
                   11254: @code{button}), that stores text and position:
1.2       jwilke   11255: 
1.26      crook    11256: @example
                   11257: object class
                   11258:   cell var text
                   11259:   cell var len
                   11260:   cell var x
                   11261:   cell var y
                   11262:   method init
                   11263:   method draw
                   11264: end-class button
                   11265: @end example
1.2       jwilke   11266: 
1.26      crook    11267: @noindent
                   11268: Now, implement the two methods, @code{draw} and @code{init}:
1.2       jwilke   11269: 
1.26      crook    11270: @example
                   11271: :noname ( o -- )
                   11272:  >r r@ x @ r@ y @ at-xy  r@ text @ r> len @ type ;
                   11273:  button defines draw
                   11274: :noname ( addr u o -- )
                   11275:  >r 0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
                   11276:  button defines init
                   11277: @end example
1.2       jwilke   11278: 
1.26      crook    11279: @noindent
                   11280: To demonstrate inheritance, we define a class @code{bold-button}, with no
                   11281: new data and no new methods:
1.2       jwilke   11282: 
1.26      crook    11283: @example
                   11284: button class
                   11285: end-class bold-button
1.1       anton    11286: 
1.26      crook    11287: : bold   27 emit ." [1m" ;
                   11288: : normal 27 emit ." [0m" ;
                   11289: @end example
1.1       anton    11290: 
1.26      crook    11291: @noindent
                   11292: The class @code{bold-button} has a different draw method to
                   11293: @code{button}, but the new method is defined in terms of the draw method
                   11294: for @code{button}:
1.1       anton    11295: 
1.26      crook    11296: @example
                   11297: :noname bold [ button :: draw ] normal ; bold-button defines draw
                   11298: @end example
1.1       anton    11299: 
1.26      crook    11300: @noindent
                   11301: Finally, create two objects and apply methods:
1.1       anton    11302: 
1.26      crook    11303: @example
                   11304: button new Constant foo
                   11305: s" thin foo" foo init
                   11306: page
                   11307: foo draw
                   11308: bold-button new Constant bar
                   11309: s" fat bar" bar init
                   11310: 1 bar y !
                   11311: bar draw
                   11312: @end example
1.1       anton    11313: 
                   11314: 
1.48      anton    11315: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
                   11316: @subsection Comparison with other object models
1.26      crook    11317: @cindex comparison of object models
                   11318: @cindex object models, comparison
1.1       anton    11319: 
1.26      crook    11320: Many object-oriented Forth extensions have been proposed (@cite{A survey
                   11321: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
                   11322: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
                   11323: relation of the object models described here to two well-known and two
                   11324: closely-related (by the use of method maps) models.
1.1       anton    11325: 
1.26      crook    11326: @cindex Neon model
                   11327: The most popular model currently seems to be the Neon model (see
                   11328: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
                   11329: 1997) by Andrew McKewan) but this model has a number of limitations
                   11330: @footnote{A longer version of this critique can be
                   11331: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
                   11332: Dimensions, May 1997) by Anton Ertl.}:
1.1       anton    11333: 
1.26      crook    11334: @itemize @bullet
                   11335: @item
1.48      anton    11336: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
                   11337: to pass objects on the stack.
1.1       anton    11338: 
1.26      crook    11339: @item
                   11340: It requires that the selector parses the input stream (at
                   11341: compile time); this leads to reduced extensibility and to bugs that are+
                   11342: hard to find.
1.1       anton    11343: 
1.26      crook    11344: @item
                   11345: It allows using every selector to every object;
                   11346: this eliminates the need for classes, but makes it harder to create
                   11347: efficient implementations. 
                   11348: @end itemize
1.1       anton    11349: 
1.26      crook    11350: @cindex Pountain's object-oriented model
                   11351: Another well-known publication is @cite{Object-Oriented Forth} (Academic
                   11352: Press, London, 1987) by Dick Pountain. However, it is not really about
                   11353: object-oriented programming, because it hardly deals with late
                   11354: binding. Instead, it focuses on features like information hiding and
                   11355: overloading that are characteristic of modular languages like Ada (83).
1.1       anton    11356: 
1.26      crook    11357: @cindex Zsoter's object-oriented model
1.48      anton    11358: In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1)
                   11359: 1996, pages 31-35) Andras Zsoter describes a model that makes heavy use
                   11360: of an active object (like @code{this} in @file{objects.fs}): The active
                   11361: object is not only used for accessing all fields, but also specifies the
                   11362: receiving object of every selector invocation; you have to change the
                   11363: active object explicitly with @code{@{ ... @}}, whereas in
                   11364: @file{objects.fs} it changes more or less implicitly at @code{m:
                   11365: ... ;m}. Such a change at the method entry point is unnecessary with the
                   11366: Zsoter's model, because the receiving object is the active object
                   11367: already. On the other hand, the explicit change is absolutely necessary
                   11368: in that model, because otherwise no one could ever change the active
                   11369: object. An ANS Forth implementation of this model is available at
                   11370: @uref{http://www.forth.org/fig/oopf.html}.
1.1       anton    11371: 
1.26      crook    11372: @cindex @file{oof.fs}, differences to other models
                   11373: The @file{oof.fs} model combines information hiding and overloading
                   11374: resolution (by keeping names in various word lists) with object-oriented
                   11375: programming. It sets the active object implicitly on method entry, but
                   11376: also allows explicit changing (with @code{>o...o>} or with
                   11377: @code{with...endwith}). It uses parsing and state-smart objects and
                   11378: classes for resolving overloading and for early binding: the object or
                   11379: class parses the selector and determines the method from this. If the
                   11380: selector is not parsed by an object or class, it performs a call to the
                   11381: selector for the active object (late binding), like Zsoter's model.
                   11382: Fields are always accessed through the active object. The big
                   11383: disadvantage of this model is the parsing and the state-smartness, which
                   11384: reduces extensibility and increases the opportunities for subtle bugs;
                   11385: essentially, you are only safe if you never tick or @code{postpone} an
                   11386: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.1       anton    11387: 
1.26      crook    11388: @cindex @file{mini-oof.fs}, differences to other models
1.48      anton    11389: The @file{mini-oof.fs} model is quite similar to a very stripped-down
                   11390: version of the @file{objects.fs} model, but syntactically it is a
                   11391: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.1       anton    11392: 
1.26      crook    11393: @c -------------------------------------------------------------
1.47      crook    11394: @node Passing Commands to the OS, Keeping track of Time, Object-oriented Forth, Words
1.21      crook    11395: @section Passing Commands to the Operating System
                   11396: @cindex operating system - passing commands
                   11397: @cindex shell commands
                   11398: 
                   11399: Gforth allows you to pass an arbitrary string to the host operating
                   11400: system shell (if such a thing exists) for execution.
                   11401: 
1.44      crook    11402: 
1.21      crook    11403: doc-sh
                   11404: doc-system
                   11405: doc-$?
1.23      crook    11406: doc-getenv
1.21      crook    11407: 
1.44      crook    11408: 
1.26      crook    11409: @c -------------------------------------------------------------
1.47      crook    11410: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
                   11411: @section Keeping track of Time
                   11412: @cindex time-related words
                   11413: 
                   11414: Gforth implements time-related operations by making calls to the C
                   11415: library function, @code{gettimeofday}.
                   11416: 
                   11417: doc-ms
                   11418: doc-time&date
                   11419: 
                   11420: 
                   11421: 
                   11422: @c -------------------------------------------------------------
                   11423: @node Miscellaneous Words,  , Keeping track of Time, Words
1.21      crook    11424: @section Miscellaneous Words
                   11425: @cindex miscellaneous words
                   11426: 
1.29      crook    11427: @comment TODO find homes for these
                   11428: 
1.26      crook    11429: These section lists the ANS Forth words that are not documented
1.21      crook    11430: elsewhere in this manual. Ultimately, they all need proper homes.
                   11431: 
                   11432: doc-[compile]
                   11433: 
1.44      crook    11434: 
1.26      crook    11435: The following ANS Forth words are not currently supported by Gforth 
1.27      crook    11436: (@pxref{ANS conformance}):
1.21      crook    11437: 
                   11438: @code{EDITOR} 
                   11439: @code{EMIT?} 
                   11440: @code{FORGET} 
                   11441: 
1.24      anton    11442: @c ******************************************************************
                   11443: @node Error messages, Tools, Words, Top
                   11444: @chapter Error messages
                   11445: @cindex error messages
                   11446: @cindex backtrace
                   11447: 
                   11448: A typical Gforth error message looks like this:
                   11449: 
                   11450: @example
                   11451: in file included from :-1
                   11452: in file included from ./yyy.fs:1
                   11453: ./xxx.fs:4: Invalid memory address
                   11454: bar
                   11455: ^^^
1.25      anton    11456: $400E664C @@
                   11457: $400E6664 foo
1.24      anton    11458: @end example
                   11459: 
                   11460: The message identifying the error is @code{Invalid memory address}.  The
                   11461: error happened when text-interpreting line 4 of the file
                   11462: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
                   11463: word on the line where the error happened, is pointed out (with
                   11464: @code{^^^}).
                   11465: 
                   11466: The file containing the error was included in line 1 of @file{./yyy.fs},
                   11467: and @file{yyy.fs} was included from a non-file (in this case, by giving
                   11468: @file{yyy.fs} as command-line parameter to Gforth).
                   11469: 
                   11470: At the end of the error message you find a return stack dump that can be
                   11471: interpreted as a backtrace (possibly empty). On top you find the top of
                   11472: the return stack when the @code{throw} happened, and at the bottom you
                   11473: find the return stack entry just above the return stack of the topmost
                   11474: text interpreter.
                   11475: 
                   11476: To the right of most return stack entries you see a guess for the word
                   11477: that pushed that return stack entry as its return address. This gives a
                   11478: backtrace. In our case we see that @code{bar} called @code{foo}, and
                   11479: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
                   11480: address} exception).
                   11481: 
                   11482: Note that the backtrace is not perfect: We don't know which return stack
                   11483: entries are return addresses (so we may get false positives); and in
                   11484: some cases (e.g., for @code{abort"}) we cannot determine from the return
                   11485: address the word that pushed the return address, so for some return
                   11486: addresses you see no names in the return stack dump.
1.25      anton    11487: 
                   11488: @cindex @code{catch} and backtraces
                   11489: The return stack dump represents the return stack at the time when a
                   11490: specific @code{throw} was executed.  In programs that make use of
                   11491: @code{catch}, it is not necessarily clear which @code{throw} should be
                   11492: used for the return stack dump (e.g., consider one @code{throw} that
                   11493: indicates an error, which is caught, and during recovery another error
1.42      anton    11494: happens; which @code{throw} should be used for the stack dump?).  Gforth
1.25      anton    11495: presents the return stack dump for the first @code{throw} after the last
                   11496: executed (not returned-to) @code{catch}; this works well in the usual
                   11497: case.
                   11498: 
                   11499: @cindex @code{gforth-fast} and backtraces
                   11500: @cindex @code{gforth-fast}, difference from @code{gforth}
                   11501: @cindex backtraces with @code{gforth-fast}
                   11502: @cindex return stack dump with @code{gforth-fast}
                   11503: @code{gforth} is able to do a return stack dump for throws generated
                   11504: from primitives (e.g., invalid memory address, stack empty etc.);
                   11505: @code{gforth-fast} is only able to do a return stack dump from a
                   11506: directly called @code{throw} (including @code{abort} etc.).  This is the
1.30      anton    11507: only difference (apart from a speed factor of between 1.15 (K6-2) and
                   11508: 1.6 (21164A)) between @code{gforth} and @code{gforth-fast}.  Given an
                   11509: exception caused by a primitive in @code{gforth-fast}, you will
                   11510: typically see no return stack dump at all; however, if the exception is
                   11511: caught by @code{catch} (e.g., for restoring some state), and then
                   11512: @code{throw}n again, the return stack dump will be for the first such
                   11513: @code{throw}.
1.2       jwilke   11514: 
1.5       anton    11515: @c ******************************************************************
1.24      anton    11516: @node Tools, ANS conformance, Error messages, Top
1.1       anton    11517: @chapter Tools
                   11518: 
                   11519: @menu
                   11520: * ANS Report::                  Report the words used, sorted by wordset.
                   11521: @end menu
                   11522: 
                   11523: See also @ref{Emacs and Gforth}.
                   11524: 
                   11525: @node ANS Report,  , Tools, Tools
                   11526: @section @file{ans-report.fs}: Report the words used, sorted by wordset
                   11527: @cindex @file{ans-report.fs}
                   11528: @cindex report the words used in your program
                   11529: @cindex words used in your program
                   11530: 
                   11531: If you want to label a Forth program as ANS Forth Program, you must
                   11532: document which wordsets the program uses; for extension wordsets, it is
                   11533: helpful to list the words the program requires from these wordsets
                   11534: (because Forth systems are allowed to provide only some words of them).
                   11535: 
                   11536: The @file{ans-report.fs} tool makes it easy for you to determine which
                   11537: words from which wordset and which non-ANS words your application
                   11538: uses. You simply have to include @file{ans-report.fs} before loading the
                   11539: program you want to check. After loading your program, you can get the
                   11540: report with @code{print-ans-report}. A typical use is to run this as
                   11541: batch job like this:
                   11542: @example
                   11543: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
                   11544: @end example
                   11545: 
                   11546: The output looks like this (for @file{compat/control.fs}):
                   11547: @example
                   11548: The program uses the following words
                   11549: from CORE :
                   11550: : POSTPONE THEN ; immediate ?dup IF 0= 
                   11551: from BLOCK-EXT :
                   11552: \ 
                   11553: from FILE :
                   11554: ( 
                   11555: @end example
                   11556: 
                   11557: @subsection Caveats
                   11558: 
                   11559: Note that @file{ans-report.fs} just checks which words are used, not whether
                   11560: they are used in an ANS Forth conforming way!
                   11561: 
                   11562: Some words are defined in several wordsets in the
                   11563: standard. @file{ans-report.fs} reports them for only one of the
                   11564: wordsets, and not necessarily the one you expect. It depends on usage
                   11565: which wordset is the right one to specify. E.g., if you only use the
                   11566: compilation semantics of @code{S"}, it is a Core word; if you also use
                   11567: its interpretation semantics, it is a File word.
                   11568: 
                   11569: @c ******************************************************************
                   11570: @node ANS conformance, Model, Tools, Top
                   11571: @chapter ANS conformance
                   11572: @cindex ANS conformance of Gforth
                   11573: 
                   11574: To the best of our knowledge, Gforth is an
                   11575: 
                   11576: ANS Forth System
                   11577: @itemize @bullet
                   11578: @item providing the Core Extensions word set
                   11579: @item providing the Block word set
                   11580: @item providing the Block Extensions word set
                   11581: @item providing the Double-Number word set
                   11582: @item providing the Double-Number Extensions word set
                   11583: @item providing the Exception word set
                   11584: @item providing the Exception Extensions word set
                   11585: @item providing the Facility word set
1.40      anton    11586: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1       anton    11587: @item providing the File Access word set
                   11588: @item providing the File Access Extensions word set
                   11589: @item providing the Floating-Point word set
                   11590: @item providing the Floating-Point Extensions word set
                   11591: @item providing the Locals word set
                   11592: @item providing the Locals Extensions word set
                   11593: @item providing the Memory-Allocation word set
                   11594: @item providing the Memory-Allocation Extensions word set (that one's easy)
                   11595: @item providing the Programming-Tools word set
                   11596: @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
                   11597: @item providing the Search-Order word set
                   11598: @item providing the Search-Order Extensions word set
                   11599: @item providing the String word set
                   11600: @item providing the String Extensions word set (another easy one)
                   11601: @end itemize
                   11602: 
                   11603: @cindex system documentation
                   11604: In addition, ANS Forth systems are required to document certain
                   11605: implementation choices. This chapter tries to meet these
                   11606: requirements. In many cases it gives a way to ask the system for the
                   11607: information instead of providing the information directly, in
                   11608: particular, if the information depends on the processor, the operating
                   11609: system or the installation options chosen, or if they are likely to
                   11610: change during the maintenance of Gforth.
                   11611: 
                   11612: @comment The framework for the rest has been taken from pfe.
                   11613: 
                   11614: @menu
                   11615: * The Core Words::              
                   11616: * The optional Block word set::  
                   11617: * The optional Double Number word set::  
                   11618: * The optional Exception word set::  
                   11619: * The optional Facility word set::  
                   11620: * The optional File-Access word set::  
                   11621: * The optional Floating-Point word set::  
                   11622: * The optional Locals word set::  
                   11623: * The optional Memory-Allocation word set::  
                   11624: * The optional Programming-Tools word set::  
                   11625: * The optional Search-Order word set::  
                   11626: @end menu
                   11627: 
                   11628: 
                   11629: @c =====================================================================
                   11630: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
                   11631: @comment  node-name,  next,  previous,  up
                   11632: @section The Core Words
                   11633: @c =====================================================================
                   11634: @cindex core words, system documentation
                   11635: @cindex system documentation, core words
                   11636: 
                   11637: @menu
                   11638: * core-idef::                   Implementation Defined Options                   
                   11639: * core-ambcond::                Ambiguous Conditions                
                   11640: * core-other::                  Other System Documentation                  
                   11641: @end menu
                   11642: 
                   11643: @c ---------------------------------------------------------------------
                   11644: @node core-idef, core-ambcond, The Core Words, The Core Words
                   11645: @subsection Implementation Defined Options
                   11646: @c ---------------------------------------------------------------------
                   11647: @cindex core words, implementation-defined options
                   11648: @cindex implementation-defined options, core words
                   11649: 
                   11650: 
                   11651: @table @i
                   11652: @item (Cell) aligned addresses:
                   11653: @cindex cell-aligned addresses
                   11654: @cindex aligned addresses
                   11655: processor-dependent. Gforth's alignment words perform natural alignment
                   11656: (e.g., an address aligned for a datum of size 8 is divisible by
                   11657: 8). Unaligned accesses usually result in a @code{-23 THROW}.
                   11658: 
                   11659: @item @code{EMIT} and non-graphic characters:
                   11660: @cindex @code{EMIT} and non-graphic characters
                   11661: @cindex non-graphic characters and @code{EMIT}
                   11662: The character is output using the C library function (actually, macro)
                   11663: @code{putc}.
                   11664: 
                   11665: @item character editing of @code{ACCEPT} and @code{EXPECT}:
                   11666: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
                   11667: @cindex editing in @code{ACCEPT} and @code{EXPECT}
                   11668: @cindex @code{ACCEPT}, editing
                   11669: @cindex @code{EXPECT}, editing
                   11670: This is modeled on the GNU readline library (@pxref{Readline
                   11671: Interaction, , Command Line Editing, readline, The GNU Readline
                   11672: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
                   11673: producing a full word completion every time you type it (instead of
1.28      crook    11674: producing the common prefix of all completions). @xref{Command-line editing}.
1.1       anton    11675: 
                   11676: @item character set:
                   11677: @cindex character set
                   11678: The character set of your computer and display device. Gforth is
                   11679: 8-bit-clean (but some other component in your system may make trouble).
                   11680: 
                   11681: @item Character-aligned address requirements:
                   11682: @cindex character-aligned address requirements
                   11683: installation-dependent. Currently a character is represented by a C
                   11684: @code{unsigned char}; in the future we might switch to @code{wchar_t}
                   11685: (Comments on that requested).
                   11686: 
                   11687: @item character-set extensions and matching of names:
                   11688: @cindex character-set extensions and matching of names
1.26      crook    11689: @cindex case-sensitivity for name lookup
                   11690: @cindex name lookup, case-sensitivity
                   11691: @cindex locale and case-sensitivity
1.21      crook    11692: Any character except the ASCII NUL character can be used in a
1.1       anton    11693: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47      crook    11694: matching is performed using the C library function @code{strncasecmp}, whose
1.1       anton    11695: function is probably influenced by the locale. E.g., the @code{C} locale
                   11696: does not know about accents and umlauts, so they are matched
                   11697: case-sensitively in that locale. For portability reasons it is best to
                   11698: write programs such that they work in the @code{C} locale. Then one can
                   11699: use libraries written by a Polish programmer (who might use words
                   11700: containing ISO Latin-2 encoded characters) and by a French programmer
                   11701: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
                   11702: funny results for some of the words (which ones, depends on the font you
                   11703: are using)). Also, the locale you prefer may not be available in other
                   11704: operating systems. Hopefully, Unicode will solve these problems one day.
                   11705: 
                   11706: @item conditions under which control characters match a space delimiter:
                   11707: @cindex space delimiters
                   11708: @cindex control characters as delimiters
                   11709: If @code{WORD} is called with the space character as a delimiter, all
                   11710: white-space characters (as identified by the C macro @code{isspace()})
                   11711: are delimiters. @code{PARSE}, on the other hand, treats space like other
1.44      crook    11712: delimiters. @code{SWORD} treats space like @code{WORD}, but behaves
1.1       anton    11713: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
                   11714: interpreter (aka text interpreter) by default, treats all white-space
                   11715: characters as delimiters.
                   11716: 
1.26      crook    11717: @item format of the control-flow stack:
                   11718: @cindex control-flow stack, format
                   11719: The data stack is used as control-flow stack. The size of a control-flow
1.1       anton    11720: stack item in cells is given by the constant @code{cs-item-size}. At the
                   11721: time of this writing, an item consists of a (pointer to a) locals list
                   11722: (third), an address in the code (second), and a tag for identifying the
                   11723: item (TOS). The following tags are used: @code{defstart},
                   11724: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
                   11725: @code{scopestart}.
                   11726: 
                   11727: @item conversion of digits > 35
                   11728: @cindex digits > 35
                   11729: The characters @code{[\]^_'} are the digits with the decimal value
                   11730: 36@minus{}41. There is no way to input many of the larger digits.
                   11731: 
                   11732: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
                   11733: @cindex @code{EXPECT}, display after end of input
                   11734: @cindex @code{ACCEPT}, display after end of input
                   11735: The cursor is moved to the end of the entered string. If the input is
                   11736: terminated using the @kbd{Return} key, a space is typed.
                   11737: 
                   11738: @item exception abort sequence of @code{ABORT"}:
                   11739: @cindex exception abort sequence of @code{ABORT"}
                   11740: @cindex @code{ABORT"}, exception abort sequence
                   11741: The error string is stored into the variable @code{"error} and a
                   11742: @code{-2 throw} is performed.
                   11743: 
                   11744: @item input line terminator:
                   11745: @cindex input line terminator
                   11746: @cindex line terminator on input
1.26      crook    11747: @cindex newline character on input
1.1       anton    11748: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
                   11749: lines. One of these characters is typically produced when you type the
                   11750: @kbd{Enter} or @kbd{Return} key.
                   11751: 
                   11752: @item maximum size of a counted string:
                   11753: @cindex maximum size of a counted string
                   11754: @cindex counted string, maximum size
                   11755: @code{s" /counted-string" environment? drop .}. Currently 255 characters
                   11756: on all ports, but this may change.
                   11757: 
                   11758: @item maximum size of a parsed string:
                   11759: @cindex maximum size of a parsed string
                   11760: @cindex parsed string, maximum size
                   11761: Given by the constant @code{/line}. Currently 255 characters.
                   11762: 
                   11763: @item maximum size of a definition name, in characters:
                   11764: @cindex maximum size of a definition name, in characters
                   11765: @cindex name, maximum length
                   11766: 31
                   11767: 
                   11768: @item maximum string length for @code{ENVIRONMENT?}, in characters:
                   11769: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
                   11770: @cindex @code{ENVIRONMENT?} string length, maximum
                   11771: 31
                   11772: 
                   11773: @item method of selecting the user input device:
                   11774: @cindex user input device, method of selecting
                   11775: The user input device is the standard input. There is currently no way to
                   11776: change it from within Gforth. However, the input can typically be
                   11777: redirected in the command line that starts Gforth.
                   11778: 
                   11779: @item method of selecting the user output device:
                   11780: @cindex user output device, method of selecting
                   11781: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10      anton    11782: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
                   11783: output when the user output device is a terminal, otherwise the output
                   11784: is buffered.
1.1       anton    11785: 
                   11786: @item methods of dictionary compilation:
                   11787: What are we expected to document here?
                   11788: 
                   11789: @item number of bits in one address unit:
                   11790: @cindex number of bits in one address unit
                   11791: @cindex address unit, size in bits
                   11792: @code{s" address-units-bits" environment? drop .}. 8 in all current
                   11793: ports.
                   11794: 
                   11795: @item number representation and arithmetic:
                   11796: @cindex number representation and arithmetic
                   11797: Processor-dependent. Binary two's complement on all current ports.
                   11798: 
                   11799: @item ranges for integer types:
                   11800: @cindex ranges for integer types
                   11801: @cindex integer types, ranges
                   11802: Installation-dependent. Make environmental queries for @code{MAX-N},
                   11803: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
                   11804: unsigned (and positive) types is 0. The lower bound for signed types on
                   11805: two's complement and one's complement machines machines can be computed
                   11806: by adding 1 to the upper bound.
                   11807: 
                   11808: @item read-only data space regions:
                   11809: @cindex read-only data space regions
                   11810: @cindex data-space, read-only regions
                   11811: The whole Forth data space is writable.
                   11812: 
                   11813: @item size of buffer at @code{WORD}:
                   11814: @cindex size of buffer at @code{WORD}
                   11815: @cindex @code{WORD} buffer size
                   11816: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   11817: shared with the pictured numeric output string. If overwriting
                   11818: @code{PAD} is acceptable, it is as large as the remaining dictionary
                   11819: space, although only as much can be sensibly used as fits in a counted
                   11820: string.
                   11821: 
                   11822: @item size of one cell in address units:
                   11823: @cindex cell size
                   11824: @code{1 cells .}.
                   11825: 
                   11826: @item size of one character in address units:
                   11827: @cindex char size
                   11828: @code{1 chars .}. 1 on all current ports.
                   11829: 
                   11830: @item size of the keyboard terminal buffer:
                   11831: @cindex size of the keyboard terminal buffer
                   11832: @cindex terminal buffer, size
                   11833: Varies. You can determine the size at a specific time using @code{lp@@
                   11834: tib - .}. It is shared with the locals stack and TIBs of files that
                   11835: include the current file. You can change the amount of space for TIBs
                   11836: and locals stack at Gforth startup with the command line option
                   11837: @code{-l}.
                   11838: 
                   11839: @item size of the pictured numeric output buffer:
                   11840: @cindex size of the pictured numeric output buffer
                   11841: @cindex pictured numeric output buffer, size
                   11842: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   11843: shared with @code{WORD}.
                   11844: 
                   11845: @item size of the scratch area returned by @code{PAD}:
                   11846: @cindex size of the scratch area returned by @code{PAD}
                   11847: @cindex @code{PAD} size
                   11848: The remainder of dictionary space. @code{unused pad here - - .}.
                   11849: 
                   11850: @item system case-sensitivity characteristics:
                   11851: @cindex case-sensitivity characteristics
1.26      crook    11852: Dictionary searches are case-insensitive (except in
1.1       anton    11853: @code{TABLE}s). However, as explained above under @i{character-set
                   11854: extensions}, the matching for non-ASCII characters is determined by the
                   11855: locale you are using. In the default @code{C} locale all non-ASCII
                   11856: characters are matched case-sensitively.
                   11857: 
                   11858: @item system prompt:
                   11859: @cindex system prompt
                   11860: @cindex prompt
                   11861: @code{ ok} in interpret state, @code{ compiled} in compile state.
                   11862: 
                   11863: @item division rounding:
                   11864: @cindex division rounding
                   11865: installation dependent. @code{s" floored" environment? drop .}. We leave
                   11866: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
                   11867: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
                   11868: 
                   11869: @item values of @code{STATE} when true:
                   11870: @cindex @code{STATE} values
                   11871: -1.
                   11872: 
                   11873: @item values returned after arithmetic overflow:
                   11874: On two's complement machines, arithmetic is performed modulo
                   11875: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   11876: arithmetic (with appropriate mapping for signed types). Division by zero
                   11877: typically results in a @code{-55 throw} (Floating-point unidentified
                   11878: fault), although a @code{-10 throw} (divide by zero) would be more
                   11879: appropriate.
                   11880: 
                   11881: @item whether the current definition can be found after @t{DOES>}:
                   11882: @cindex @t{DOES>}, visibility of current definition
                   11883: No.
                   11884: 
                   11885: @end table
                   11886: 
                   11887: @c ---------------------------------------------------------------------
                   11888: @node core-ambcond, core-other, core-idef, The Core Words
                   11889: @subsection Ambiguous conditions
                   11890: @c ---------------------------------------------------------------------
                   11891: @cindex core words, ambiguous conditions
                   11892: @cindex ambiguous conditions, core words
                   11893: 
                   11894: @table @i
                   11895: 
                   11896: @item a name is neither a word nor a number:
                   11897: @cindex name not found
1.26      crook    11898: @cindex undefined word
1.1       anton    11899: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
                   11900: preserves the data and FP stack, so you don't lose more work than
                   11901: necessary.
                   11902: 
                   11903: @item a definition name exceeds the maximum length allowed:
1.26      crook    11904: @cindex word name too long
1.1       anton    11905: @code{-19 throw} (Word name too long)
                   11906: 
                   11907: @item addressing a region not inside the various data spaces of the forth system:
                   11908: @cindex Invalid memory address
1.32      anton    11909: The stacks, code space and header space are accessible. Machine code space is
1.1       anton    11910: typically readable. Accessing other addresses gives results dependent on
                   11911: the operating system. On decent systems: @code{-9 throw} (Invalid memory
                   11912: address).
                   11913: 
                   11914: @item argument type incompatible with parameter:
1.26      crook    11915: @cindex argument type mismatch
1.1       anton    11916: This is usually not caught. Some words perform checks, e.g., the control
                   11917: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
                   11918: mismatch).
                   11919: 
                   11920: @item attempting to obtain the execution token of a word with undefined execution semantics:
                   11921: @cindex Interpreting a compile-only word, for @code{'} etc.
                   11922: @cindex execution token of words with undefined execution semantics
                   11923: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
                   11924: get an execution token for @code{compile-only-error} (which performs a
                   11925: @code{-14 throw} when executed).
                   11926: 
                   11927: @item dividing by zero:
                   11928: @cindex dividing by zero
                   11929: @cindex floating point unidentified fault, integer division
1.24      anton    11930: On better platforms, this produces a @code{-10 throw} (Division by
                   11931: zero); on other systems, this typically results in a @code{-55 throw}
                   11932: (Floating-point unidentified fault).
1.1       anton    11933: 
                   11934: @item insufficient data stack or return stack space:
                   11935: @cindex insufficient data stack or return stack space
                   11936: @cindex stack overflow
1.26      crook    11937: @cindex address alignment exception, stack overflow
1.1       anton    11938: @cindex Invalid memory address, stack overflow
                   11939: Depending on the operating system, the installation, and the invocation
                   11940: of Gforth, this is either checked by the memory management hardware, or
1.24      anton    11941: it is not checked. If it is checked, you typically get a @code{-3 throw}
                   11942: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
                   11943: throw} (Invalid memory address) (depending on the platform and how you
                   11944: achieved the overflow) as soon as the overflow happens. If it is not
                   11945: checked, overflows typically result in mysterious illegal memory
                   11946: accesses, producing @code{-9 throw} (Invalid memory address) or
                   11947: @code{-23 throw} (Address alignment exception); they might also destroy
                   11948: the internal data structure of @code{ALLOCATE} and friends, resulting in
                   11949: various errors in these words.
1.1       anton    11950: 
                   11951: @item insufficient space for loop control parameters:
                   11952: @cindex insufficient space for loop control parameters
                   11953: like other return stack overflows.
                   11954: 
                   11955: @item insufficient space in the dictionary:
                   11956: @cindex insufficient space in the dictionary
                   11957: @cindex dictionary overflow
1.12      anton    11958: If you try to allot (either directly with @code{allot}, or indirectly
                   11959: with @code{,}, @code{create} etc.) more memory than available in the
                   11960: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
                   11961: to access memory beyond the end of the dictionary, the results are
                   11962: similar to stack overflows.
1.1       anton    11963: 
                   11964: @item interpreting a word with undefined interpretation semantics:
                   11965: @cindex interpreting a word with undefined interpretation semantics
                   11966: @cindex Interpreting a compile-only word
                   11967: For some words, we have defined interpretation semantics. For the
                   11968: others: @code{-14 throw} (Interpreting a compile-only word).
                   11969: 
                   11970: @item modifying the contents of the input buffer or a string literal:
                   11971: @cindex modifying the contents of the input buffer or a string literal
                   11972: These are located in writable memory and can be modified.
                   11973: 
                   11974: @item overflow of the pictured numeric output string:
                   11975: @cindex overflow of the pictured numeric output string
                   11976: @cindex pictured numeric output string, overflow
1.24      anton    11977: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1       anton    11978: 
                   11979: @item parsed string overflow:
                   11980: @cindex parsed string overflow
                   11981: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
                   11982: 
                   11983: @item producing a result out of range:
                   11984: @cindex result out of range
                   11985: On two's complement machines, arithmetic is performed modulo
                   11986: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   11987: arithmetic (with appropriate mapping for signed types). Division by zero
1.24      anton    11988: typically results in a @code{-10 throw} (divide by zero) or @code{-55
                   11989: throw} (floating point unidentified fault). @code{convert} and
                   11990: @code{>number} currently overflow silently.
1.1       anton    11991: 
                   11992: @item reading from an empty data or return stack:
                   11993: @cindex stack empty
                   11994: @cindex stack underflow
1.24      anton    11995: @cindex return stack underflow
1.1       anton    11996: The data stack is checked by the outer (aka text) interpreter after
                   11997: every word executed. If it has underflowed, a @code{-4 throw} (Stack
                   11998: underflow) is performed. Apart from that, stacks may be checked or not,
1.24      anton    11999: depending on operating system, installation, and invocation. If they are
                   12000: caught by a check, they typically result in @code{-4 throw} (Stack
                   12001: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
                   12002: (Invalid memory address), depending on the platform and which stack
                   12003: underflows and by how much. Note that even if the system uses checking
                   12004: (through the MMU), your program may have to underflow by a significant
                   12005: number of stack items to trigger the reaction (the reason for this is
                   12006: that the MMU, and therefore the checking, works with a page-size
                   12007: granularity).  If there is no checking, the symptoms resulting from an
                   12008: underflow are similar to those from an overflow.  Unbalanced return
                   12009: stack errors result in a variaty of symptoms, including @code{-9 throw}
                   12010: (Invalid memory address) and Illegal Instruction (typically @code{-260
                   12011: throw}).
1.1       anton    12012: 
                   12013: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
                   12014: @cindex unexpected end of the input buffer
                   12015: @cindex zero-length string as a name
                   12016: @cindex Attempt to use zero-length string as a name
                   12017: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
                   12018: use zero-length string as a name). Words like @code{'} probably will not
                   12019: find what they search. Note that it is possible to create zero-length
                   12020: names with @code{nextname} (should it not?).
                   12021: 
                   12022: @item @code{>IN} greater than input buffer:
                   12023: @cindex @code{>IN} greater than input buffer
                   12024: The next invocation of a parsing word returns a string with length 0.
                   12025: 
                   12026: @item @code{RECURSE} appears after @code{DOES>}:
                   12027: @cindex @code{RECURSE} appears after @code{DOES>}
                   12028: Compiles a recursive call to the defining word, not to the defined word.
                   12029: 
                   12030: @item argument input source different than current input source for @code{RESTORE-INPUT}:
                   12031: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26      crook    12032: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1       anton    12033: @cindex @code{RESTORE-INPUT}, Argument type mismatch
                   12034: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
                   12035: the end of the file was reached), its source-id may be
                   12036: reused. Therefore, restoring an input source specification referencing a
                   12037: closed file may lead to unpredictable results instead of a @code{-12
                   12038: THROW}.
                   12039: 
                   12040: In the future, Gforth may be able to restore input source specifications
                   12041: from other than the current input source.
                   12042: 
                   12043: @item data space containing definitions gets de-allocated:
                   12044: @cindex data space containing definitions gets de-allocated
                   12045: Deallocation with @code{allot} is not checked. This typically results in
                   12046: memory access faults or execution of illegal instructions.
                   12047: 
                   12048: @item data space read/write with incorrect alignment:
                   12049: @cindex data space read/write with incorrect alignment
                   12050: @cindex alignment faults
1.26      crook    12051: @cindex address alignment exception
1.1       anton    12052: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12      anton    12053: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1       anton    12054: alignment turned on, incorrect alignment results in a @code{-9 throw}
                   12055: (Invalid memory address). There are reportedly some processors with
1.12      anton    12056: alignment restrictions that do not report violations.
1.1       anton    12057: 
                   12058: @item data space pointer not properly aligned, @code{,}, @code{C,}:
                   12059: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
                   12060: Like other alignment errors.
                   12061: 
                   12062: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
                   12063: Like other stack underflows.
                   12064: 
                   12065: @item loop control parameters not available:
                   12066: @cindex loop control parameters not available
                   12067: Not checked. The counted loop words simply assume that the top of return
                   12068: stack items are loop control parameters and behave accordingly.
                   12069: 
                   12070: @item most recent definition does not have a name (@code{IMMEDIATE}):
                   12071: @cindex most recent definition does not have a name (@code{IMMEDIATE})
                   12072: @cindex last word was headerless
                   12073: @code{abort" last word was headerless"}.
                   12074: 
                   12075: @item name not defined by @code{VALUE} used by @code{TO}:
                   12076: @cindex name not defined by @code{VALUE} used by @code{TO}
                   12077: @cindex @code{TO} on non-@code{VALUE}s
                   12078: @cindex Invalid name argument, @code{TO}
                   12079: @code{-32 throw} (Invalid name argument) (unless name is a local or was
                   12080: defined by @code{CONSTANT}; in the latter case it just changes the constant).
                   12081: 
                   12082: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
                   12083: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26      crook    12084: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1       anton    12085: @code{-13 throw} (Undefined word)
                   12086: 
                   12087: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
                   12088: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
                   12089: Gforth behaves as if they were of the same type. I.e., you can predict
                   12090: the behaviour by interpreting all parameters as, e.g., signed.
                   12091: 
                   12092: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
                   12093: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
                   12094: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
                   12095: compilation semantics of @code{TO}.
                   12096: 
                   12097: @item String longer than a counted string returned by @code{WORD}:
1.26      crook    12098: @cindex string longer than a counted string returned by @code{WORD}
1.1       anton    12099: @cindex @code{WORD}, string overflow
                   12100: Not checked. The string will be ok, but the count will, of course,
                   12101: contain only the least significant bits of the length.
                   12102: 
                   12103: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
                   12104: @cindex @code{LSHIFT}, large shift counts
                   12105: @cindex @code{RSHIFT}, large shift counts
                   12106: Processor-dependent. Typical behaviours are returning 0 and using only
                   12107: the low bits of the shift count.
                   12108: 
                   12109: @item word not defined via @code{CREATE}:
                   12110: @cindex @code{>BODY} of non-@code{CREATE}d words
                   12111: @code{>BODY} produces the PFA of the word no matter how it was defined.
                   12112: 
                   12113: @cindex @code{DOES>} of non-@code{CREATE}d words
                   12114: @code{DOES>} changes the execution semantics of the last defined word no
                   12115: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
                   12116: @code{CREATE , DOES>}.
                   12117: 
                   12118: @item words improperly used outside @code{<#} and @code{#>}:
                   12119: Not checked. As usual, you can expect memory faults.
                   12120: 
                   12121: @end table
                   12122: 
                   12123: 
                   12124: @c ---------------------------------------------------------------------
                   12125: @node core-other,  , core-ambcond, The Core Words
                   12126: @subsection Other system documentation
                   12127: @c ---------------------------------------------------------------------
                   12128: @cindex other system documentation, core words
                   12129: @cindex core words, other system documentation
                   12130: 
                   12131: @table @i
                   12132: @item nonstandard words using @code{PAD}:
                   12133: @cindex @code{PAD} use by nonstandard words
                   12134: None.
                   12135: 
                   12136: @item operator's terminal facilities available:
                   12137: @cindex operator's terminal facilities available
                   12138: After processing the command line, Gforth goes into interactive mode,
                   12139: and you can give commands to Gforth interactively. The actual facilities
                   12140: available depend on how you invoke Gforth.
                   12141: 
                   12142: @item program data space available:
                   12143: @cindex program data space available
                   12144: @cindex data space available
                   12145: @code{UNUSED .} gives the remaining dictionary space. The total
                   12146: dictionary space can be specified with the @code{-m} switch
                   12147: (@pxref{Invoking Gforth}) when Gforth starts up.
                   12148: 
                   12149: @item return stack space available:
                   12150: @cindex return stack space available
                   12151: You can compute the total return stack space in cells with
                   12152: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
                   12153: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
                   12154: 
                   12155: @item stack space available:
                   12156: @cindex stack space available
                   12157: You can compute the total data stack space in cells with
                   12158: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
                   12159: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
                   12160: 
                   12161: @item system dictionary space required, in address units:
                   12162: @cindex system dictionary space required, in address units
                   12163: Type @code{here forthstart - .} after startup. At the time of this
                   12164: writing, this gives 80080 (bytes) on a 32-bit system.
                   12165: @end table
                   12166: 
                   12167: 
                   12168: @c =====================================================================
                   12169: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
                   12170: @section The optional Block word set
                   12171: @c =====================================================================
                   12172: @cindex system documentation, block words
                   12173: @cindex block words, system documentation
                   12174: 
                   12175: @menu
                   12176: * block-idef::                  Implementation Defined Options
                   12177: * block-ambcond::               Ambiguous Conditions               
                   12178: * block-other::                 Other System Documentation                 
                   12179: @end menu
                   12180: 
                   12181: 
                   12182: @c ---------------------------------------------------------------------
                   12183: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
                   12184: @subsection Implementation Defined Options
                   12185: @c ---------------------------------------------------------------------
                   12186: @cindex implementation-defined options, block words
                   12187: @cindex block words, implementation-defined options
                   12188: 
                   12189: @table @i
                   12190: @item the format for display by @code{LIST}:
                   12191: @cindex @code{LIST} display format
                   12192: First the screen number is displayed, then 16 lines of 64 characters,
                   12193: each line preceded by the line number.
                   12194: 
                   12195: @item the length of a line affected by @code{\}:
                   12196: @cindex length of a line affected by @code{\}
                   12197: @cindex @code{\}, line length in blocks
                   12198: 64 characters.
                   12199: @end table
                   12200: 
                   12201: 
                   12202: @c ---------------------------------------------------------------------
                   12203: @node block-ambcond, block-other, block-idef, The optional Block word set
                   12204: @subsection Ambiguous conditions
                   12205: @c ---------------------------------------------------------------------
                   12206: @cindex block words, ambiguous conditions
                   12207: @cindex ambiguous conditions, block words
                   12208: 
                   12209: @table @i
                   12210: @item correct block read was not possible:
                   12211: @cindex block read not possible
                   12212: Typically results in a @code{throw} of some OS-derived value (between
                   12213: -512 and -2048). If the blocks file was just not long enough, blanks are
                   12214: supplied for the missing portion.
                   12215: 
                   12216: @item I/O exception in block transfer:
                   12217: @cindex I/O exception in block transfer
                   12218: @cindex block transfer, I/O exception
                   12219: Typically results in a @code{throw} of some OS-derived value (between
                   12220: -512 and -2048).
                   12221: 
                   12222: @item invalid block number:
                   12223: @cindex invalid block number
                   12224: @cindex block number invalid
                   12225: @code{-35 throw} (Invalid block number)
                   12226: 
                   12227: @item a program directly alters the contents of @code{BLK}:
                   12228: @cindex @code{BLK}, altering @code{BLK}
                   12229: The input stream is switched to that other block, at the same
                   12230: position. If the storing to @code{BLK} happens when interpreting
                   12231: non-block input, the system will get quite confused when the block ends.
                   12232: 
                   12233: @item no current block buffer for @code{UPDATE}:
                   12234: @cindex @code{UPDATE}, no current block buffer
                   12235: @code{UPDATE} has no effect.
                   12236: 
                   12237: @end table
                   12238: 
                   12239: @c ---------------------------------------------------------------------
                   12240: @node block-other,  , block-ambcond, The optional Block word set
                   12241: @subsection Other system documentation
                   12242: @c ---------------------------------------------------------------------
                   12243: @cindex other system documentation, block words
                   12244: @cindex block words, other system documentation
                   12245: 
                   12246: @table @i
                   12247: @item any restrictions a multiprogramming system places on the use of buffer addresses:
                   12248: No restrictions (yet).
                   12249: 
                   12250: @item the number of blocks available for source and data:
                   12251: depends on your disk space.
                   12252: 
                   12253: @end table
                   12254: 
                   12255: 
                   12256: @c =====================================================================
                   12257: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
                   12258: @section The optional Double Number word set
                   12259: @c =====================================================================
                   12260: @cindex system documentation, double words
                   12261: @cindex double words, system documentation
                   12262: 
                   12263: @menu
                   12264: * double-ambcond::              Ambiguous Conditions              
                   12265: @end menu
                   12266: 
                   12267: 
                   12268: @c ---------------------------------------------------------------------
                   12269: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
                   12270: @subsection Ambiguous conditions
                   12271: @c ---------------------------------------------------------------------
                   12272: @cindex double words, ambiguous conditions
                   12273: @cindex ambiguous conditions, double words
                   12274: 
                   12275: @table @i
1.29      crook    12276: @item @i{d} outside of range of @i{n} in @code{D>S}:
                   12277: @cindex @code{D>S}, @i{d} out of range of @i{n} 
                   12278: The least significant cell of @i{d} is produced.
1.1       anton    12279: 
                   12280: @end table
                   12281: 
                   12282: 
                   12283: @c =====================================================================
                   12284: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
                   12285: @section The optional Exception word set
                   12286: @c =====================================================================
                   12287: @cindex system documentation, exception words
                   12288: @cindex exception words, system documentation
                   12289: 
                   12290: @menu
                   12291: * exception-idef::              Implementation Defined Options              
                   12292: @end menu
                   12293: 
                   12294: 
                   12295: @c ---------------------------------------------------------------------
                   12296: @node exception-idef,  , The optional Exception word set, The optional Exception word set
                   12297: @subsection Implementation Defined Options
                   12298: @c ---------------------------------------------------------------------
                   12299: @cindex implementation-defined options, exception words
                   12300: @cindex exception words, implementation-defined options
                   12301: 
                   12302: @table @i
                   12303: @item @code{THROW}-codes used in the system:
                   12304: @cindex @code{THROW}-codes used in the system
                   12305: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29      crook    12306: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1       anton    12307: codes -512@minus{}-2047 are used for OS errors (for file and memory
                   12308: allocation operations). The mapping from OS error numbers to throw codes
                   12309: is -512@minus{}@code{errno}. One side effect of this mapping is that
                   12310: undefined OS errors produce a message with a strange number; e.g.,
                   12311: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
                   12312: @end table
                   12313: 
                   12314: @c =====================================================================
                   12315: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
                   12316: @section The optional Facility word set
                   12317: @c =====================================================================
                   12318: @cindex system documentation, facility words
                   12319: @cindex facility words, system documentation
                   12320: 
                   12321: @menu
                   12322: * facility-idef::               Implementation Defined Options               
                   12323: * facility-ambcond::            Ambiguous Conditions            
                   12324: @end menu
                   12325: 
                   12326: 
                   12327: @c ---------------------------------------------------------------------
                   12328: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
                   12329: @subsection Implementation Defined Options
                   12330: @c ---------------------------------------------------------------------
                   12331: @cindex implementation-defined options, facility words
                   12332: @cindex facility words, implementation-defined options
                   12333: 
                   12334: @table @i
                   12335: @item encoding of keyboard events (@code{EKEY}):
                   12336: @cindex keyboard events, encoding in @code{EKEY}
                   12337: @cindex @code{EKEY}, encoding of keyboard events
1.40      anton    12338: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41      anton    12339: Other keys are encoded with the constants @code{k-left}, @code{k-right},
                   12340: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
                   12341: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
                   12342: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40      anton    12343: 
1.1       anton    12344: 
                   12345: @item duration of a system clock tick:
                   12346: @cindex duration of a system clock tick
                   12347: @cindex clock tick duration
                   12348: System dependent. With respect to @code{MS}, the time is specified in
                   12349: microseconds. How well the OS and the hardware implement this, is
                   12350: another question.
                   12351: 
                   12352: @item repeatability to be expected from the execution of @code{MS}:
                   12353: @cindex repeatability to be expected from the execution of @code{MS}
                   12354: @cindex @code{MS}, repeatability to be expected
                   12355: System dependent. On Unix, a lot depends on load. If the system is
                   12356: lightly loaded, and the delay is short enough that Gforth does not get
                   12357: swapped out, the performance should be acceptable. Under MS-DOS and
                   12358: other single-tasking systems, it should be good.
                   12359: 
                   12360: @end table
                   12361: 
                   12362: 
                   12363: @c ---------------------------------------------------------------------
                   12364: @node facility-ambcond,  , facility-idef, The optional Facility word set
                   12365: @subsection Ambiguous conditions
                   12366: @c ---------------------------------------------------------------------
                   12367: @cindex facility words, ambiguous conditions
                   12368: @cindex ambiguous conditions, facility words
                   12369: 
                   12370: @table @i
                   12371: @item @code{AT-XY} can't be performed on user output device:
                   12372: @cindex @code{AT-XY} can't be performed on user output device
                   12373: Largely terminal dependent. No range checks are done on the arguments.
                   12374: No errors are reported. You may see some garbage appearing, you may see
                   12375: simply nothing happen.
                   12376: 
                   12377: @end table
                   12378: 
                   12379: 
                   12380: @c =====================================================================
                   12381: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
                   12382: @section The optional File-Access word set
                   12383: @c =====================================================================
                   12384: @cindex system documentation, file words
                   12385: @cindex file words, system documentation
                   12386: 
                   12387: @menu
                   12388: * file-idef::                   Implementation Defined Options
                   12389: * file-ambcond::                Ambiguous Conditions                
                   12390: @end menu
                   12391: 
                   12392: @c ---------------------------------------------------------------------
                   12393: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
                   12394: @subsection Implementation Defined Options
                   12395: @c ---------------------------------------------------------------------
                   12396: @cindex implementation-defined options, file words
                   12397: @cindex file words, implementation-defined options
                   12398: 
                   12399: @table @i
                   12400: @item file access methods used:
                   12401: @cindex file access methods used
                   12402: @code{R/O}, @code{R/W} and @code{BIN} work as you would
                   12403: expect. @code{W/O} translates into the C file opening mode @code{w} (or
                   12404: @code{wb}): The file is cleared, if it exists, and created, if it does
                   12405: not (with both @code{open-file} and @code{create-file}).  Under Unix
                   12406: @code{create-file} creates a file with 666 permissions modified by your
                   12407: umask.
                   12408: 
                   12409: @item file exceptions:
                   12410: @cindex file exceptions
                   12411: The file words do not raise exceptions (except, perhaps, memory access
                   12412: faults when you pass illegal addresses or file-ids).
                   12413: 
                   12414: @item file line terminator:
                   12415: @cindex file line terminator
                   12416: System-dependent. Gforth uses C's newline character as line
                   12417: terminator. What the actual character code(s) of this are is
                   12418: system-dependent.
                   12419: 
                   12420: @item file name format:
                   12421: @cindex file name format
                   12422: System dependent. Gforth just uses the file name format of your OS.
                   12423: 
                   12424: @item information returned by @code{FILE-STATUS}:
                   12425: @cindex @code{FILE-STATUS}, returned information
                   12426: @code{FILE-STATUS} returns the most powerful file access mode allowed
                   12427: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
                   12428: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
                   12429: along with the returned mode.
                   12430: 
                   12431: @item input file state after an exception when including source:
                   12432: @cindex exception when including source
                   12433: All files that are left via the exception are closed.
                   12434: 
1.29      crook    12435: @item @i{ior} values and meaning:
                   12436: @cindex @i{ior} values and meaning
                   12437: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    12438: intended as throw codes. They typically are in the range
                   12439: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    12440: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    12441: 
                   12442: @item maximum depth of file input nesting:
                   12443: @cindex maximum depth of file input nesting
                   12444: @cindex file input nesting, maximum depth
                   12445: limited by the amount of return stack, locals/TIB stack, and the number
                   12446: of open files available. This should not give you troubles.
                   12447: 
                   12448: @item maximum size of input line:
                   12449: @cindex maximum size of input line
                   12450: @cindex input line size, maximum
                   12451: @code{/line}. Currently 255.
                   12452: 
                   12453: @item methods of mapping block ranges to files:
                   12454: @cindex mapping block ranges to files
                   12455: @cindex files containing blocks
                   12456: @cindex blocks in files
                   12457: By default, blocks are accessed in the file @file{blocks.fb} in the
                   12458: current working directory. The file can be switched with @code{USE}.
                   12459: 
                   12460: @item number of string buffers provided by @code{S"}:
                   12461: @cindex @code{S"}, number of string buffers
                   12462: 1
                   12463: 
                   12464: @item size of string buffer used by @code{S"}:
                   12465: @cindex @code{S"}, size of string buffer
                   12466: @code{/line}. currently 255.
                   12467: 
                   12468: @end table
                   12469: 
                   12470: @c ---------------------------------------------------------------------
                   12471: @node file-ambcond,  , file-idef, The optional File-Access word set
                   12472: @subsection Ambiguous conditions
                   12473: @c ---------------------------------------------------------------------
                   12474: @cindex file words, ambiguous conditions
                   12475: @cindex ambiguous conditions, file words
                   12476: 
                   12477: @table @i
                   12478: @item attempting to position a file outside its boundaries:
                   12479: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
                   12480: @code{REPOSITION-FILE} is performed as usual: Afterwards,
                   12481: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
                   12482: 
                   12483: @item attempting to read from file positions not yet written:
                   12484: @cindex reading from file positions not yet written
                   12485: End-of-file, i.e., zero characters are read and no error is reported.
                   12486: 
1.29      crook    12487: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
                   12488: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
1.1       anton    12489: An appropriate exception may be thrown, but a memory fault or other
                   12490: problem is more probable.
                   12491: 
1.29      crook    12492: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
                   12493: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
                   12494: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
                   12495: The @i{ior} produced by the operation, that discovered the problem, is
1.1       anton    12496: thrown.
                   12497: 
                   12498: @item named file cannot be opened (@code{INCLUDED}):
                   12499: @cindex @code{INCLUDED}, named file cannot be opened
1.29      crook    12500: The @i{ior} produced by @code{open-file} is thrown.
1.1       anton    12501: 
                   12502: @item requesting an unmapped block number:
                   12503: @cindex unmapped block numbers
                   12504: There are no unmapped legal block numbers. On some operating systems,
                   12505: writing a block with a large number may overflow the file system and
                   12506: have an error message as consequence.
                   12507: 
                   12508: @item using @code{source-id} when @code{blk} is non-zero:
                   12509: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
                   12510: @code{source-id} performs its function. Typically it will give the id of
                   12511: the source which loaded the block. (Better ideas?)
                   12512: 
                   12513: @end table
                   12514: 
                   12515: 
                   12516: @c =====================================================================
                   12517: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
                   12518: @section The optional Floating-Point word set
                   12519: @c =====================================================================
                   12520: @cindex system documentation, floating-point words
                   12521: @cindex floating-point words, system documentation
                   12522: 
                   12523: @menu
                   12524: * floating-idef::               Implementation Defined Options
                   12525: * floating-ambcond::            Ambiguous Conditions            
                   12526: @end menu
                   12527: 
                   12528: 
                   12529: @c ---------------------------------------------------------------------
                   12530: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
                   12531: @subsection Implementation Defined Options
                   12532: @c ---------------------------------------------------------------------
                   12533: @cindex implementation-defined options, floating-point words
                   12534: @cindex floating-point words, implementation-defined options
                   12535: 
                   12536: @table @i
                   12537: @item format and range of floating point numbers:
                   12538: @cindex format and range of floating point numbers
                   12539: @cindex floating point numbers, format and range
                   12540: System-dependent; the @code{double} type of C.
                   12541: 
1.29      crook    12542: @item results of @code{REPRESENT} when @i{float} is out of range:
                   12543: @cindex  @code{REPRESENT}, results when @i{float} is out of range
1.1       anton    12544: System dependent; @code{REPRESENT} is implemented using the C library
                   12545: function @code{ecvt()} and inherits its behaviour in this respect.
                   12546: 
                   12547: @item rounding or truncation of floating-point numbers:
                   12548: @cindex rounding of floating-point numbers
                   12549: @cindex truncation of floating-point numbers
                   12550: @cindex floating-point numbers, rounding or truncation
                   12551: System dependent; the rounding behaviour is inherited from the hosting C
                   12552: compiler. IEEE-FP-based (i.e., most) systems by default round to
                   12553: nearest, and break ties by rounding to even (i.e., such that the last
                   12554: bit of the mantissa is 0).
                   12555: 
                   12556: @item size of floating-point stack:
                   12557: @cindex floating-point stack size
                   12558: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
                   12559: the floating-point stack (in floats). You can specify this on startup
                   12560: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
                   12561: 
                   12562: @item width of floating-point stack:
                   12563: @cindex floating-point stack width 
                   12564: @code{1 floats}.
                   12565: 
                   12566: @end table
                   12567: 
                   12568: 
                   12569: @c ---------------------------------------------------------------------
                   12570: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
                   12571: @subsection Ambiguous conditions
                   12572: @c ---------------------------------------------------------------------
                   12573: @cindex floating-point words, ambiguous conditions
                   12574: @cindex ambiguous conditions, floating-point words
                   12575: 
                   12576: @table @i
                   12577: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
                   12578: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
                   12579: System-dependent. Typically results in a @code{-23 THROW} like other
                   12580: alignment violations.
                   12581: 
                   12582: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
                   12583: @cindex @code{f@@} used with an address that is not float aligned
                   12584: @cindex @code{f!} used with an address that is not float aligned
                   12585: System-dependent. Typically results in a @code{-23 THROW} like other
                   12586: alignment violations.
                   12587: 
                   12588: @item floating-point result out of range:
                   12589: @cindex floating-point result out of range
                   12590: System-dependent. Can result in a @code{-55 THROW} (Floating-point
                   12591: unidentified fault), or can produce a special value representing, e.g.,
                   12592: Infinity.
                   12593: 
                   12594: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
                   12595: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
                   12596: System-dependent. Typically results in an alignment fault like other
                   12597: alignment violations.
                   12598: 
1.35      anton    12599: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
                   12600: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1       anton    12601: The floating-point number is converted into decimal nonetheless.
                   12602: 
                   12603: @item Both arguments are equal to zero (@code{FATAN2}):
                   12604: @cindex @code{FATAN2}, both arguments are equal to zero
                   12605: System-dependent. @code{FATAN2} is implemented using the C library
                   12606: function @code{atan2()}.
                   12607: 
1.29      crook    12608: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
                   12609: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
                   12610: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1       anton    12611: because of small errors and the tan will be a very large (or very small)
                   12612: but finite number.
                   12613: 
1.29      crook    12614: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
                   12615: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1       anton    12616: The result is rounded to the nearest float.
                   12617: 
                   12618: @item dividing by zero:
                   12619: @cindex dividing by zero, floating-point
                   12620: @cindex floating-point dividing by zero
                   12621: @cindex floating-point unidentified fault, FP divide-by-zero
                   12622: @code{-55 throw} (Floating-point unidentified fault)
                   12623: 
                   12624: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
                   12625: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
                   12626: System dependent. On IEEE-FP based systems the number is converted into
                   12627: an infinity.
                   12628: 
1.29      crook    12629: @item @i{float}<1 (@code{FACOSH}):
                   12630: @cindex @code{FACOSH}, @i{float}<1
1.1       anton    12631: @cindex floating-point unidentified fault, @code{FACOSH}
                   12632: @code{-55 throw} (Floating-point unidentified fault)
                   12633: 
1.29      crook    12634: @item @i{float}=<-1 (@code{FLNP1}):
                   12635: @cindex @code{FLNP1}, @i{float}=<-1
1.1       anton    12636: @cindex floating-point unidentified fault, @code{FLNP1}
                   12637: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29      crook    12638: negative infinity is typically produced for @i{float}=-1.
1.1       anton    12639: 
1.29      crook    12640: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
                   12641: @cindex @code{FLN}, @i{float}=<0
                   12642: @cindex @code{FLOG}, @i{float}=<0
1.1       anton    12643: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
                   12644: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29      crook    12645: negative infinity is typically produced for @i{float}=0.
1.1       anton    12646: 
1.29      crook    12647: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
                   12648: @cindex @code{FASINH}, @i{float}<0
                   12649: @cindex @code{FSQRT}, @i{float}<0
1.1       anton    12650: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
                   12651: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
                   12652: produces values for these inputs on my Linux box (Bug in the C library?)
                   12653: 
1.29      crook    12654: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
                   12655: @cindex @code{FACOS}, |@i{float}|>1
                   12656: @cindex @code{FASIN}, |@i{float}|>1
                   12657: @cindex @code{FATANH}, |@i{float}|>1
1.1       anton    12658: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
                   12659: @code{-55 throw} (Floating-point unidentified fault).
                   12660: 
1.29      crook    12661: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
                   12662: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1       anton    12663: @cindex floating-point unidentified fault, @code{F>D}
                   12664: @code{-55 throw} (Floating-point unidentified fault).
                   12665: 
                   12666: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
                   12667: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
                   12668: This does not happen.
                   12669: @end table
                   12670: 
                   12671: @c =====================================================================
                   12672: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
                   12673: @section The optional Locals word set
                   12674: @c =====================================================================
                   12675: @cindex system documentation, locals words
                   12676: @cindex locals words, system documentation
                   12677: 
                   12678: @menu
                   12679: * locals-idef::                 Implementation Defined Options                 
                   12680: * locals-ambcond::              Ambiguous Conditions              
                   12681: @end menu
                   12682: 
                   12683: 
                   12684: @c ---------------------------------------------------------------------
                   12685: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
                   12686: @subsection Implementation Defined Options
                   12687: @c ---------------------------------------------------------------------
                   12688: @cindex implementation-defined options, locals words
                   12689: @cindex locals words, implementation-defined options
                   12690: 
                   12691: @table @i
                   12692: @item maximum number of locals in a definition:
                   12693: @cindex maximum number of locals in a definition
                   12694: @cindex locals, maximum number in a definition
                   12695: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
                   12696: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
                   12697: characters. The number of locals in a definition is bounded by the size
                   12698: of locals-buffer, which contains the names of the locals.
                   12699: 
                   12700: @end table
                   12701: 
                   12702: 
                   12703: @c ---------------------------------------------------------------------
                   12704: @node locals-ambcond,  , locals-idef, The optional Locals word set
                   12705: @subsection Ambiguous conditions
                   12706: @c ---------------------------------------------------------------------
                   12707: @cindex locals words, ambiguous conditions
                   12708: @cindex ambiguous conditions, locals words
                   12709: 
                   12710: @table @i
                   12711: @item executing a named local in interpretation state:
                   12712: @cindex local in interpretation state
                   12713: @cindex Interpreting a compile-only word, for a local
                   12714: Locals have no interpretation semantics. If you try to perform the
                   12715: interpretation semantics, you will get a @code{-14 throw} somewhere
                   12716: (Interpreting a compile-only word). If you perform the compilation
                   12717: semantics, the locals access will be compiled (irrespective of state).
                   12718: 
1.29      crook    12719: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1       anton    12720: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
                   12721: @cindex @code{TO} on non-@code{VALUE}s and non-locals
                   12722: @cindex Invalid name argument, @code{TO}
                   12723: @code{-32 throw} (Invalid name argument)
                   12724: 
                   12725: @end table
                   12726: 
                   12727: 
                   12728: @c =====================================================================
                   12729: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
                   12730: @section The optional Memory-Allocation word set
                   12731: @c =====================================================================
                   12732: @cindex system documentation, memory-allocation words
                   12733: @cindex memory-allocation words, system documentation
                   12734: 
                   12735: @menu
                   12736: * memory-idef::                 Implementation Defined Options                 
                   12737: @end menu
                   12738: 
                   12739: 
                   12740: @c ---------------------------------------------------------------------
                   12741: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
                   12742: @subsection Implementation Defined Options
                   12743: @c ---------------------------------------------------------------------
                   12744: @cindex implementation-defined options, memory-allocation words
                   12745: @cindex memory-allocation words, implementation-defined options
                   12746: 
                   12747: @table @i
1.29      crook    12748: @item values and meaning of @i{ior}:
                   12749: @cindex  @i{ior} values and meaning
                   12750: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    12751: intended as throw codes. They typically are in the range
                   12752: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    12753: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    12754: 
                   12755: @end table
                   12756: 
                   12757: @c =====================================================================
                   12758: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
                   12759: @section The optional Programming-Tools word set
                   12760: @c =====================================================================
                   12761: @cindex system documentation, programming-tools words
                   12762: @cindex programming-tools words, system documentation
                   12763: 
                   12764: @menu
                   12765: * programming-idef::            Implementation Defined Options            
                   12766: * programming-ambcond::         Ambiguous Conditions         
                   12767: @end menu
                   12768: 
                   12769: 
                   12770: @c ---------------------------------------------------------------------
                   12771: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
                   12772: @subsection Implementation Defined Options
                   12773: @c ---------------------------------------------------------------------
                   12774: @cindex implementation-defined options, programming-tools words
                   12775: @cindex programming-tools words, implementation-defined options
                   12776: 
                   12777: @table @i
                   12778: @item ending sequence for input following @code{;CODE} and @code{CODE}:
                   12779: @cindex @code{;CODE} ending sequence
                   12780: @cindex @code{CODE} ending sequence
                   12781: @code{END-CODE}
                   12782: 
                   12783: @item manner of processing input following @code{;CODE} and @code{CODE}:
                   12784: @cindex @code{;CODE}, processing input
                   12785: @cindex @code{CODE}, processing input
                   12786: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
                   12787: the input is processed by the text interpreter, (starting) in interpret
                   12788: state.
                   12789: 
                   12790: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
                   12791: @cindex @code{ASSEMBLER}, search order capability
                   12792: The ANS Forth search order word set.
                   12793: 
                   12794: @item source and format of display by @code{SEE}:
                   12795: @cindex @code{SEE}, source and format of output
                   12796: The source for @code{see} is the intermediate code used by the inner
                   12797: interpreter.  The current @code{see} tries to output Forth source code
                   12798: as well as possible.
                   12799: 
                   12800: @end table
                   12801: 
                   12802: @c ---------------------------------------------------------------------
                   12803: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
                   12804: @subsection Ambiguous conditions
                   12805: @c ---------------------------------------------------------------------
                   12806: @cindex programming-tools words, ambiguous conditions
                   12807: @cindex ambiguous conditions, programming-tools words
                   12808: 
                   12809: @table @i
                   12810: 
1.21      crook    12811: @item deleting the compilation word list (@code{FORGET}):
                   12812: @cindex @code{FORGET}, deleting the compilation word list
1.1       anton    12813: Not implemented (yet).
                   12814: 
1.29      crook    12815: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
                   12816: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
                   12817: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1       anton    12818: @cindex control-flow stack underflow
                   12819: This typically results in an @code{abort"} with a descriptive error
                   12820: message (may change into a @code{-22 throw} (Control structure mismatch)
                   12821: in the future). You may also get a memory access error. If you are
                   12822: unlucky, this ambiguous condition is not caught.
                   12823: 
1.29      crook    12824: @item @i{name} can't be found (@code{FORGET}):
                   12825: @cindex @code{FORGET}, @i{name} can't be found
1.1       anton    12826: Not implemented (yet).
                   12827: 
1.29      crook    12828: @item @i{name} not defined via @code{CREATE}:
                   12829: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1       anton    12830: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
                   12831: the execution semantics of the last defined word no matter how it was
                   12832: defined.
                   12833: 
                   12834: @item @code{POSTPONE} applied to @code{[IF]}:
                   12835: @cindex @code{POSTPONE} applied to @code{[IF]}
                   12836: @cindex @code{[IF]} and @code{POSTPONE}
                   12837: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
                   12838: equivalent to @code{[IF]}.
                   12839: 
                   12840: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
                   12841: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
                   12842: Continue in the same state of conditional compilation in the next outer
                   12843: input source. Currently there is no warning to the user about this.
                   12844: 
                   12845: @item removing a needed definition (@code{FORGET}):
                   12846: @cindex @code{FORGET}, removing a needed definition
                   12847: Not implemented (yet).
                   12848: 
                   12849: @end table
                   12850: 
                   12851: 
                   12852: @c =====================================================================
                   12853: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
                   12854: @section The optional Search-Order word set
                   12855: @c =====================================================================
                   12856: @cindex system documentation, search-order words
                   12857: @cindex search-order words, system documentation
                   12858: 
                   12859: @menu
                   12860: * search-idef::                 Implementation Defined Options                 
                   12861: * search-ambcond::              Ambiguous Conditions              
                   12862: @end menu
                   12863: 
                   12864: 
                   12865: @c ---------------------------------------------------------------------
                   12866: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
                   12867: @subsection Implementation Defined Options
                   12868: @c ---------------------------------------------------------------------
                   12869: @cindex implementation-defined options, search-order words
                   12870: @cindex search-order words, implementation-defined options
                   12871: 
                   12872: @table @i
                   12873: @item maximum number of word lists in search order:
                   12874: @cindex maximum number of word lists in search order
                   12875: @cindex search order, maximum depth
                   12876: @code{s" wordlists" environment? drop .}. Currently 16.
                   12877: 
                   12878: @item minimum search order:
                   12879: @cindex minimum search order
                   12880: @cindex search order, minimum
                   12881: @code{root root}.
                   12882: 
                   12883: @end table
                   12884: 
                   12885: @c ---------------------------------------------------------------------
                   12886: @node search-ambcond,  , search-idef, The optional Search-Order word set
                   12887: @subsection Ambiguous conditions
                   12888: @c ---------------------------------------------------------------------
                   12889: @cindex search-order words, ambiguous conditions
                   12890: @cindex ambiguous conditions, search-order words
                   12891: 
                   12892: @table @i
1.21      crook    12893: @item changing the compilation word list (during compilation):
                   12894: @cindex changing the compilation word list (during compilation)
                   12895: @cindex compilation word list, change before definition ends
                   12896: The word is entered into the word list that was the compilation word list
1.1       anton    12897: at the start of the definition. Any changes to the name field (e.g.,
                   12898: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
                   12899: are applied to the latest defined word (as reported by @code{last} or
1.21      crook    12900: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1       anton    12901: 
                   12902: @item search order empty (@code{previous}):
                   12903: @cindex @code{previous}, search order empty
1.26      crook    12904: @cindex vocstack empty, @code{previous}
1.1       anton    12905: @code{abort" Vocstack empty"}.
                   12906: 
                   12907: @item too many word lists in search order (@code{also}):
                   12908: @cindex @code{also}, too many word lists in search order
1.26      crook    12909: @cindex vocstack full, @code{also}
1.1       anton    12910: @code{abort" Vocstack full"}.
                   12911: 
                   12912: @end table
                   12913: 
                   12914: @c ***************************************************************
                   12915: @node Model, Integrating Gforth, ANS conformance, Top
                   12916: @chapter Model
                   12917: 
                   12918: This chapter has yet to be written. It will contain information, on
                   12919: which internal structures you can rely.
                   12920: 
                   12921: @c ***************************************************************
                   12922: @node Integrating Gforth, Emacs and Gforth, Model, Top
                   12923: @chapter Integrating Gforth into C programs
                   12924: 
                   12925: This is not yet implemented.
                   12926: 
                   12927: Several people like to use Forth as scripting language for applications
                   12928: that are otherwise written in C, C++, or some other language.
                   12929: 
                   12930: The Forth system ATLAST provides facilities for embedding it into
                   12931: applications; unfortunately it has several disadvantages: most
                   12932: importantly, it is not based on ANS Forth, and it is apparently dead
                   12933: (i.e., not developed further and not supported). The facilities
1.21      crook    12934: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1       anton    12935: making the switch should not be hard.
                   12936: 
                   12937: We also tried to design the interface such that it can easily be
                   12938: implemented by other Forth systems, so that we may one day arrive at a
                   12939: standardized interface. Such a standard interface would allow you to
                   12940: replace the Forth system without having to rewrite C code.
                   12941: 
                   12942: You embed the Gforth interpreter by linking with the library
                   12943: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
                   12944: global symbols in this library that belong to the interface, have the
                   12945: prefix @code{forth_}. (Global symbols that are used internally have the
                   12946: prefix @code{gforth_}).
                   12947: 
                   12948: You can include the declarations of Forth types and the functions and
                   12949: variables of the interface with @code{#include <forth.h>}.
                   12950: 
                   12951: Types.
                   12952: 
                   12953: Variables.
                   12954: 
                   12955: Data and FP Stack pointer. Area sizes.
                   12956: 
                   12957: functions.
                   12958: 
                   12959: forth_init(imagefile)
                   12960: forth_evaluate(string) exceptions?
                   12961: forth_goto(address) (or forth_execute(xt)?)
                   12962: forth_continue() (a corountining mechanism)
                   12963: 
                   12964: Adding primitives.
                   12965: 
                   12966: No checking.
                   12967: 
                   12968: Signals?
                   12969: 
                   12970: Accessing the Stacks
                   12971: 
1.26      crook    12972: @c ******************************************************************
1.1       anton    12973: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
                   12974: @chapter Emacs and Gforth
                   12975: @cindex Emacs and Gforth
                   12976: 
                   12977: @cindex @file{gforth.el}
                   12978: @cindex @file{forth.el}
                   12979: @cindex Rydqvist, Goran
                   12980: @cindex comment editing commands
                   12981: @cindex @code{\}, editing with Emacs
                   12982: @cindex debug tracer editing commands
                   12983: @cindex @code{~~}, removal with Emacs
                   12984: @cindex Forth mode in Emacs
                   12985: Gforth comes with @file{gforth.el}, an improved version of
                   12986: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26      crook    12987: improvements are:
                   12988: 
                   12989: @itemize @bullet
                   12990: @item
                   12991: A better (but still not perfect) handling of indentation.
                   12992: @item
                   12993: Comment paragraph filling (@kbd{M-q})
                   12994: @item
                   12995: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
                   12996: @item
                   12997: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41      anton    12998: @item
                   12999: Support of the @code{info-lookup} feature for looking up the
                   13000: documentation of a word.
1.26      crook    13001: @end itemize
                   13002: 
                   13003: I left the stuff I do not use alone, even though some of it only makes
                   13004: sense for TILE. To get a description of these features, enter Forth mode
                   13005: and type @kbd{C-h m}.
1.1       anton    13006: 
                   13007: @cindex source location of error or debugging output in Emacs
                   13008: @cindex error output, finding the source location in Emacs
                   13009: @cindex debugging output, finding the source location in Emacs
                   13010: In addition, Gforth supports Emacs quite well: The source code locations
                   13011: given in error messages, debugging output (from @code{~~}) and failed
                   13012: assertion messages are in the right format for Emacs' compilation mode
                   13013: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
                   13014: Manual}) so the source location corresponding to an error or other
                   13015: message is only a few keystrokes away (@kbd{C-x `} for the next error,
                   13016: @kbd{C-c C-c} for the error under the cursor).
                   13017: 
                   13018: @cindex @file{TAGS} file
                   13019: @cindex @file{etags.fs}
                   13020: @cindex viewing the source of a word in Emacs
1.43      anton    13021: @cindex @code{require}, placement in files
                   13022: @cindex @code{include}, placement in files
                   13023: Also, if you @code{require} @file{etags.fs}, a new @file{TAGS} file will
1.26      crook    13024: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1       anton    13025: contains the definitions of all words defined afterwards. You can then
                   13026: find the source for a word using @kbd{M-.}. Note that emacs can use
                   13027: several tags files at the same time (e.g., one for the Gforth sources
                   13028: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
                   13029: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
                   13030: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43      anton    13031: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
                   13032: with @file{etags.fs}, you should avoid putting definitions both before
                   13033: and after @code{require} etc., otherwise you will see the same file
                   13034: visited several times by commands like @code{tags-search}.
1.1       anton    13035: 
1.41      anton    13036: @cindex viewing the documentation of a word in Emacs
                   13037: @cindex context-sensitive help
                   13038: Moreover, for words documented in this manual, you can look up the
                   13039: glossary entry quickly by using @kbd{C-h TAB}
                   13040: (@code{info-lookup-symbol}, see @pxref{Documentation, ,Documentation
                   13041: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
1.42      anton    13042: later and does not work for words containing @code{:}.
1.41      anton    13043: 
                   13044: 
1.1       anton    13045: @cindex @file{.emacs}
                   13046: To get all these benefits, add the following lines to your @file{.emacs}
                   13047: file:
                   13048: 
                   13049: @example
                   13050: (autoload 'forth-mode "gforth.el")
                   13051: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
                   13052: @end example
                   13053: 
1.26      crook    13054: @c ******************************************************************
1.1       anton    13055: @node Image Files, Engine, Emacs and Gforth, Top
                   13056: @chapter Image Files
1.26      crook    13057: @cindex image file
                   13058: @cindex @file{.fi} files
1.1       anton    13059: @cindex precompiled Forth code
                   13060: @cindex dictionary in persistent form
                   13061: @cindex persistent form of dictionary
                   13062: 
                   13063: An image file is a file containing an image of the Forth dictionary,
                   13064: i.e., compiled Forth code and data residing in the dictionary.  By
                   13065: convention, we use the extension @code{.fi} for image files.
                   13066: 
                   13067: @menu
1.18      anton    13068: * Image Licensing Issues::      Distribution terms for images.
                   13069: * Image File Background::       Why have image files?
1.29      crook    13070: * Non-Relocatable Image Files::   don't always work.
1.18      anton    13071: * Data-Relocatable Image Files::  are better.
1.29      crook    13072: * Fully Relocatable Image Files:: better yet.
1.18      anton    13073: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.29      crook    13074: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.18      anton    13075: * Modifying the Startup Sequence::  and turnkey applications.
1.1       anton    13076: @end menu
                   13077: 
1.18      anton    13078: @node Image Licensing Issues, Image File Background, Image Files, Image Files
                   13079: @section Image Licensing Issues
                   13080: @cindex license for images
                   13081: @cindex image license
                   13082: 
                   13083: An image created with @code{gforthmi} (@pxref{gforthmi}) or
                   13084: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
                   13085: original image; i.e., according to copyright law it is a derived work of
                   13086: the original image.
                   13087: 
                   13088: Since Gforth is distributed under the GNU GPL, the newly created image
                   13089: falls under the GNU GPL, too. In particular, this means that if you
                   13090: distribute the image, you have to make all of the sources for the image
                   13091: available, including those you wrote.  For details see @ref{License, ,
                   13092: GNU General Public License (Section 3)}.
                   13093: 
                   13094: If you create an image with @code{cross} (@pxref{cross.fs}), the image
                   13095: contains only code compiled from the sources you gave it; if none of
                   13096: these sources is under the GPL, the terms discussed above do not apply
                   13097: to the image. However, if your image needs an engine (a gforth binary)
                   13098: that is under the GPL, you should make sure that you distribute both in
                   13099: a way that is at most a @emph{mere aggregation}, if you don't want the
                   13100: terms of the GPL to apply to the image.
                   13101: 
                   13102: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1       anton    13103: @section Image File Background
                   13104: @cindex image file background
                   13105: 
                   13106: Our Forth system consists not only of primitives, but also of
                   13107: definitions written in Forth. Since the Forth compiler itself belongs to
                   13108: those definitions, it is not possible to start the system with the
                   13109: primitives and the Forth source alone. Therefore we provide the Forth
1.26      crook    13110: code as an image file in nearly executable form. When Gforth starts up,
                   13111: a C routine loads the image file into memory, optionally relocates the
                   13112: addresses, then sets up the memory (stacks etc.) according to
                   13113: information in the image file, and (finally) starts executing Forth
                   13114: code.
1.1       anton    13115: 
                   13116: The image file variants represent different compromises between the
                   13117: goals of making it easy to generate image files and making them
                   13118: portable.
                   13119: 
                   13120: @cindex relocation at run-time
1.26      crook    13121: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1       anton    13122: run-time. This avoids many of the complications discussed below (image
                   13123: files are data relocatable without further ado), but costs performance
                   13124: (one addition per memory access).
                   13125: 
                   13126: @cindex relocation at load-time
1.26      crook    13127: By contrast, the Gforth loader performs relocation at image load time. The
                   13128: loader also has to replace tokens that represent primitive calls with the
1.1       anton    13129: appropriate code-field addresses (or code addresses in the case of
                   13130: direct threading).
                   13131: 
                   13132: There are three kinds of image files, with different degrees of
                   13133: relocatability: non-relocatable, data-relocatable, and fully relocatable
                   13134: image files.
                   13135: 
                   13136: @cindex image file loader
                   13137: @cindex relocating loader
                   13138: @cindex loader for image files
                   13139: These image file variants have several restrictions in common; they are
                   13140: caused by the design of the image file loader:
                   13141: 
                   13142: @itemize @bullet
                   13143: @item
                   13144: There is only one segment; in particular, this means, that an image file
                   13145: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26      crook    13146: them). The contents of the stacks are not represented, either.
1.1       anton    13147: 
                   13148: @item
                   13149: The only kinds of relocation supported are: adding the same offset to
                   13150: all cells that represent data addresses; and replacing special tokens
                   13151: with code addresses or with pieces of machine code.
                   13152: 
                   13153: If any complex computations involving addresses are performed, the
                   13154: results cannot be represented in the image file. Several applications that
                   13155: use such computations come to mind:
                   13156: @itemize @minus
                   13157: @item
                   13158: Hashing addresses (or data structures which contain addresses) for table
                   13159: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
                   13160: purpose, you will have no problem, because the hash tables are
                   13161: recomputed automatically when the system is started. If you use your own
                   13162: hash tables, you will have to do something similar.
                   13163: 
                   13164: @item
                   13165: There's a cute implementation of doubly-linked lists that uses
                   13166: @code{XOR}ed addresses. You could represent such lists as singly-linked
                   13167: in the image file, and restore the doubly-linked representation on
                   13168: startup.@footnote{In my opinion, though, you should think thrice before
                   13169: using a doubly-linked list (whatever implementation).}
                   13170: 
                   13171: @item
                   13172: The code addresses of run-time routines like @code{docol:} cannot be
                   13173: represented in the image file (because their tokens would be replaced by
                   13174: machine code in direct threaded implementations). As a workaround,
                   13175: compute these addresses at run-time with @code{>code-address} from the
                   13176: executions tokens of appropriate words (see the definitions of
                   13177: @code{docol:} and friends in @file{kernel.fs}).
                   13178: 
                   13179: @item
                   13180: On many architectures addresses are represented in machine code in some
                   13181: shifted or mangled form. You cannot put @code{CODE} words that contain
                   13182: absolute addresses in this form in a relocatable image file. Workarounds
                   13183: are representing the address in some relative form (e.g., relative to
                   13184: the CFA, which is present in some register), or loading the address from
                   13185: a place where it is stored in a non-mangled form.
                   13186: @end itemize
                   13187: @end itemize
                   13188: 
                   13189: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
                   13190: @section Non-Relocatable Image Files
                   13191: @cindex non-relocatable image files
1.26      crook    13192: @cindex image file, non-relocatable
1.1       anton    13193: 
                   13194: These files are simple memory dumps of the dictionary. They are specific
                   13195: to the executable (i.e., @file{gforth} file) they were created
                   13196: with. What's worse, they are specific to the place on which the
                   13197: dictionary resided when the image was created. Now, there is no
                   13198: guarantee that the dictionary will reside at the same place the next
                   13199: time you start Gforth, so there's no guarantee that a non-relocatable
                   13200: image will work the next time (Gforth will complain instead of crashing,
                   13201: though).
                   13202: 
                   13203: You can create a non-relocatable image file with
                   13204: 
1.44      crook    13205: 
1.1       anton    13206: doc-savesystem
                   13207: 
1.44      crook    13208: 
1.1       anton    13209: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
                   13210: @section Data-Relocatable Image Files
                   13211: @cindex data-relocatable image files
1.26      crook    13212: @cindex image file, data-relocatable
1.1       anton    13213: 
                   13214: These files contain relocatable data addresses, but fixed code addresses
                   13215: (instead of tokens). They are specific to the executable (i.e.,
                   13216: @file{gforth} file) they were created with. For direct threading on some
                   13217: architectures (e.g., the i386), data-relocatable images do not work. You
                   13218: get a data-relocatable image, if you use @file{gforthmi} with a
                   13219: Gforth binary that is not doubly indirect threaded (@pxref{Fully
                   13220: Relocatable Image Files}).
                   13221: 
                   13222: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
                   13223: @section Fully Relocatable Image Files
                   13224: @cindex fully relocatable image files
1.26      crook    13225: @cindex image file, fully relocatable
1.1       anton    13226: 
                   13227: @cindex @file{kern*.fi}, relocatability
                   13228: @cindex @file{gforth.fi}, relocatability
                   13229: These image files have relocatable data addresses, and tokens for code
                   13230: addresses. They can be used with different binaries (e.g., with and
                   13231: without debugging) on the same machine, and even across machines with
                   13232: the same data formats (byte order, cell size, floating point
                   13233: format). However, they are usually specific to the version of Gforth
                   13234: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
                   13235: are fully relocatable.
                   13236: 
                   13237: There are two ways to create a fully relocatable image file:
                   13238: 
                   13239: @menu
1.29      crook    13240: * gforthmi::                    The normal way
1.1       anton    13241: * cross.fs::                    The hard way
                   13242: @end menu
                   13243: 
                   13244: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
                   13245: @subsection @file{gforthmi}
                   13246: @cindex @file{comp-i.fs}
                   13247: @cindex @file{gforthmi}
                   13248: 
                   13249: You will usually use @file{gforthmi}. If you want to create an
1.29      crook    13250: image @i{file} that contains everything you would load by invoking
                   13251: Gforth with @code{gforth @i{options}}, you simply say:
1.1       anton    13252: @example
1.29      crook    13253: gforthmi @i{file} @i{options}
1.1       anton    13254: @end example
                   13255: 
                   13256: E.g., if you want to create an image @file{asm.fi} that has the file
                   13257: @file{asm.fs} loaded in addition to the usual stuff, you could do it
                   13258: like this:
                   13259: 
                   13260: @example
                   13261: gforthmi asm.fi asm.fs
                   13262: @end example
                   13263: 
1.27      crook    13264: @file{gforthmi} is implemented as a sh script and works like this: It
                   13265: produces two non-relocatable images for different addresses and then
                   13266: compares them. Its output reflects this: first you see the output (if
                   13267: any) of the two Gforth invocations that produce the nonrelocatable image
                   13268: files, then you see the output of the comparing program: It displays the
                   13269: offset used for data addresses and the offset used for code addresses;
1.1       anton    13270: moreover, for each cell that cannot be represented correctly in the
1.44      crook    13271: image files, it displays a line like this:
1.1       anton    13272: 
                   13273: @example
                   13274:      78DC         BFFFFA50         BFFFFA40
                   13275: @end example
                   13276: 
                   13277: This means that at offset $78dc from @code{forthstart}, one input image
                   13278: contains $bffffa50, and the other contains $bffffa40. Since these cells
                   13279: cannot be represented correctly in the output image, you should examine
                   13280: these places in the dictionary and verify that these cells are dead
                   13281: (i.e., not read before they are written).
1.39      anton    13282: 
                   13283: @cindex --application, @code{gforthmi} option
                   13284: If you insert the option @code{--application} in front of the image file
                   13285: name, you will get an image that uses the @code{--appl-image} option
                   13286: instead of the @code{--image-file} option (@pxref{Invoking
                   13287: Gforth}). When you execute such an image on Unix (by typing the image
                   13288: name as command), the Gforth engine will pass all options to the image
                   13289: instead of trying to interpret them as engine options.
1.1       anton    13290: 
1.27      crook    13291: If you type @file{gforthmi} with no arguments, it prints some usage
                   13292: instructions.
                   13293: 
1.1       anton    13294: @cindex @code{savesystem} during @file{gforthmi}
                   13295: @cindex @code{bye} during @file{gforthmi}
                   13296: @cindex doubly indirect threaded code
1.44      crook    13297: @cindex environment variables
                   13298: @cindex @code{GFORTHD} -- environment variable
                   13299: @cindex @code{GFORTH} -- environment variable
1.1       anton    13300: @cindex @code{gforth-ditc}
1.29      crook    13301: There are a few wrinkles: After processing the passed @i{options}, the
1.1       anton    13302: words @code{savesystem} and @code{bye} must be visible. A special doubly
                   13303: indirect threaded version of the @file{gforth} executable is used for
                   13304: creating the nonrelocatable images; you can pass the exact filename of
                   13305: this executable through the environment variable @code{GFORTHD}
                   13306: (default: @file{gforth-ditc}); if you pass a version that is not doubly
                   13307: indirect threaded, you will not get a fully relocatable image, but a
1.27      crook    13308: data-relocatable image (because there is no code address offset). The
                   13309: normal @file{gforth} executable is used for creating the relocatable
                   13310: image; you can pass the exact filename of this executable through the
                   13311: environment variable @code{GFORTH}.
1.1       anton    13312: 
                   13313: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
                   13314: @subsection @file{cross.fs}
                   13315: @cindex @file{cross.fs}
                   13316: @cindex cross-compiler
                   13317: @cindex metacompiler
1.47      crook    13318: @cindex target compiler
1.1       anton    13319: 
                   13320: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47      crook    13321: programming language (@pxref{Cross Compiler}).
1.1       anton    13322: 
1.47      crook    13323: @code{cross} allows you to create image files for machines with
1.1       anton    13324: different data sizes and data formats than the one used for generating
                   13325: the image file. You can also use it to create an application image that
                   13326: does not contain a Forth compiler. These features are bought with
                   13327: restrictions and inconveniences in programming. E.g., addresses have to
                   13328: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
                   13329: order to make the code relocatable.
                   13330: 
                   13331: 
                   13332: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
                   13333: @section Stack and Dictionary Sizes
                   13334: @cindex image file, stack and dictionary sizes
                   13335: @cindex dictionary size default
                   13336: @cindex stack size default
                   13337: 
                   13338: If you invoke Gforth with a command line flag for the size
                   13339: (@pxref{Invoking Gforth}), the size you specify is stored in the
                   13340: dictionary. If you save the dictionary with @code{savesystem} or create
                   13341: an image with @file{gforthmi}, this size will become the default
                   13342: for the resulting image file. E.g., the following will create a
1.21      crook    13343: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1       anton    13344: 
                   13345: @example
                   13346: gforthmi gforth.fi -m 1M
                   13347: @end example
                   13348: 
                   13349: In other words, if you want to set the default size for the dictionary
                   13350: and the stacks of an image, just invoke @file{gforthmi} with the
                   13351: appropriate options when creating the image.
                   13352: 
                   13353: @cindex stack size, cache-friendly
                   13354: Note: For cache-friendly behaviour (i.e., good performance), you should
                   13355: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
                   13356: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
                   13357: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
                   13358: 
                   13359: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
                   13360: @section Running Image Files
                   13361: @cindex running image files
                   13362: @cindex invoking image files
                   13363: @cindex image file invocation
                   13364: 
                   13365: @cindex -i, invoke image file
                   13366: @cindex --image file, invoke image file
1.29      crook    13367: You can invoke Gforth with an image file @i{image} instead of the
1.1       anton    13368: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
                   13369: @example
1.29      crook    13370: gforth -i @i{image}
1.1       anton    13371: @end example
                   13372: 
                   13373: @cindex executable image file
1.26      crook    13374: @cindex image file, executable
1.1       anton    13375: If your operating system supports starting scripts with a line of the
                   13376: form @code{#! ...}, you just have to type the image file name to start
                   13377: Gforth with this image file (note that the file extension @code{.fi} is
1.29      crook    13378: just a convention). I.e., to run Gforth with the image file @i{image},
                   13379: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27      crook    13380: This works because every @code{.fi} file starts with a line of this
                   13381: format:
                   13382: 
                   13383: @example
                   13384: #! /usr/local/bin/gforth-0.4.0 -i
                   13385: @end example
                   13386: 
                   13387: The file and pathname for the Gforth engine specified on this line is
                   13388: the specific Gforth executable that it was built against; i.e. the value
                   13389: of the environment variable @code{GFORTH} at the time that
                   13390: @file{gforthmi} was executed.
1.1       anton    13391: 
1.27      crook    13392: You can make use of the same shell capability to make a Forth source
                   13393: file into an executable. For example, if you place this text in a file:
1.26      crook    13394: 
                   13395: @example
                   13396: #! /usr/local/bin/gforth
                   13397: 
                   13398: ." Hello, world" CR
                   13399: bye
                   13400: @end example
                   13401: 
                   13402: @noindent
1.27      crook    13403: and then make the file executable (chmod +x in Unix), you can run it
1.26      crook    13404: directly from the command line. The sequence @code{#!} is used in two
                   13405: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29      crook    13406: system@footnote{The Unix kernel actually recognises two types of files:
                   13407: executable files and files of data, where the data is processed by an
                   13408: interpreter that is specified on the ``interpreter line'' -- the first
                   13409: line of the file, starting with the sequence #!. There may be a small
                   13410: limit (e.g., 32) on the number of characters that may be specified on
                   13411: the interpreter line.} secondly it is treated as a comment character by
                   13412: Gforth. Because of the second usage, a space is required between
                   13413: @code{#!} and the path to the executable.
1.27      crook    13414: 
                   13415: The disadvantage of this latter technique, compared with using
                   13416: @file{gforthmi}, is that it is slower; the Forth source code is compiled
                   13417: on-the-fly, each time the program is invoked.
                   13418: 
1.26      crook    13419: 
1.1       anton    13420: doc-#!
                   13421: 
1.44      crook    13422: 
1.1       anton    13423: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
                   13424: @section Modifying the Startup Sequence
                   13425: @cindex startup sequence for image file
                   13426: @cindex image file initialization sequence
                   13427: @cindex initialization sequence of image file
                   13428: 
                   13429: You can add your own initialization to the startup sequence through the
1.26      crook    13430: deferred word @code{'cold}. @code{'cold} is invoked just before the
                   13431: image-specific command line processing (by default, loading files and
                   13432: evaluating (@code{-e}) strings) starts.
1.1       anton    13433: 
                   13434: A sequence for adding your initialization usually looks like this:
                   13435: 
                   13436: @example
                   13437: :noname
                   13438:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
                   13439:     ... \ your stuff
                   13440: ; IS 'cold
                   13441: @end example
                   13442: 
                   13443: @cindex turnkey image files
1.26      crook    13444: @cindex image file, turnkey applications
1.1       anton    13445: You can make a turnkey image by letting @code{'cold} execute a word
                   13446: (your turnkey application) that never returns; instead, it exits Gforth
                   13447: via @code{bye} or @code{throw}.
                   13448: 
                   13449: @cindex command-line arguments, access
                   13450: @cindex arguments on the command line, access
                   13451: You can access the (image-specific) command-line arguments through the
1.26      crook    13452: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1       anton    13453: access to @code{argv}.
                   13454: 
1.26      crook    13455: If @code{'cold} exits normally, Gforth processes the command-line
                   13456: arguments as files to be loaded and strings to be evaluated.  Therefore,
                   13457: @code{'cold} should remove the arguments it has used in this case.
                   13458: 
1.44      crook    13459: 
                   13460: 
1.26      crook    13461: doc-'cold
1.1       anton    13462: doc-argc
                   13463: doc-argv
                   13464: doc-arg
                   13465: 
                   13466: 
1.44      crook    13467: 
1.1       anton    13468: @c ******************************************************************
1.13      pazsan   13469: @node Engine, Binding to System Library, Image Files, Top
1.1       anton    13470: @chapter Engine
                   13471: @cindex engine
                   13472: @cindex virtual machine
                   13473: 
1.26      crook    13474: Reading this chapter is not necessary for programming with Gforth. It
1.1       anton    13475: may be helpful for finding your way in the Gforth sources.
                   13476: 
                   13477: The ideas in this section have also been published in the papers
                   13478: @cite{ANS fig/GNU/??? Forth} (in German) by Bernd Paysan, presented at
                   13479: the Forth-Tagung '93 and @cite{A Portable Forth Engine} by M. Anton
                   13480: Ertl, presented at EuroForth '93; the latter is available at
1.47      crook    13481: @*@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z}.
1.1       anton    13482: 
                   13483: @menu
                   13484: * Portability::                 
                   13485: * Threading::                   
                   13486: * Primitives::                  
                   13487: * Performance::                 
                   13488: @end menu
                   13489: 
                   13490: @node Portability, Threading, Engine, Engine
                   13491: @section Portability
                   13492: @cindex engine portability
                   13493: 
1.26      crook    13494: An important goal of the Gforth Project is availability across a wide
                   13495: range of personal machines. fig-Forth, and, to a lesser extent, F83,
                   13496: achieved this goal by manually coding the engine in assembly language
                   13497: for several then-popular processors. This approach is very
                   13498: labor-intensive and the results are short-lived due to progress in
                   13499: computer architecture.
1.1       anton    13500: 
                   13501: @cindex C, using C for the engine
                   13502: Others have avoided this problem by coding in C, e.g., Mitch Bradley
                   13503: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
                   13504: particularly popular for UNIX-based Forths due to the large variety of
                   13505: architectures of UNIX machines. Unfortunately an implementation in C
                   13506: does not mix well with the goals of efficiency and with using
                   13507: traditional techniques: Indirect or direct threading cannot be expressed
                   13508: in C, and switch threading, the fastest technique available in C, is
                   13509: significantly slower. Another problem with C is that it is very
                   13510: cumbersome to express double integer arithmetic.
                   13511: 
                   13512: @cindex GNU C for the engine
                   13513: @cindex long long
                   13514: Fortunately, there is a portable language that does not have these
                   13515: limitations: GNU C, the version of C processed by the GNU C compiler
                   13516: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
                   13517: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
                   13518: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
                   13519: threading possible, its @code{long long} type (@pxref{Long Long, ,
                   13520: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
                   13521: double numbers@footnote{Unfortunately, long longs are not implemented
                   13522: properly on all machines (e.g., on alpha-osf1, long longs are only 64
                   13523: bits, the same size as longs (and pointers), but they should be twice as
1.4       anton    13524: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1       anton    13525: C Manual}). So, we had to implement doubles in C after all. Still, on
                   13526: most machines we can use long longs and achieve better performance than
                   13527: with the emulation package.}. GNU C is available for free on all
                   13528: important (and many unimportant) UNIX machines, VMS, 80386s running
                   13529: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
                   13530: on all these machines.
                   13531: 
                   13532: Writing in a portable language has the reputation of producing code that
                   13533: is slower than assembly. For our Forth engine we repeatedly looked at
                   13534: the code produced by the compiler and eliminated most compiler-induced
                   13535: inefficiencies by appropriate changes in the source code.
                   13536: 
                   13537: @cindex explicit register declarations
                   13538: @cindex --enable-force-reg, configuration flag
                   13539: @cindex -DFORCE_REG
                   13540: However, register allocation cannot be portably influenced by the
                   13541: programmer, leading to some inefficiencies on register-starved
                   13542: machines. We use explicit register declarations (@pxref{Explicit Reg
                   13543: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
                   13544: improve the speed on some machines. They are turned on by using the
                   13545: configuration flag @code{--enable-force-reg} (@code{gcc} switch
                   13546: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
                   13547: machine, but also on the compiler version: On some machines some
                   13548: compiler versions produce incorrect code when certain explicit register
                   13549: declarations are used. So by default @code{-DFORCE_REG} is not used.
                   13550: 
                   13551: @node Threading, Primitives, Portability, Engine
                   13552: @section Threading
                   13553: @cindex inner interpreter implementation
                   13554: @cindex threaded code implementation
                   13555: 
                   13556: @cindex labels as values
                   13557: GNU C's labels as values extension (available since @code{gcc-2.0},
                   13558: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29      crook    13559: makes it possible to take the address of @i{label} by writing
                   13560: @code{&&@i{label}}.  This address can then be used in a statement like
                   13561: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1       anton    13562: @code{goto x}.
                   13563: 
1.26      crook    13564: @cindex @code{NEXT}, indirect threaded
1.1       anton    13565: @cindex indirect threaded inner interpreter
                   13566: @cindex inner interpreter, indirect threaded
1.26      crook    13567: With this feature an indirect threaded @code{NEXT} looks like:
1.1       anton    13568: @example
                   13569: cfa = *ip++;
                   13570: ca = *cfa;
                   13571: goto *ca;
                   13572: @end example
                   13573: @cindex instruction pointer
                   13574: For those unfamiliar with the names: @code{ip} is the Forth instruction
                   13575: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
                   13576: execution token and points to the code field of the next word to be
                   13577: executed; The @code{ca} (code address) fetched from there points to some
                   13578: executable code, e.g., a primitive or the colon definition handler
                   13579: @code{docol}.
                   13580: 
1.26      crook    13581: @cindex @code{NEXT}, direct threaded
1.1       anton    13582: @cindex direct threaded inner interpreter
                   13583: @cindex inner interpreter, direct threaded
                   13584: Direct threading is even simpler:
                   13585: @example
                   13586: ca = *ip++;
                   13587: goto *ca;
                   13588: @end example
                   13589: 
                   13590: Of course we have packaged the whole thing neatly in macros called
1.26      crook    13591: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1       anton    13592: 
                   13593: @menu
                   13594: * Scheduling::                  
                   13595: * Direct or Indirect Threaded?::  
                   13596: * DOES>::                       
                   13597: @end menu
                   13598: 
                   13599: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
                   13600: @subsection Scheduling
                   13601: @cindex inner interpreter optimization
                   13602: 
                   13603: There is a little complication: Pipelined and superscalar processors,
                   13604: i.e., RISC and some modern CISC machines can process independent
                   13605: instructions while waiting for the results of an instruction. The
                   13606: compiler usually reorders (schedules) the instructions in a way that
                   13607: achieves good usage of these delay slots. However, on our first tries
                   13608: the compiler did not do well on scheduling primitives. E.g., for
                   13609: @code{+} implemented as
                   13610: @example
                   13611: n=sp[0]+sp[1];
                   13612: sp++;
                   13613: sp[0]=n;
                   13614: NEXT;
                   13615: @end example
1.26      crook    13616: the @code{NEXT} comes strictly after the other code, i.e., there is nearly no
1.1       anton    13617: scheduling. After a little thought the problem becomes clear: The
1.21      crook    13618: compiler cannot know that @code{sp} and @code{ip} point to different
                   13619: addresses (and the version of @code{gcc} we used would not know it even
                   13620: if it was possible), so it could not move the load of the cfa above the
                   13621: store to the TOS. Indeed the pointers could be the same, if code on or
                   13622: very near the top of stack were executed. In the interest of speed we
                   13623: chose to forbid this probably unused ``feature'' and helped the compiler
1.26      crook    13624: in scheduling: @code{NEXT} is divided into the loading part (@code{NEXT_P1})
1.21      crook    13625: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
1.1       anton    13626: @example
                   13627: n=sp[0]+sp[1];
                   13628: sp++;
                   13629: NEXT_P1;
                   13630: sp[0]=n;
                   13631: NEXT_P2;
                   13632: @end example
                   13633: This can be scheduled optimally by the compiler.
                   13634: 
                   13635: This division can be turned off with the switch @code{-DCISC_NEXT}. This
                   13636: switch is on by default on machines that do not profit from scheduling
                   13637: (e.g., the 80386), in order to preserve registers.
                   13638: 
                   13639: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
                   13640: @subsection Direct or Indirect Threaded?
                   13641: @cindex threading, direct or indirect?
                   13642: 
                   13643: @cindex -DDIRECT_THREADED
                   13644: Both! After packaging the nasty details in macro definitions we
                   13645: realized that we could switch between direct and indirect threading by
                   13646: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
                   13647: defining a few machine-specific macros for the direct-threading case.
                   13648: On the Forth level we also offer access words that hide the
                   13649: differences between the threading methods (@pxref{Threading Words}).
                   13650: 
                   13651: Indirect threading is implemented completely machine-independently.
                   13652: Direct threading needs routines for creating jumps to the executable
1.21      crook    13653: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
                   13654: machine-dependent, but they do not amount to many source lines. Therefore,
                   13655: even porting direct threading to a new machine requires little effort.
1.1       anton    13656: 
                   13657: @cindex --enable-indirect-threaded, configuration flag
                   13658: @cindex --enable-direct-threaded, configuration flag
                   13659: The default threading method is machine-dependent. You can enforce a
                   13660: specific threading method when building Gforth with the configuration
                   13661: flag @code{--enable-direct-threaded} or
                   13662: @code{--enable-indirect-threaded}. Note that direct threading is not
                   13663: supported on all machines.
                   13664: 
                   13665: @node DOES>,  , Direct or Indirect Threaded?, Threading
                   13666: @subsection DOES>
                   13667: @cindex @code{DOES>} implementation
                   13668: 
1.26      crook    13669: @cindex @code{dodoes} routine
                   13670: @cindex @code{DOES>}-code
1.1       anton    13671: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
                   13672: the chunk of code executed by every word defined by a
                   13673: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
                   13674: the Forth code to be executed, i.e. the code after the
1.26      crook    13675: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
1.1       anton    13676: 
1.21      crook    13677: In fig-Forth the code field points directly to the @code{dodoes} and the
1.45      crook    13678: @code{DOES>}-code address is stored in the cell after the code address (i.e. at
1.29      crook    13679: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
1.1       anton    13680: the Forth-79 and all later standards, because in fig-Forth this address
                   13681: lies in the body (which is illegal in these standards). However, by
                   13682: making the code field larger for all words this solution becomes legal
                   13683: again. We use this approach for the indirect threaded version and for
                   13684: direct threading on some machines. Leaving a cell unused in most words
                   13685: is a bit wasteful, but on the machines we are targeting this is hardly a
                   13686: problem. The other reason for having a code field size of two cells is
                   13687: to avoid having different image files for direct and indirect threaded
                   13688: systems (direct threaded systems require two-cell code fields on many
                   13689: machines).
                   13690: 
1.26      crook    13691: @cindex @code{DOES>}-handler
1.1       anton    13692: The other approach is that the code field points or jumps to the cell
1.26      crook    13693: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
                   13694: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
                   13695: @code{DOES>}-code address by computing the code address, i.e., the address of
1.45      crook    13696: the jump to @code{dodoes}, and add the length of that jump field. A variant of
1.1       anton    13697: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
                   13698: return address (which can be found in the return register on RISCs) is
1.26      crook    13699: the @code{DOES>}-code address. Since the two cells available in the code field
1.1       anton    13700: are used up by the jump to the code address in direct threading on many
                   13701: architectures, we use this approach for direct threading on these
                   13702: architectures. We did not want to add another cell to the code field.
                   13703: 
                   13704: @node Primitives, Performance, Threading, Engine
                   13705: @section Primitives
                   13706: @cindex primitives, implementation
                   13707: @cindex virtual machine instructions, implementation
                   13708: 
                   13709: @menu
                   13710: * Automatic Generation::        
                   13711: * TOS Optimization::            
                   13712: * Produced code::               
                   13713: @end menu
                   13714: 
                   13715: @node Automatic Generation, TOS Optimization, Primitives, Primitives
                   13716: @subsection Automatic Generation
                   13717: @cindex primitives, automatic generation
                   13718: 
                   13719: @cindex @file{prims2x.fs}
                   13720: Since the primitives are implemented in a portable language, there is no
                   13721: longer any need to minimize the number of primitives. On the contrary,
                   13722: having many primitives has an advantage: speed. In order to reduce the
                   13723: number of errors in primitives and to make programming them easier, we
                   13724: provide a tool, the primitive generator (@file{prims2x.fs}), that
                   13725: automatically generates most (and sometimes all) of the C code for a
                   13726: primitive from the stack effect notation.  The source for a primitive
                   13727: has the following form:
                   13728: 
                   13729: @cindex primitive source format
                   13730: @format
1.58      anton    13731: @i{Forth-name}  ( @i{stack-effect} )        @i{category}    [@i{pronounc.}]
1.29      crook    13732: [@code{""}@i{glossary entry}@code{""}]
                   13733: @i{C code}
1.1       anton    13734: [@code{:}
1.29      crook    13735: @i{Forth code}]
1.1       anton    13736: @end format
                   13737: 
                   13738: The items in brackets are optional. The category and glossary fields
                   13739: are there for generating the documentation, the Forth code is there
                   13740: for manual implementations on machines without GNU C. E.g., the source
                   13741: for the primitive @code{+} is:
                   13742: @example
1.58      anton    13743: +    ( n1 n2 -- n )   core    plus
1.1       anton    13744: n = n1+n2;
                   13745: @end example
                   13746: 
                   13747: This looks like a specification, but in fact @code{n = n1+n2} is C
                   13748: code. Our primitive generation tool extracts a lot of information from
                   13749: the stack effect notations@footnote{We use a one-stack notation, even
                   13750: though we have separate data and floating-point stacks; The separate
                   13751: notation can be generated easily from the unified notation.}: The number
                   13752: of items popped from and pushed on the stack, their type, and by what
                   13753: name they are referred to in the C code. It then generates a C code
                   13754: prelude and postlude for each primitive. The final C code for @code{+}
                   13755: looks like this:
                   13756: 
                   13757: @example
1.46      pazsan   13758: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
1.1       anton    13759: /*  */                          /* documentation */
                   13760: @{
                   13761: DEF_CA                          /* definition of variable ca (indirect threading) */
                   13762: Cell n1;                        /* definitions of variables */
                   13763: Cell n2;
                   13764: Cell n;
                   13765: n1 = (Cell) sp[1];              /* input */
                   13766: n2 = (Cell) TOS;
                   13767: sp += 1;                        /* stack adjustment */
                   13768: NAME("+")                       /* debugging output (with -DDEBUG) */
                   13769: @{
                   13770: n = n1+n2;                      /* C code taken from the source */
                   13771: @}
                   13772: NEXT_P1;                        /* NEXT part 1 */
                   13773: TOS = (Cell)n;                  /* output */
                   13774: NEXT_P2;                        /* NEXT part 2 */
                   13775: @}
                   13776: @end example
                   13777: 
                   13778: This looks long and inefficient, but the GNU C compiler optimizes quite
                   13779: well and produces optimal code for @code{+} on, e.g., the R3000 and the
                   13780: HP RISC machines: Defining the @code{n}s does not produce any code, and
                   13781: using them as intermediate storage also adds no cost.
                   13782: 
1.26      crook    13783: There are also other optimizations that are not illustrated by this
                   13784: example: assignments between simple variables are usually for free (copy
1.1       anton    13785: propagation). If one of the stack items is not used by the primitive
                   13786: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
                   13787: (dead code elimination). On the other hand, there are some things that
                   13788: the compiler does not do, therefore they are performed by
                   13789: @file{prims2x.fs}: The compiler does not optimize code away that stores
                   13790: a stack item to the place where it just came from (e.g., @code{over}).
                   13791: 
                   13792: While programming a primitive is usually easy, there are a few cases
                   13793: where the programmer has to take the actions of the generator into
                   13794: account, most notably @code{?dup}, but also words that do not (always)
1.26      crook    13795: fall through to @code{NEXT}.
1.1       anton    13796: 
                   13797: @node TOS Optimization, Produced code, Automatic Generation, Primitives
                   13798: @subsection TOS Optimization
                   13799: @cindex TOS optimization for primitives
                   13800: @cindex primitives, keeping the TOS in a register
                   13801: 
                   13802: An important optimization for stack machine emulators, e.g., Forth
                   13803: engines, is keeping  one or more of the top stack items in
1.29      crook    13804: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
                   13805: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1       anton    13806: @itemize @bullet
                   13807: @item
1.29      crook    13808: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1       anton    13809: due to fewer loads from and stores to the stack.
1.29      crook    13810: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
                   13811: @i{y<n}, due to additional moves between registers.
1.1       anton    13812: @end itemize
                   13813: 
                   13814: @cindex -DUSE_TOS
                   13815: @cindex -DUSE_NO_TOS
                   13816: In particular, keeping one item in a register is never a disadvantage,
                   13817: if there are enough registers. Keeping two items in registers is a
                   13818: disadvantage for frequent words like @code{?branch}, constants,
                   13819: variables, literals and @code{i}. Therefore our generator only produces
                   13820: code that keeps zero or one items in registers. The generated C code
                   13821: covers both cases; the selection between these alternatives is made at
                   13822: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
                   13823: code for @code{+} is just a simple variable name in the one-item case,
                   13824: otherwise it is a macro that expands into @code{sp[0]}. Note that the
                   13825: GNU C compiler tries to keep simple variables like @code{TOS} in
                   13826: registers, and it usually succeeds, if there are enough registers.
                   13827: 
                   13828: @cindex -DUSE_FTOS
                   13829: @cindex -DUSE_NO_FTOS
                   13830: The primitive generator performs the TOS optimization for the
                   13831: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
                   13832: operations the benefit of this optimization is even larger:
                   13833: floating-point operations take quite long on most processors, but can be
                   13834: performed in parallel with other operations as long as their results are
                   13835: not used. If the FP-TOS is kept in a register, this works. If
                   13836: it is kept on the stack, i.e., in memory, the store into memory has to
                   13837: wait for the result of the floating-point operation, lengthening the
                   13838: execution time of the primitive considerably.
                   13839: 
                   13840: The TOS optimization makes the automatic generation of primitives a
                   13841: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
                   13842: @code{TOS} is not sufficient. There are some special cases to
                   13843: consider:
                   13844: @itemize @bullet
                   13845: @item In the case of @code{dup ( w -- w w )} the generator must not
                   13846: eliminate the store to the original location of the item on the stack,
                   13847: if the TOS optimization is turned on.
                   13848: @item Primitives with stack effects of the form @code{--}
1.29      crook    13849: @i{out1}...@i{outy} must store the TOS to the stack at the start.
                   13850: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1       anton    13851: must load the TOS from the stack at the end. But for the null stack
                   13852: effect @code{--} no stores or loads should be generated.
                   13853: @end itemize
                   13854: 
                   13855: @node Produced code,  , TOS Optimization, Primitives
                   13856: @subsection Produced code
                   13857: @cindex primitives, assembly code listing
                   13858: 
                   13859: @cindex @file{engine.s}
                   13860: To see what assembly code is produced for the primitives on your machine
                   13861: with your compiler and your flag settings, type @code{make engine.s} and
                   13862: look at the resulting file @file{engine.s}.
                   13863: 
                   13864: @node  Performance,  , Primitives, Engine
                   13865: @section Performance
                   13866: @cindex performance of some Forth interpreters
                   13867: @cindex engine performance
                   13868: @cindex benchmarking Forth systems
                   13869: @cindex Gforth performance
                   13870: 
                   13871: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
                   13872: impossible to write a significantly faster engine.
                   13873: 
                   13874: On register-starved machines like the 386 architecture processors
                   13875: improvements are possible, because @code{gcc} does not utilize the
                   13876: registers as well as a human, even with explicit register declarations;
                   13877: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
                   13878: and hand-tuned it for the 486; this system is 1.19 times faster on the
                   13879: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40      anton    13880: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
                   13881: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
                   13882: registers fit in real registers (and we can even afford to use the TOS
                   13883: optimization), resulting in a speedup of 1.14 on the sieve over the
                   13884: earlier results.
1.1       anton    13885: 
                   13886: @cindex Win32Forth performance
                   13887: @cindex NT Forth performance
                   13888: @cindex eforth performance
                   13889: @cindex ThisForth performance
                   13890: @cindex PFE performance
                   13891: @cindex TILE performance
1.40      anton    13892: The potential advantage of assembly language implementations
1.1       anton    13893: is not necessarily realized in complete Forth systems: We compared
1.40      anton    13894: Gforth-0.4.9 (direct threaded, compiled with @code{gcc-2.95.1} and
1.1       anton    13895: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
                   13896: 1994) and Eforth (with and without peephole (aka pinhole) optimization
                   13897: of the threaded code); all these systems were written in assembly
                   13898: language. We also compared Gforth with three systems written in C:
                   13899: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
                   13900: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
1.21      crook    13901: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
                   13902: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
1.1       anton    13903: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
                   13904: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
                   13905: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
                   13906: 486DX2/66 with similar memory performance under Windows NT. Marcel
                   13907: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
                   13908: added the peephole optimizer, ran the benchmarks and reported the
                   13909: results.
1.40      anton    13910: 
1.1       anton    13911: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
                   13912: matrix multiplication come from the Stanford integer benchmarks and have
                   13913: been translated into Forth by Martin Fraeman; we used the versions
                   13914: included in the TILE Forth package, but with bigger data set sizes; and
                   13915: a recursive Fibonacci number computation for benchmarking calling
                   13916: performance. The following table shows the time taken for the benchmarks
                   13917: scaled by the time taken by Gforth (in other words, it shows the speedup
                   13918: factor that Gforth achieved over the other systems).
                   13919: 
                   13920: @example
1.40      anton    13921: relative      Win32-    NT       eforth       This-      
1.1       anton    13922:   time  Gforth Forth Forth eforth  +opt   PFE Forth  TILE
1.40      anton    13923: sieve     1.00  1.58  1.30   1.58  0.97  1.80  3.63  9.79
                   13924: bubble    1.00  1.55  1.67   1.75  1.04  1.78        4.59
                   13925: matmul    1.00  1.67  1.53   1.66  0.84  1.79        4.63
                   13926: fib       1.00  1.75  1.53   1.40  0.99  1.99  3.43  4.93
1.1       anton    13927: @end example
                   13928: 
1.26      crook    13929: You may be quite surprised by the good performance of Gforth when
                   13930: compared with systems written in assembly language. One important reason
                   13931: for the disappointing performance of these other systems is probably
                   13932: that they are not written optimally for the 486 (e.g., they use the
                   13933: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
                   13934: but costly method for relocating the Forth image: like @code{cforth}, it
                   13935: computes the actual addresses at run time, resulting in two address
                   13936: computations per @code{NEXT} (@pxref{Image File Background}).
                   13937: 
1.40      anton    13938: Only Eforth with the peephole optimizer performs comparable to
                   13939: Gforth. The speedups achieved with peephole optimization of threaded
                   13940: code are quite remarkable. Adding a peephole optimizer to Gforth should
                   13941: cause similar speedups.
1.1       anton    13942: 
                   13943: The speedup of Gforth over PFE, ThisForth and TILE can be easily
                   13944: explained with the self-imposed restriction of the latter systems to
                   13945: standard C, which makes efficient threading impossible (however, the
1.4       anton    13946: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1       anton    13947: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
                   13948: Moreover, current C compilers have a hard time optimizing other aspects
                   13949: of the ThisForth and the TILE source.
                   13950: 
1.26      crook    13951: The performance of Gforth on 386 architecture processors varies widely
                   13952: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
                   13953: allocate any of the virtual machine registers into real machine
                   13954: registers by itself and would not work correctly with explicit register
1.40      anton    13955: declarations, giving a 1.5 times slower engine (on a 486DX2/66 running
1.26      crook    13956: the Sieve) than the one measured above.
1.1       anton    13957: 
1.26      crook    13958: Note that there have been several releases of Win32Forth since the
                   13959: release presented here, so the results presented above may have little
1.40      anton    13960: predictive value for the performance of Win32Forth today (results for
                   13961: the current release on an i486DX2/66 are welcome).
1.1       anton    13962: 
                   13963: @cindex @file{Benchres}
                   13964: In @cite{Translating Forth to Efficient C} by M. Anton Ertl and Martin
                   13965: Maierhofer (presented at EuroForth '95), an indirect threaded version of
                   13966: Gforth is compared with Win32Forth, NT Forth, PFE, and ThisForth; that
1.40      anton    13967: version of Gforth is slower on a 486 than the direct threaded version
                   13968: used here. The paper available at
1.47      crook    13969: @*@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz};
1.1       anton    13970: it also contains numbers for some native code systems. You can find a
                   13971: newer version of these measurements at
1.47      crook    13972: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1       anton    13973: find numbers for Gforth on various machines in @file{Benchres}.
                   13974: 
1.26      crook    13975: @c ******************************************************************
1.13      pazsan   13976: @node Binding to System Library, Cross Compiler, Engine, Top
1.14      pazsan   13977: @chapter Binding to System Library
1.13      pazsan   13978: 
                   13979: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14      pazsan   13980: @chapter Cross Compiler
1.47      crook    13981: @cindex @file{cross.fs}
                   13982: @cindex cross-compiler
                   13983: @cindex metacompiler
                   13984: @cindex target compiler
1.13      pazsan   13985: 
1.46      pazsan   13986: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
                   13987: mostly written in Forth, including crucial parts like the outer
                   13988: interpreter and compiler, it needs compiled Forth code to get
                   13989: started. The cross compiler allows to create new images for other
                   13990: architectures, even running under another Forth system.
1.13      pazsan   13991: 
                   13992: @menu
                   13993: * Using the Cross Compiler::
                   13994: * How the Cross Compiler Works::
                   13995: @end menu
                   13996: 
1.21      crook    13997: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14      pazsan   13998: @section Using the Cross Compiler
1.46      pazsan   13999: 
                   14000: The cross compiler uses a language that resembles Forth, but isn't. The
                   14001: main difference is that you can execute Forth code after definition,
                   14002: while you usually can't execute the code compiled by cross, because the
                   14003: code you are compiling is typically for a different computer than the
                   14004: one you are compiling on.
                   14005: 
                   14006: The Makefile is already set up to allow you to create kernels for new
                   14007: architectures with a simple make command. The generic kernels using the
                   14008: GCC compiled virtual machine are created in the normal build process
                   14009: with @code{make}. To create a embedded Gforth executable for e.g. the
                   14010: 8086 processor (running on a DOS machine), type
                   14011: 
                   14012: @example
                   14013: make kernl-8086.fi
                   14014: @end example
                   14015: 
                   14016: This will use the machine description from the @file{arch/8086}
                   14017: directory to create a new kernel. A machine file may look like that:
                   14018: 
                   14019: @example
                   14020: \ Parameter for target systems                         06oct92py
                   14021: 
                   14022:     4 Constant cell             \ cell size in bytes
                   14023:     2 Constant cell<<           \ cell shift to bytes
                   14024:     5 Constant cell>bit         \ cell shift to bits
                   14025:     8 Constant bits/char        \ bits per character
                   14026:     8 Constant bits/byte        \ bits per byte [default: 8]
                   14027:     8 Constant float            \ bytes per float
                   14028:     8 Constant /maxalign        \ maximum alignment in bytes
                   14029: false Constant bigendian        \ byte order
                   14030: ( true=big, false=little )
                   14031: 
                   14032: include machpc.fs               \ feature list
                   14033: @end example
                   14034: 
                   14035: This part is obligatory for the cross compiler itself, the feature list
                   14036: is used by the kernel to conditionally compile some features in and out,
                   14037: depending on whether the target supports these features.
                   14038: 
                   14039: There are some optional features, if you define your own primitives,
                   14040: have an assembler, or need special, nonstandard preparation to make the
                   14041: boot process work. @code{asm-include} include an assembler,
                   14042: @code{prims-include} includes primitives, and @code{>boot} prepares for
                   14043: booting.
                   14044: 
                   14045: @example
                   14046: : asm-include    ." Include assembler" cr
                   14047:   s" arch/8086/asm.fs" included ;
                   14048: 
                   14049: : prims-include  ." Include primitives" cr
                   14050:   s" arch/8086/prim.fs" included ;
                   14051: 
                   14052: : >boot          ." Prepare booting" cr
                   14053:   s" ' boot >body into-forth 1+ !" evaluate ;
                   14054: @end example
                   14055: 
                   14056: These words are used as sort of macro during the cross compilation in
                   14057: the file @file{kernel/main.fs}. Instead of using this macros, it would
                   14058: be possible --- but more complicated --- to write a new kernel project
                   14059: file, too.
                   14060: 
                   14061: @file{kernel/main.fs} expects the machine description file name on the
                   14062: stack; the cross compiler itself (@file{cross.fs}) assumes that either
                   14063: @code{mach-file} leaves a counted string on the stack, or
                   14064: @code{machine-file} leaves an address, count pair of the filename on the
                   14065: stack.
                   14066: 
                   14067: The feature list is typically controlled using @code{SetValue}, generic
                   14068: files that are used by several projects can use @code{DefaultValue}
                   14069: instead. Both functions work like @code{Value}, when the value isn't
                   14070: defined, but @code{SetValue} works like @code{to} if the value is
                   14071: defined, and @code{DefaultValue} doesn't set anything, if the value is
                   14072: defined.
                   14073: 
                   14074: @example
                   14075: \ generic mach file for pc gforth                       03sep97jaw
                   14076: 
                   14077: true DefaultValue NIL  \ relocating
                   14078: 
                   14079: >ENVIRON
                   14080: 
                   14081: true DefaultValue file          \ controls the presence of the
                   14082:                                 \ file access wordset
                   14083: true DefaultValue OS            \ flag to indicate a operating system
                   14084: 
                   14085: true DefaultValue prims         \ true: primitives are c-code
                   14086: 
                   14087: true DefaultValue floating      \ floating point wordset is present
                   14088: 
                   14089: true DefaultValue glocals       \ gforth locals are present
                   14090:                                 \ will be loaded
                   14091: true DefaultValue dcomps        \ double number comparisons
                   14092: 
                   14093: true DefaultValue hash          \ hashing primitives are loaded/present
                   14094: 
                   14095: true DefaultValue xconds        \ used together with glocals,
                   14096:                                 \ special conditionals supporting gforths'
                   14097:                                 \ local variables
                   14098: true DefaultValue header        \ save a header information
                   14099: 
                   14100: true DefaultValue backtrace     \ enables backtrace code
                   14101: 
                   14102: false DefaultValue ec
                   14103: false DefaultValue crlf
                   14104: 
                   14105: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
                   14106: 
                   14107: &16 KB          DefaultValue stack-size
                   14108: &15 KB &512 +   DefaultValue fstack-size
                   14109: &15 KB          DefaultValue rstack-size
                   14110: &14 KB &512 +   DefaultValue lstack-size
                   14111: @end example
1.13      pazsan   14112: 
1.48      anton    14113: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
1.14      pazsan   14114: @section How the Cross Compiler Works
1.13      pazsan   14115: 
                   14116: @node Bugs, Origin, Cross Compiler, Top
1.21      crook    14117: @appendix Bugs
1.1       anton    14118: @cindex bug reporting
                   14119: 
1.21      crook    14120: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1       anton    14121: 
                   14122: If you find a bug, please send a bug report to
1.33      anton    14123: @email{bug-gforth@@gnu.org}. A bug report should include this
1.21      crook    14124: information:
                   14125: 
                   14126: @itemize @bullet
                   14127: @item
                   14128: The Gforth version used (it is announced at the start of an
                   14129: interactive Gforth session).
                   14130: @item
                   14131: The machine and operating system (on Unix
                   14132: systems @code{uname -a} will report this information).
                   14133: @item
                   14134: The installation options (send the file @file{config.status}).
                   14135: @item
                   14136: A complete list of changes (if any) you (or your installer) have made to the
                   14137: Gforth sources.
                   14138: @item
                   14139: A program (or a sequence of keyboard commands) that reproduces the bug.
                   14140: @item
                   14141: A description of what you think constitutes the buggy behaviour.
                   14142: @end itemize
1.1       anton    14143: 
                   14144: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
                   14145: to Report Bugs, gcc.info, GNU C Manual}.
                   14146: 
                   14147: 
1.21      crook    14148: @node Origin, Forth-related information, Bugs, Top
                   14149: @appendix Authors and Ancestors of Gforth
1.1       anton    14150: 
                   14151: @section Authors and Contributors
                   14152: @cindex authors of Gforth
                   14153: @cindex contributors to Gforth
                   14154: 
                   14155: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
                   14156: Ertl. The third major author was Jens Wilke.  Lennart Benschop (who was
                   14157: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
                   14158: with their continuous feedback. Lennart Benshop contributed
                   14159: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
                   14160: support for calling C libraries. Helpful comments also came from Paul
                   14161: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.58      anton    14162: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, and
                   14163: Robert Epprecht. Since the release of Gforth-0.2.1 there were also
                   14164: helpful comments from many others; thank you all, sorry for not listing
                   14165: you here (but digging through my mailbox to extract your names is on my
                   14166: to-do list). Since the release of Gforth-0.4.0 Neal Crook worked on the
                   14167: manual.
1.1       anton    14168: 
                   14169: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
                   14170: and autoconf, among others), and to the creators of the Internet: Gforth
1.21      crook    14171: was developed across the Internet, and its authors did not meet
1.20      pazsan   14172: physically for the first 4 years of development.
1.1       anton    14173: 
                   14174: @section Pedigree
1.26      crook    14175: @cindex pedigree of Gforth
1.1       anton    14176: 
1.20      pazsan   14177: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
1.1       anton    14178: Dirk Zoller) will cross-fertilize each other. Of course, a significant
                   14179: part of the design of Gforth was prescribed by ANS Forth.
                   14180: 
1.20      pazsan   14181: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1       anton    14182: 32 bit native code version of VolksForth for the Atari ST, written
                   14183: mostly by Dietrich Weineck.
                   14184: 
                   14185: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
                   14186: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
                   14187: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
                   14188: 
                   14189: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
                   14190: Forth-83 standard. !! Pedigree? When?
                   14191: 
                   14192: A team led by Bill Ragsdale implemented fig-Forth on many processors in
                   14193: 1979. Robert Selzer and Bill Ragsdale developed the original
                   14194: implementation of fig-Forth for the 6502 based on microForth.
                   14195: 
                   14196: The principal architect of microForth was Dean Sanderson. microForth was
                   14197: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
                   14198: the 1802, and subsequently implemented on the 8080, the 6800 and the
                   14199: Z80.
                   14200: 
                   14201: All earlier Forth systems were custom-made, usually by Charles Moore,
                   14202: who discovered (as he puts it) Forth during the late 60s. The first full
                   14203: Forth existed in 1971.
                   14204: 
                   14205: A part of the information in this section comes from @cite{The Evolution
                   14206: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
                   14207: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
                   14208: Notices 28(3), 1993.  You can find more historical and genealogical
                   14209: information about Forth there.
                   14210: 
1.21      crook    14211: @node Forth-related information, Word Index, Origin, Top
                   14212: @appendix Other Forth-related information
                   14213: @cindex Forth-related information
                   14214: 
                   14215: @menu
                   14216: * Internet resources::
                   14217: * Books::
                   14218: * The Forth Interest Group::
                   14219: * Conferences::
                   14220: @end menu
                   14221: 
                   14222: 
                   14223: @node Internet resources, Books, Forth-related information, Forth-related information
                   14224: @section Internet resources
1.26      crook    14225: @cindex internet resources
1.21      crook    14226: 
                   14227: @cindex comp.lang.forth
                   14228: @cindex frequently asked questions
1.45      crook    14229: There is an active news group (comp.lang.forth) discussing Forth and
1.21      crook    14230: Forth-related issues. A frequently-asked-questions (FAQ) list
1.45      crook    14231: is posted to the news group regularly, and archived at these sites:
1.21      crook    14232: 
                   14233: @itemize @bullet
                   14234: @item
1.47      crook    14235: @uref{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
1.21      crook    14236: @item
1.47      crook    14237: @uref{ftp://ftp.forth.org/pub/Forth/FAQ/}
1.21      crook    14238: @end itemize
                   14239: 
                   14240: The FAQ list should be considered mandatory reading before posting to
1.45      crook    14241: the news group.
1.21      crook    14242: 
                   14243: Here are some other web sites holding Forth-related material:
                   14244: 
                   14245: @itemize @bullet
                   14246: @item
1.47      crook    14247: @uref{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
1.21      crook    14248: @item
1.47      crook    14249: @uref{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
1.21      crook    14250: @item
1.47      crook    14251: @uref{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
1.21      crook    14252: @item
1.47      crook    14253: @uref{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
1.21      crook    14254: Research page, including links to the Journal of Forth Application and
                   14255: Research (JFAR) and a searchable Forth bibliography.
                   14256: @end itemize
                   14257: 
                   14258: 
                   14259: @node Books, The Forth Interest Group, Internet resources, Forth-related information
                   14260: @section Books
1.26      crook    14261: @cindex books on Forth
1.21      crook    14262: 
                   14263: As the Standard is relatively new, there are not many books out yet. It
                   14264: is not recommended to learn Forth by using Gforth and a book that is not
                   14265: written for ANS Forth, as you will not know your mistakes from the
                   14266: deviations of the book. However, books based on the Forth-83 standard
                   14267: should be ok, because ANS Forth is primarily an extension of Forth-83.
1.44      crook    14268: Refer to the Forth FAQ for details of Forth-related books.
1.21      crook    14269: 
                   14270: @cindex standard document for ANS Forth
                   14271: @cindex ANS Forth document
                   14272: The definite reference if you want to write ANS Forth programs is, of
1.26      crook    14273: course, the ANS Forth document. It is available in printed form from the
1.21      crook    14274: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
                   14275: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
                   14276: $200. You can also get it from Global Engineering Documents (Tel.: USA
                   14277: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
                   14278: 
                   14279: @cite{dpANS6}, the last draft of the standard, which was then submitted
                   14280: to ANSI for publication is available electronically and for free in some
                   14281: MS Word format, and it has been converted to HTML
1.47      crook    14282: (@uref{http://www.taygeta.com/forth/dpans.html}; this HTML version also
1.44      crook    14283: includes the answers to Requests for Interpretation (RFIs). Some
                   14284: pointers to these versions can be found through
1.47      crook    14285: @*@uref{http://www.complang.tuwien.ac.at/projects/forth.html}.
1.44      crook    14286: 
1.21      crook    14287: 
                   14288: @node The Forth Interest Group, Conferences, Books, Forth-related information
                   14289: @section The Forth Interest Group
                   14290: @cindex Forth interest group (FIG)
                   14291: 
                   14292: The Forth Interest Group (FIG) is a world-wide, non-profit,
1.26      crook    14293: member-supported organisation. It publishes a regular magazine,
                   14294: @var{FORTH Dimensions}, and offers other benefits of membership. You can
                   14295: contact the FIG through their office email address:
                   14296: @email{office@@forth.org} or by visiting their web site at
1.47      crook    14297: @uref{http://www.forth.org/}. This web site also includes links to FIG
1.26      crook    14298: chapters in other countries and American cities
1.47      crook    14299: (@uref{http://www.forth.org/chapters.html}).
1.21      crook    14300: 
1.48      anton    14301: @node Conferences,  , The Forth Interest Group, Forth-related information
1.21      crook    14302: @section Conferences
                   14303: @cindex Conferences
                   14304: 
                   14305: There are several regular conferences related to Forth. They are all
1.26      crook    14306: well-publicised in @var{FORTH Dimensions} and on the comp.lang.forth
1.45      crook    14307: news group:
1.21      crook    14308: 
                   14309: @itemize @bullet
                   14310: @item
                   14311: FORML -- the Forth modification laboratory convenes every year near
                   14312: Monterey, California.
                   14313: @item
                   14314: The Rochester Forth Conference -- an annual conference traditionally
                   14315: held in Rochester, New York.
                   14316: @item
                   14317: EuroForth -- this European conference takes place annually.
                   14318: @end itemize
                   14319: 
                   14320: 
1.41      anton    14321: @node Word Index, Name Index, Forth-related information, Top
1.1       anton    14322: @unnumbered Word Index
                   14323: 
1.26      crook    14324: This index is a list of Forth words that have ``glossary'' entries
                   14325: within this manual. Each word is listed with its stack effect and
                   14326: wordset.
1.1       anton    14327: 
                   14328: @printindex fn
                   14329: 
1.41      anton    14330: @node Name Index, Concept Index, Word Index, Top
                   14331: @unnumbered Name Index
                   14332: 
                   14333: This index is a list of Forth words that have ``glossary'' entries
                   14334: within this manual.
                   14335: 
                   14336: @printindex ky
                   14337: 
                   14338: @node Concept Index,  , Name Index, Top
1.1       anton    14339: @unnumbered Concept and Word Index
                   14340: 
1.26      crook    14341: Not all entries listed in this index are present verbatim in the
                   14342: text. This index also duplicates, in abbreviated form, all of the words
                   14343: listed in the Word Index (only the names are listed for the words here).
1.1       anton    14344: 
                   14345: @printindex cp
                   14346: 
                   14347: @contents
                   14348: @bye
                   14349: 

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