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

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: 
                    312: Interpretation and Compilation Semantics
                    313: 
1.44      crook     314: * Combined words::
1.12      anton     315: 
1.21      crook     316: The Text Interpreter
                    317: 
1.29      crook     318: * Input Sources::
1.21      crook     319: * Number Conversion::
                    320: * Interpret/Compile states::
                    321: * Literals::
                    322: * Interpreter Directives::
                    323: 
1.26      crook     324: Word Lists
                    325: 
                    326: * Why use word lists?::
                    327: * Word list examples::
                    328: 
                    329: Files
                    330: 
1.48      anton     331: * Forth source files::          
                    332: * General files::               
                    333: * Search Paths::                
                    334: 
                    335: Search Paths
                    336: 
                    337: * Forth Search Paths::          
1.26      crook     338: * General Search Paths::        
                    339: 
                    340: Other I/O
                    341: 
1.32      anton     342: * Simple numeric output::       Predefined formats
                    343: * Formatted numeric output::    Formatted (pictured) output
                    344: * String Formats::              How Forth stores strings in memory
                    345: * Displaying characters and strings:: Other stuff
                    346: * Input::                       Input
1.26      crook     347: 
                    348: Programming Tools
                    349: 
                    350: * Debugging::                   Simple and quick.
                    351: * Assertions::                  Making your programs self-checking.
1.46      pazsan    352: * Singlestep Debugger::         Executing your program word by word.
1.26      crook     353: 
                    354: Locals
                    355: 
                    356: * Gforth locals::               
                    357: * ANS Forth locals::            
                    358: 
                    359: Gforth locals
                    360: 
                    361: * Where are locals visible by name?::  
                    362: * How long do locals live?::    
                    363: * Programming Style::           
                    364: * Implementation::              
                    365: 
1.12      anton     366: Structures
                    367: 
                    368: * Why explicit structure support?::  
                    369: * Structure Usage::             
                    370: * Structure Naming Convention::  
                    371: * Structure Implementation::    
                    372: * Structure Glossary::          
                    373: 
                    374: Object-oriented Forth
                    375: 
1.48      anton     376: * Why object-oriented programming?::  
                    377: * Object-Oriented Terminology::  
                    378: * Objects::                     
                    379: * OOF::                         
                    380: * Mini-OOF::                    
1.23      crook     381: * Comparison with other object models::  
1.12      anton     382: 
1.24      anton     383: The @file{objects.fs} model
1.12      anton     384: 
                    385: * Properties of the Objects model::  
                    386: * Basic Objects Usage::         
1.41      anton     387: * The Objects base class::      
1.12      anton     388: * Creating objects::            
                    389: * Object-Oriented Programming Style::  
                    390: * Class Binding::               
                    391: * Method conveniences::         
                    392: * Classes and Scoping::         
1.41      anton     393: * Dividing classes::            
1.12      anton     394: * Object Interfaces::           
                    395: * Objects Implementation::      
                    396: * Objects Glossary::            
                    397: 
1.24      anton     398: The @file{oof.fs} model
1.12      anton     399: 
                    400: * Properties of the OOF model::
                    401: * Basic OOF Usage::
1.23      crook     402: * The OOF base class::
1.12      anton     403: * Class Declaration::
                    404: * Class Implementation::
                    405: 
1.24      anton     406: The @file{mini-oof.fs} model
1.23      crook     407: 
1.48      anton     408: * Basic Mini-OOF Usage::        
                    409: * Mini-OOF Example::            
                    410: * Mini-OOF Implementation::     
                    411: * Comparison with other object models::  
1.23      crook     412: 
1.12      anton     413: Tools
                    414: 
                    415: * ANS Report::                  Report the words used, sorted by wordset.
                    416: 
                    417: ANS conformance
                    418: 
                    419: * The Core Words::              
                    420: * The optional Block word set::  
                    421: * The optional Double Number word set::  
                    422: * The optional Exception word set::  
                    423: * The optional Facility word set::  
                    424: * The optional File-Access word set::  
                    425: * The optional Floating-Point word set::  
                    426: * The optional Locals word set::  
                    427: * The optional Memory-Allocation word set::  
                    428: * The optional Programming-Tools word set::  
                    429: * The optional Search-Order word set::  
                    430: 
                    431: The Core Words
                    432: 
                    433: * core-idef::                   Implementation Defined Options                   
                    434: * core-ambcond::                Ambiguous Conditions                
                    435: * core-other::                  Other System Documentation                  
                    436: 
                    437: The optional Block word set
                    438: 
                    439: * block-idef::                  Implementation Defined Options
                    440: * block-ambcond::               Ambiguous Conditions               
                    441: * block-other::                 Other System Documentation                 
                    442: 
                    443: The optional Double Number word set
                    444: 
                    445: * double-ambcond::              Ambiguous Conditions              
                    446: 
                    447: The optional Exception word set
                    448: 
                    449: * exception-idef::              Implementation Defined Options              
                    450: 
                    451: The optional Facility word set
                    452: 
                    453: * facility-idef::               Implementation Defined Options               
                    454: * facility-ambcond::            Ambiguous Conditions            
                    455: 
                    456: The optional File-Access word set
                    457: 
                    458: * file-idef::                   Implementation Defined Options
                    459: * file-ambcond::                Ambiguous Conditions                
                    460: 
                    461: The optional Floating-Point word set
                    462: 
                    463: * floating-idef::               Implementation Defined Options
                    464: * floating-ambcond::            Ambiguous Conditions            
                    465: 
                    466: The optional Locals word set
                    467: 
                    468: * locals-idef::                 Implementation Defined Options                 
                    469: * locals-ambcond::              Ambiguous Conditions              
                    470: 
                    471: The optional Memory-Allocation word set
                    472: 
                    473: * memory-idef::                 Implementation Defined Options                 
                    474: 
                    475: The optional Programming-Tools word set
                    476: 
                    477: * programming-idef::            Implementation Defined Options            
                    478: * programming-ambcond::         Ambiguous Conditions         
                    479: 
                    480: The optional Search-Order word set
                    481: 
                    482: * search-idef::                 Implementation Defined Options                 
                    483: * search-ambcond::              Ambiguous Conditions              
                    484: 
                    485: Image Files
                    486: 
1.24      anton     487: * Image Licensing Issues::      Distribution terms for images.
                    488: * Image File Background::       Why have image files?
1.32      anton     489: * Non-Relocatable Image Files::   don't always work.
1.24      anton     490: * Data-Relocatable Image Files::  are better.
1.32      anton     491: * Fully Relocatable Image Files:: better yet.
1.24      anton     492: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.32      anton     493: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.24      anton     494: * Modifying the Startup Sequence::  and turnkey applications.
1.12      anton     495: 
                    496: Fully Relocatable Image Files
                    497: 
1.27      crook     498: * gforthmi::                    The normal way
1.12      anton     499: * cross.fs::                    The hard way
                    500: 
                    501: Engine
                    502: 
                    503: * Portability::                 
                    504: * Threading::                   
                    505: * Primitives::                  
                    506: * Performance::                 
                    507: 
                    508: Threading
                    509: 
                    510: * Scheduling::                  
                    511: * Direct or Indirect Threaded?::  
                    512: * DOES>::                       
                    513: 
                    514: Primitives
                    515: 
                    516: * Automatic Generation::        
                    517: * TOS Optimization::            
                    518: * Produced code::               
1.13      pazsan    519: 
                    520: Cross Compiler
                    521: 
                    522: * Using the Cross Compiler::
                    523: * How the Cross Compiler Works::
                    524: 
1.24      anton     525: Other Forth-related information
1.21      crook     526: 
                    527: * Internet resources::
                    528: * Books::
                    529: * The Forth Interest Group::
                    530: * Conferences::
                    531: 
1.24      anton     532: @end detailmenu
1.1       anton     533: @end menu
                    534: 
1.26      crook     535: @node License, Goals, Top, Top
1.1       anton     536: @unnumbered GNU GENERAL PUBLIC LICENSE
                    537: @center Version 2, June 1991
                    538: 
                    539: @display
                    540: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
                    541: 675 Mass Ave, Cambridge, MA 02139, USA
                    542: 
                    543: Everyone is permitted to copy and distribute verbatim copies
                    544: of this license document, but changing it is not allowed.
                    545: @end display
                    546: 
                    547: @unnumberedsec Preamble
                    548: 
                    549:   The licenses for most software are designed to take away your
                    550: freedom to share and change it.  By contrast, the GNU General Public
                    551: License is intended to guarantee your freedom to share and change free
                    552: software---to make sure the software is free for all its users.  This
                    553: General Public License applies to most of the Free Software
                    554: Foundation's software and to any other program whose authors commit to
                    555: using it.  (Some other Free Software Foundation software is covered by
                    556: the GNU Library General Public License instead.)  You can apply it to
                    557: your programs, too.
                    558: 
                    559:   When we speak of free software, we are referring to freedom, not
                    560: price.  Our General Public Licenses are designed to make sure that you
                    561: have the freedom to distribute copies of free software (and charge for
                    562: this service if you wish), that you receive source code or can get it
                    563: if you want it, that you can change the software or use pieces of it
                    564: in new free programs; and that you know you can do these things.
                    565: 
                    566:   To protect your rights, we need to make restrictions that forbid
                    567: anyone to deny you these rights or to ask you to surrender the rights.
                    568: These restrictions translate to certain responsibilities for you if you
                    569: distribute copies of the software, or if you modify it.
                    570: 
                    571:   For example, if you distribute copies of such a program, whether
                    572: gratis or for a fee, you must give the recipients all the rights that
                    573: you have.  You must make sure that they, too, receive or can get the
                    574: source code.  And you must show them these terms so they know their
                    575: rights.
                    576: 
                    577:   We protect your rights with two steps: (1) copyright the software, and
                    578: (2) offer you this license which gives you legal permission to copy,
                    579: distribute and/or modify the software.
                    580: 
                    581:   Also, for each author's protection and ours, we want to make certain
                    582: that everyone understands that there is no warranty for this free
                    583: software.  If the software is modified by someone else and passed on, we
                    584: want its recipients to know that what they have is not the original, so
                    585: that any problems introduced by others will not reflect on the original
                    586: authors' reputations.
                    587: 
                    588:   Finally, any free program is threatened constantly by software
                    589: patents.  We wish to avoid the danger that redistributors of a free
                    590: program will individually obtain patent licenses, in effect making the
                    591: program proprietary.  To prevent this, we have made it clear that any
                    592: patent must be licensed for everyone's free use or not licensed at all.
                    593: 
                    594:   The precise terms and conditions for copying, distribution and
                    595: modification follow.
                    596: 
                    597: @iftex
                    598: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
                    599: @end iftex
1.49      anton     600: @ifnottex
1.1       anton     601: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
1.49      anton     602: @end ifnottex
1.1       anton     603: 
                    604: @enumerate 0
                    605: @item
                    606: This License applies to any program or other work which contains
                    607: a notice placed by the copyright holder saying it may be distributed
                    608: under the terms of this General Public License.  The ``Program'', below,
                    609: refers to any such program or work, and a ``work based on the Program''
                    610: means either the Program or any derivative work under copyright law:
                    611: that is to say, a work containing the Program or a portion of it,
                    612: either verbatim or with modifications and/or translated into another
                    613: language.  (Hereinafter, translation is included without limitation in
                    614: the term ``modification''.)  Each licensee is addressed as ``you''.
                    615: 
                    616: Activities other than copying, distribution and modification are not
                    617: covered by this License; they are outside its scope.  The act of
                    618: running the Program is not restricted, and the output from the Program
                    619: is covered only if its contents constitute a work based on the
                    620: Program (independent of having been made by running the Program).
                    621: Whether that is true depends on what the Program does.
                    622: 
                    623: @item
                    624: You may copy and distribute verbatim copies of the Program's
                    625: source code as you receive it, in any medium, provided that you
                    626: conspicuously and appropriately publish on each copy an appropriate
                    627: copyright notice and disclaimer of warranty; keep intact all the
                    628: notices that refer to this License and to the absence of any warranty;
                    629: and give any other recipients of the Program a copy of this License
                    630: along with the Program.
                    631: 
                    632: You may charge a fee for the physical act of transferring a copy, and
                    633: you may at your option offer warranty protection in exchange for a fee.
                    634: 
                    635: @item
                    636: You may modify your copy or copies of the Program or any portion
                    637: of it, thus forming a work based on the Program, and copy and
                    638: distribute such modifications or work under the terms of Section 1
                    639: above, provided that you also meet all of these conditions:
                    640: 
                    641: @enumerate a
                    642: @item
                    643: You must cause the modified files to carry prominent notices
                    644: stating that you changed the files and the date of any change.
                    645: 
                    646: @item
                    647: You must cause any work that you distribute or publish, that in
                    648: whole or in part contains or is derived from the Program or any
                    649: part thereof, to be licensed as a whole at no charge to all third
                    650: parties under the terms of this License.
                    651: 
                    652: @item
                    653: If the modified program normally reads commands interactively
                    654: when run, you must cause it, when started running for such
                    655: interactive use in the most ordinary way, to print or display an
                    656: announcement including an appropriate copyright notice and a
                    657: notice that there is no warranty (or else, saying that you provide
                    658: a warranty) and that users may redistribute the program under
                    659: these conditions, and telling the user how to view a copy of this
                    660: License.  (Exception: if the Program itself is interactive but
                    661: does not normally print such an announcement, your work based on
                    662: the Program is not required to print an announcement.)
                    663: @end enumerate
                    664: 
                    665: These requirements apply to the modified work as a whole.  If
                    666: identifiable sections of that work are not derived from the Program,
                    667: and can be reasonably considered independent and separate works in
                    668: themselves, then this License, and its terms, do not apply to those
                    669: sections when you distribute them as separate works.  But when you
                    670: distribute the same sections as part of a whole which is a work based
                    671: on the Program, the distribution of the whole must be on the terms of
                    672: this License, whose permissions for other licensees extend to the
                    673: entire whole, and thus to each and every part regardless of who wrote it.
                    674: 
                    675: Thus, it is not the intent of this section to claim rights or contest
                    676: your rights to work written entirely by you; rather, the intent is to
                    677: exercise the right to control the distribution of derivative or
                    678: collective works based on the Program.
                    679: 
                    680: In addition, mere aggregation of another work not based on the Program
                    681: with the Program (or with a work based on the Program) on a volume of
                    682: a storage or distribution medium does not bring the other work under
                    683: the scope of this License.
                    684: 
                    685: @item
                    686: You may copy and distribute the Program (or a work based on it,
                    687: under Section 2) in object code or executable form under the terms of
                    688: Sections 1 and 2 above provided that you also do one of the following:
                    689: 
                    690: @enumerate a
                    691: @item
                    692: Accompany it with the complete corresponding machine-readable
                    693: source code, which must be distributed under the terms of Sections
                    694: 1 and 2 above on a medium customarily used for software interchange; or,
                    695: 
                    696: @item
                    697: Accompany it with a written offer, valid for at least three
                    698: years, to give any third party, for a charge no more than your
                    699: cost of physically performing source distribution, a complete
                    700: machine-readable copy of the corresponding source code, to be
                    701: distributed under the terms of Sections 1 and 2 above on a medium
                    702: customarily used for software interchange; or,
                    703: 
                    704: @item
                    705: Accompany it with the information you received as to the offer
                    706: to distribute corresponding source code.  (This alternative is
                    707: allowed only for noncommercial distribution and only if you
                    708: received the program in object code or executable form with such
                    709: an offer, in accord with Subsection b above.)
                    710: @end enumerate
                    711: 
                    712: The source code for a work means the preferred form of the work for
                    713: making modifications to it.  For an executable work, complete source
                    714: code means all the source code for all modules it contains, plus any
                    715: associated interface definition files, plus the scripts used to
                    716: control compilation and installation of the executable.  However, as a
                    717: special exception, the source code distributed need not include
                    718: anything that is normally distributed (in either source or binary
                    719: form) with the major components (compiler, kernel, and so on) of the
                    720: operating system on which the executable runs, unless that component
                    721: itself accompanies the executable.
                    722: 
                    723: If distribution of executable or object code is made by offering
                    724: access to copy from a designated place, then offering equivalent
                    725: access to copy the source code from the same place counts as
                    726: distribution of the source code, even though third parties are not
                    727: compelled to copy the source along with the object code.
                    728: 
                    729: @item
                    730: You may not copy, modify, sublicense, or distribute the Program
                    731: except as expressly provided under this License.  Any attempt
                    732: otherwise to copy, modify, sublicense or distribute the Program is
                    733: void, and will automatically terminate your rights under this License.
                    734: However, parties who have received copies, or rights, from you under
                    735: this License will not have their licenses terminated so long as such
                    736: parties remain in full compliance.
                    737: 
                    738: @item
                    739: You are not required to accept this License, since you have not
                    740: signed it.  However, nothing else grants you permission to modify or
                    741: distribute the Program or its derivative works.  These actions are
                    742: prohibited by law if you do not accept this License.  Therefore, by
                    743: modifying or distributing the Program (or any work based on the
                    744: Program), you indicate your acceptance of this License to do so, and
                    745: all its terms and conditions for copying, distributing or modifying
                    746: the Program or works based on it.
                    747: 
                    748: @item
                    749: Each time you redistribute the Program (or any work based on the
                    750: Program), the recipient automatically receives a license from the
                    751: original licensor to copy, distribute or modify the Program subject to
                    752: these terms and conditions.  You may not impose any further
                    753: restrictions on the recipients' exercise of the rights granted herein.
                    754: You are not responsible for enforcing compliance by third parties to
                    755: this License.
                    756: 
                    757: @item
                    758: If, as a consequence of a court judgment or allegation of patent
                    759: infringement or for any other reason (not limited to patent issues),
                    760: conditions are imposed on you (whether by court order, agreement or
                    761: otherwise) that contradict the conditions of this License, they do not
                    762: excuse you from the conditions of this License.  If you cannot
                    763: distribute so as to satisfy simultaneously your obligations under this
                    764: License and any other pertinent obligations, then as a consequence you
                    765: may not distribute the Program at all.  For example, if a patent
                    766: license would not permit royalty-free redistribution of the Program by
                    767: all those who receive copies directly or indirectly through you, then
                    768: the only way you could satisfy both it and this License would be to
                    769: refrain entirely from distribution of the Program.
                    770: 
                    771: If any portion of this section is held invalid or unenforceable under
                    772: any particular circumstance, the balance of the section is intended to
                    773: apply and the section as a whole is intended to apply in other
                    774: circumstances.
                    775: 
                    776: It is not the purpose of this section to induce you to infringe any
                    777: patents or other property right claims or to contest validity of any
                    778: such claims; this section has the sole purpose of protecting the
                    779: integrity of the free software distribution system, which is
                    780: implemented by public license practices.  Many people have made
                    781: generous contributions to the wide range of software distributed
                    782: through that system in reliance on consistent application of that
                    783: system; it is up to the author/donor to decide if he or she is willing
                    784: to distribute software through any other system and a licensee cannot
                    785: impose that choice.
                    786: 
                    787: This section is intended to make thoroughly clear what is believed to
                    788: be a consequence of the rest of this License.
                    789: 
                    790: @item
                    791: If the distribution and/or use of the Program is restricted in
                    792: certain countries either by patents or by copyrighted interfaces, the
                    793: original copyright holder who places the Program under this License
                    794: may add an explicit geographical distribution limitation excluding
                    795: those countries, so that distribution is permitted only in or among
                    796: countries not thus excluded.  In such case, this License incorporates
                    797: the limitation as if written in the body of this License.
                    798: 
                    799: @item
                    800: The Free Software Foundation may publish revised and/or new versions
                    801: of the General Public License from time to time.  Such new versions will
                    802: be similar in spirit to the present version, but may differ in detail to
                    803: address new problems or concerns.
                    804: 
                    805: Each version is given a distinguishing version number.  If the Program
                    806: specifies a version number of this License which applies to it and ``any
                    807: later version'', you have the option of following the terms and conditions
                    808: either of that version or of any later version published by the Free
                    809: Software Foundation.  If the Program does not specify a version number of
                    810: this License, you may choose any version ever published by the Free Software
                    811: Foundation.
                    812: 
                    813: @item
                    814: If you wish to incorporate parts of the Program into other free
                    815: programs whose distribution conditions are different, write to the author
                    816: to ask for permission.  For software which is copyrighted by the Free
                    817: Software Foundation, write to the Free Software Foundation; we sometimes
                    818: make exceptions for this.  Our decision will be guided by the two goals
                    819: of preserving the free status of all derivatives of our free software and
                    820: of promoting the sharing and reuse of software generally.
                    821: 
                    822: @iftex
                    823: @heading NO WARRANTY
                    824: @end iftex
1.49      anton     825: @ifnottex
1.1       anton     826: @center NO WARRANTY
1.49      anton     827: @end ifnottex
1.1       anton     828: 
                    829: @item
                    830: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
                    831: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
                    832: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
                    833: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
                    834: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
                    835: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
                    836: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
                    837: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
                    838: REPAIR OR CORRECTION.
                    839: 
                    840: @item
                    841: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
                    842: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
                    843: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
                    844: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
                    845: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
                    846: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
                    847: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
                    848: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
                    849: POSSIBILITY OF SUCH DAMAGES.
                    850: @end enumerate
                    851: 
                    852: @iftex
                    853: @heading END OF TERMS AND CONDITIONS
                    854: @end iftex
1.49      anton     855: @ifnottex
1.1       anton     856: @center END OF TERMS AND CONDITIONS
1.49      anton     857: @end ifnottex
1.1       anton     858: 
                    859: @page
                    860: @unnumberedsec How to Apply These Terms to Your New Programs
                    861: 
                    862:   If you develop a new program, and you want it to be of the greatest
                    863: possible use to the public, the best way to achieve this is to make it
                    864: free software which everyone can redistribute and change under these terms.
                    865: 
                    866:   To do so, attach the following notices to the program.  It is safest
                    867: to attach them to the start of each source file to most effectively
                    868: convey the exclusion of warranty; and each file should have at least
                    869: the ``copyright'' line and a pointer to where the full notice is found.
                    870: 
                    871: @smallexample
                    872: @var{one line to give the program's name and a brief idea of what it does.}
                    873: Copyright (C) 19@var{yy}  @var{name of author}
                    874: 
                    875: This program is free software; you can redistribute it and/or modify 
                    876: it under the terms of the GNU General Public License as published by 
                    877: the Free Software Foundation; either version 2 of the License, or 
                    878: (at your option) any later version.
                    879: 
                    880: This program is distributed in the hope that it will be useful,
                    881: but WITHOUT ANY WARRANTY; without even the implied warranty of
                    882: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                    883: GNU General Public License for more details.
                    884: 
                    885: You should have received a copy of the GNU General Public License
                    886: along with this program; if not, write to the Free Software
                    887: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
                    888: @end smallexample
                    889: 
                    890: Also add information on how to contact you by electronic and paper mail.
                    891: 
                    892: If the program is interactive, make it output a short notice like this
                    893: when it starts in an interactive mode:
                    894: 
                    895: @smallexample
                    896: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
                    897: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
                    898: type `show w'.  
                    899: This is free software, and you are welcome to redistribute it 
                    900: under certain conditions; type `show c' for details.
                    901: @end smallexample
                    902: 
                    903: The hypothetical commands @samp{show w} and @samp{show c} should show
                    904: the appropriate parts of the General Public License.  Of course, the
                    905: commands you use may be called something other than @samp{show w} and
                    906: @samp{show c}; they could even be mouse-clicks or menu items---whatever
                    907: suits your program.
                    908: 
                    909: You should also get your employer (if you work as a programmer) or your
                    910: school, if any, to sign a ``copyright disclaimer'' for the program, if
                    911: necessary.  Here is a sample; alter the names:
                    912: 
                    913: @smallexample
                    914: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
                    915: `Gnomovision' (which makes passes at compilers) written by James Hacker.
                    916: 
                    917: @var{signature of Ty Coon}, 1 April 1989
                    918: Ty Coon, President of Vice
                    919: @end smallexample
                    920: 
                    921: This General Public License does not permit incorporating your program into
                    922: proprietary programs.  If your program is a subroutine library, you may
                    923: consider it more useful to permit linking proprietary applications with the
                    924: library.  If this is what you want to do, use the GNU Library General
                    925: Public License instead of this License.
                    926: 
                    927: @iftex
                    928: @unnumbered Preface
                    929: @cindex Preface
1.21      crook     930: This manual documents Gforth. Some introductory material is provided for
                    931: readers who are unfamiliar with Forth or who are migrating to Gforth
                    932: from other Forth compilers. However, this manual is primarily a
                    933: reference manual.
1.1       anton     934: @end iftex
                    935: 
1.28      crook     936: @comment TODO much more blurb here.
1.26      crook     937: 
                    938: @c ******************************************************************
1.29      crook     939: @node Goals, Gforth Environment, License, Top
1.26      crook     940: @comment node-name,     next,           previous, up
                    941: @chapter Goals of Gforth
                    942: @cindex goals of the Gforth project
                    943: The goal of the Gforth Project is to develop a standard model for
                    944: ANS Forth. This can be split into several subgoals:
                    945: 
                    946: @itemize @bullet
                    947: @item
                    948: Gforth should conform to the ANS Forth Standard.
                    949: @item
                    950: It should be a model, i.e. it should define all the
                    951: implementation-dependent things.
                    952: @item
                    953: It should become standard, i.e. widely accepted and used. This goal
                    954: is the most difficult one.
                    955: @end itemize
                    956: 
                    957: To achieve these goals Gforth should be
                    958: @itemize @bullet
                    959: @item
                    960: Similar to previous models (fig-Forth, F83)
                    961: @item
                    962: Powerful. It should provide for all the things that are considered
                    963: necessary today and even some that are not yet considered necessary.
                    964: @item
                    965: Efficient. It should not get the reputation of being exceptionally
                    966: slow.
                    967: @item
                    968: Free.
                    969: @item
                    970: Available on many machines/easy to port.
                    971: @end itemize
                    972: 
                    973: Have we achieved these goals? Gforth conforms to the ANS Forth
                    974: standard. It may be considered a model, but we have not yet documented
                    975: which parts of the model are stable and which parts we are likely to
                    976: change. It certainly has not yet become a de facto standard, but it
                    977: appears to be quite popular. It has some similarities to and some
                    978: differences from previous models. It has some powerful features, but not
                    979: yet everything that we envisioned. We certainly have achieved our
                    980: execution speed goals (@pxref{Performance}).  It is free and available
                    981: on many machines.
                    982: 
                    983: @menu
                    984: * Gforth Extensions Sinful?::
                    985: @end menu
                    986: 
1.48      anton     987: @node Gforth Extensions Sinful?,  , Goals, Goals
1.26      crook     988: @comment node-name,     next,           previous, up
                    989: @section Is it a Sin to use Gforth Extensions?
                    990: @cindex Gforth extensions
                    991: 
                    992: If you've been paying attention, you will have realised that there is an
                    993: ANS (American National Standard) for Forth. As you read through the rest
1.29      crook     994: of this manual, you will see documentation for @i{Standard} words, and
                    995: documentation for some appealing Gforth @i{extensions}. You might ask
                    996: yourself the question: @i{``Given that there is a standard, would I be
1.45      crook     997: committing a sin if I use (non-Standard) Gforth extensions?''}
1.26      crook     998: 
                    999: The answer to that question is somewhat pragmatic and somewhat
                   1000: philosophical. Consider these points:
                   1001: 
                   1002: @itemize @bullet
                   1003: @item
                   1004: A number of the Gforth extensions can be implemented in ANS Forth using
                   1005: files provided in the @file{compat/} directory. These are mentioned in
                   1006: the text in passing.
                   1007: @item
                   1008: Forth has a rich historical precedent for programmers taking advantage
                   1009: of implementation-dependent features of their tools (for example,
                   1010: relying on a knowledge of the dictionary structure). Sometimes these
                   1011: techniques are necessary to extract every last bit of performance from
                   1012: the hardware, sometimes they are just a programming shorthand.
                   1013: @item
                   1014: The best way to break the rules is to know what the rules are. To learn
                   1015: the rules, there is no substitute for studying the text of the Standard
                   1016: itself. In particular, Appendix A of the Standard (@var{Rationale})
                   1017: provides a valuable insight into the thought processes of the technical
                   1018: committee.
                   1019: @item
                   1020: The best reason to break a rule is because you have to; because it's
                   1021: more productive to do that, because it makes your code run fast enough
                   1022: or because you can see no Standard way to achieve what you want to
                   1023: achieve.
                   1024: @end itemize
                   1025: 
                   1026: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
                   1027: analyse your program and determine what non-Standard definitions it
                   1028: relies upon.
                   1029: 
1.29      crook    1030: 
1.26      crook    1031: @c ******************************************************************
1.48      anton    1032: @node Gforth Environment, Tutorial, Goals, Top
1.29      crook    1033: @chapter Gforth Environment
                   1034: @cindex Gforth environment
1.21      crook    1035: 
1.45      crook    1036: Note: ultimately, the Gforth man page will be auto-generated from the
1.29      crook    1037: material in this chapter.
1.21      crook    1038: 
                   1039: @menu
1.29      crook    1040: * Invoking Gforth::             Getting in
                   1041: * Leaving Gforth::              Getting out
                   1042: * Command-line editing::        
1.48      anton    1043: * Upper and lower case::        
                   1044: * Environment variables::       that affect how Gforth starts up
1.29      crook    1045: * Gforth Files::                What gets installed and where
1.48      anton    1046: * Startup speed::               When 35ms is not fast enough ...
1.21      crook    1047: @end menu
                   1048: 
1.49      anton    1049: For related information about the creation of images see @ref{Image Files}.
1.29      crook    1050: 
1.21      crook    1051: @comment ----------------------------------------------
1.48      anton    1052: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29      crook    1053: @section Invoking Gforth
                   1054: @cindex invoking Gforth
                   1055: @cindex running Gforth
                   1056: @cindex command-line options
                   1057: @cindex options on the command line
                   1058: @cindex flags on the command line
1.21      crook    1059: 
1.30      anton    1060: Gforth is made up of two parts; an executable ``engine'' (named
                   1061: @file{gforth} or @file{gforth-fast}) and an image file. To start it, you
                   1062: will usually just say @code{gforth} -- this automatically loads the
                   1063: default image file @file{gforth.fi}. In many other cases the default
                   1064: Gforth image will be invoked like this:
1.21      crook    1065: @example
1.30      anton    1066: gforth [file | -e forth-code] ...
1.21      crook    1067: @end example
1.29      crook    1068: @noindent
                   1069: This interprets the contents of the files and the Forth code in the order they
                   1070: are given.
1.21      crook    1071: 
1.30      anton    1072: In addition to the @file{gforth} engine, there is also an engine called
                   1073: @file{gforth-fast}, which is faster, but gives less informative error
                   1074: messages (@pxref{Error messages}).
                   1075: 
1.29      crook    1076: In general, the command line looks like this:
1.21      crook    1077: 
                   1078: @example
1.30      anton    1079: gforth[-fast] [engine options] [image options]
1.21      crook    1080: @end example
                   1081: 
1.30      anton    1082: The engine options must come before the rest of the command
1.29      crook    1083: line. They are:
1.26      crook    1084: 
1.29      crook    1085: @table @code
                   1086: @cindex -i, command-line option
                   1087: @cindex --image-file, command-line option
                   1088: @item --image-file @i{file}
                   1089: @itemx -i @i{file}
                   1090: Loads the Forth image @i{file} instead of the default
                   1091: @file{gforth.fi} (@pxref{Image Files}).
1.21      crook    1092: 
1.39      anton    1093: @cindex --appl-image, command-line option
                   1094: @item --appl-image @i{file}
                   1095: Loads the image @i{file} and leaves all further command-line arguments
                   1096: to the image (instead of processing them as options).  This is useful
                   1097: for building executable application images on Unix, built with
                   1098: @code{gforthmi --application ...}.
                   1099: 
1.29      crook    1100: @cindex --path, command-line option
                   1101: @cindex -p, command-line option
                   1102: @item --path @i{path}
                   1103: @itemx -p @i{path}
                   1104: Uses @i{path} for searching the image file and Forth source code files
                   1105: instead of the default in the environment variable @code{GFORTHPATH} or
                   1106: the path specified at installation time (e.g.,
                   1107: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
                   1108: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21      crook    1109: 
1.29      crook    1110: @cindex --dictionary-size, command-line option
                   1111: @cindex -m, command-line option
                   1112: @cindex @i{size} parameters for command-line options
                   1113: @cindex size of the dictionary and the stacks
                   1114: @item --dictionary-size @i{size}
                   1115: @itemx -m @i{size}
                   1116: Allocate @i{size} space for the Forth dictionary space instead of
                   1117: using the default specified in the image (typically 256K). The
                   1118: @i{size} specification for this and subsequent options consists of
                   1119: an integer and a unit (e.g.,
                   1120: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
                   1121: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
                   1122: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
                   1123: @code{e} is used.
1.21      crook    1124: 
1.29      crook    1125: @cindex --data-stack-size, command-line option
                   1126: @cindex -d, command-line option
                   1127: @item --data-stack-size @i{size}
                   1128: @itemx -d @i{size}
                   1129: Allocate @i{size} space for the data stack instead of using the
                   1130: default specified in the image (typically 16K).
1.21      crook    1131: 
1.29      crook    1132: @cindex --return-stack-size, command-line option
                   1133: @cindex -r, command-line option
                   1134: @item --return-stack-size @i{size}
                   1135: @itemx -r @i{size}
                   1136: Allocate @i{size} space for the return stack instead of using the
                   1137: default specified in the image (typically 15K).
1.21      crook    1138: 
1.29      crook    1139: @cindex --fp-stack-size, command-line option
                   1140: @cindex -f, command-line option
                   1141: @item --fp-stack-size @i{size}
                   1142: @itemx -f @i{size}
                   1143: Allocate @i{size} space for the floating point stack instead of
                   1144: using the default specified in the image (typically 15.5K). In this case
                   1145: the unit specifier @code{e} refers to floating point numbers.
1.21      crook    1146: 
1.48      anton    1147: @cindex --locals-stack-size, command-line option
                   1148: @cindex -l, command-line option
                   1149: @item --locals-stack-size @i{size}
                   1150: @itemx -l @i{size}
                   1151: Allocate @i{size} space for the locals stack instead of using the
                   1152: default specified in the image (typically 14.5K).
                   1153: 
                   1154: @cindex -h, command-line option
                   1155: @cindex --help, command-line option
                   1156: @item --help
                   1157: @itemx -h
                   1158: Print a message about the command-line options
                   1159: 
                   1160: @cindex -v, command-line option
                   1161: @cindex --version, command-line option
                   1162: @item --version
                   1163: @itemx -v
                   1164: Print version and exit
                   1165: 
                   1166: @cindex --debug, command-line option
                   1167: @item --debug
                   1168: Print some information useful for debugging on startup.
                   1169: 
                   1170: @cindex --offset-image, command-line option
                   1171: @item --offset-image
                   1172: Start the dictionary at a slightly different position than would be used
                   1173: otherwise (useful for creating data-relocatable images,
                   1174: @pxref{Data-Relocatable Image Files}).
                   1175: 
                   1176: @cindex --no-offset-im, command-line option
                   1177: @item --no-offset-im
                   1178: Start the dictionary at the normal position.
                   1179: 
                   1180: @cindex --clear-dictionary, command-line option
                   1181: @item --clear-dictionary
                   1182: Initialize all bytes in the dictionary to 0 before loading the image
                   1183: (@pxref{Data-Relocatable Image Files}).
                   1184: 
                   1185: @cindex --die-on-signal, command-line-option
                   1186: @item --die-on-signal
                   1187: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
                   1188: or the segmentation violation SIGSEGV) by translating it into a Forth
                   1189: @code{THROW}. With this option, Gforth exits if it receives such a
                   1190: signal. This option is useful when the engine and/or the image might be
                   1191: severely broken (such that it causes another signal before recovering
                   1192: from the first); this option avoids endless loops in such cases.
                   1193: @end table
                   1194: 
                   1195: @cindex loading files at startup
                   1196: @cindex executing code on startup
                   1197: @cindex batch processing with Gforth
                   1198: As explained above, the image-specific command-line arguments for the
                   1199: default image @file{gforth.fi} consist of a sequence of filenames and
                   1200: @code{-e @var{forth-code}} options that are interpreted in the sequence
                   1201: in which they are given. The @code{-e @var{forth-code}} or
                   1202: @code{--evaluate @var{forth-code}} option evaluates the Forth
                   1203: code. This option takes only one argument; if you want to evaluate more
                   1204: Forth words, you have to quote them or use @code{-e} several times. To exit
                   1205: after processing the command line (instead of entering interactive mode)
                   1206: append @code{-e bye} to the command line.
                   1207: 
                   1208: @cindex versions, invoking other versions of Gforth
                   1209: If you have several versions of Gforth installed, @code{gforth} will
                   1210: invoke the version that was installed last. @code{gforth-@i{version}}
                   1211: invokes a specific version. If your environment contains the variable
                   1212: @code{GFORTHPATH}, you may want to override it by using the
                   1213: @code{--path} option.
                   1214: 
                   1215: Not yet implemented:
                   1216: On startup the system first executes the system initialization file
                   1217: (unless the option @code{--no-init-file} is given; note that the system
                   1218: resulting from using this option may not be ANS Forth conformant). Then
                   1219: the user initialization file @file{.gforth.fs} is executed, unless the
                   1220: option @code{--no-rc} is given; this file is first searched in @file{.},
                   1221: then in @file{~}, then in the normal path (see above).
                   1222: 
                   1223: 
                   1224: 
                   1225: @comment ----------------------------------------------
                   1226: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
                   1227: @section Leaving Gforth
                   1228: @cindex Gforth - leaving
                   1229: @cindex leaving Gforth
                   1230: 
                   1231: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
                   1232: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
                   1233: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49      anton    1234: data are discarded.  For ways of saving the state of the system before
                   1235: leaving Gforth see @ref{Image Files}.
1.48      anton    1236: 
                   1237: doc-bye
                   1238: 
                   1239: 
                   1240: @comment ----------------------------------------------
                   1241: @node Command-line editing, Upper and lower case, Leaving Gforth, Gforth Environment
                   1242: @section Command-line editing
                   1243: @cindex command-line editing
                   1244: 
                   1245: Gforth maintains a history file that records every line that you type to
                   1246: the text interpreter. This file is preserved between sessions, and is
                   1247: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
                   1248: repeatedly you can recall successively older commands from this (or
                   1249: previous) session(s). The full list of command-line editing facilities is:
                   1250: 
                   1251: @itemize @bullet
                   1252: @item
                   1253: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
                   1254: commands from the history buffer.
                   1255: @item
                   1256: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
                   1257: from the history buffer.
                   1258: @item
                   1259: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
                   1260: @item
                   1261: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
                   1262: @item
                   1263: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
                   1264: closing up the line.
                   1265: @item
                   1266: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
                   1267: @item
                   1268: @kbd{Ctrl-a} to move the cursor to the start of the line.
                   1269: @item
                   1270: @kbd{Ctrl-e} to move the cursor to the end of the line.
                   1271: @item
                   1272: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
                   1273: line.
                   1274: @item
                   1275: @key{TAB} to step through all possible full-word completions of the word
                   1276: currently being typed.
                   1277: @item
                   1278: @kbd{Ctrl-d} at the start of the line to terminate Gforth (gracefully,
                   1279: using @code{bye}).
                   1280: @end itemize
                   1281: 
                   1282: When editing, displayable characters are inserted to the left of the
                   1283: cursor position; the line is always in ``insert'' (as opposed to
                   1284: ``overstrike'') mode.
                   1285: 
                   1286: @cindex history file
                   1287: @cindex @file{.gforth-history}
                   1288: On Unix systems, the history file is @file{~/.gforth-history} by
                   1289: default@footnote{i.e. it is stored in the user's home directory.}. You
                   1290: can find out the name and location of your history file using:
                   1291: 
                   1292: @example 
                   1293: history-file type \ Unix-class systems
                   1294: 
                   1295: history-file type \ Other systems
                   1296: history-dir  type
                   1297: @end example
                   1298: 
                   1299: If you enter long definitions by hand, you can use a text editor to
                   1300: paste them out of the history file into a Forth source file for reuse at
                   1301: a later time.
                   1302: 
                   1303: Gforth never trims the size of the history file, so you should do this
                   1304: periodically, if necessary.
                   1305: 
                   1306: @comment this is all defined in history.fs
                   1307: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
                   1308: @comment chosen?
                   1309: 
                   1310: 
                   1311: 
                   1312: @comment ----------------------------------------------
                   1313: @node Upper and lower case, Environment variables, Command-line editing, Gforth Environment
                   1314: @section Upper and lower case
                   1315: @cindex case-sensitivity
                   1316: @cindex upper and lower case
                   1317: 
                   1318: Gforth is case-insensitive; you can enter definitions and invoke
                   1319: Standard words using upper, lower or mixed case (however,
                   1320: @pxref{core-idef, Implementation-defined options, Implementation-defined
                   1321: options}).
                   1322: 
                   1323: ANS Forth only @i{requires} implementations to recognise Standard words
                   1324: when they are typed entirely in upper case. Therefore, a Standard
                   1325: program must use upper case for all Standard words. You can use whatever
                   1326: case you like for words that you define, but in a standard program you
                   1327: have to use the words in the same case that you defined them.
                   1328: 
                   1329: Gforth supports case sensitivity through @code{table}s (case-sensitive
                   1330: wordlists, @pxref{Word Lists}).
                   1331: 
                   1332: Two people have asked how to convert Gforth to case sensitivity; while
                   1333: we think this is a bad idea, you can change all wordlists into tables
                   1334: like this:
                   1335: 
                   1336: @example
                   1337: ' table-find forth-wordlist wordlist-map @ !
                   1338: @end example
                   1339: 
                   1340: Note that you now have to type the predefined words in the same case
                   1341: that we defined them, which are varying.  You may want to convert them
                   1342: to your favourite case before doing this operation (I won't explain how,
                   1343: because if you are even contemplating to do this, you'd better have
                   1344: enough knowledge of Forth systems to know this already).
                   1345: 
                   1346: @comment ----------------------------------------------
                   1347: @node Environment variables, Gforth Files, Upper and lower case, Gforth Environment
                   1348: @section Environment variables
                   1349: @cindex environment variables
                   1350: 
                   1351: Gforth uses these environment variables:
                   1352: 
                   1353: @itemize @bullet
                   1354: @item
                   1355: @cindex @code{GFORTHHIST} -- environment variable
                   1356: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
                   1357: open/create the history file, @file{.gforth-history}. Default:
                   1358: @code{$HOME}.
                   1359: 
                   1360: @item
                   1361: @cindex @code{GFORTHPATH} -- environment variable
                   1362: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
                   1363: for Forth source-code files.
                   1364: 
                   1365: @item
                   1366: @cindex @code{GFORTH} -- environment variable
1.49      anton    1367: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton    1368: 
                   1369: @item
                   1370: @cindex @code{GFORTHD} -- environment variable
                   1371: @code{GFORTHD} -- used by @file{gforthmi} @xref{gforthmi}.
                   1372: 
                   1373: @item
                   1374: @cindex @code{TMP}, @code{TEMP} - environment variable
                   1375: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
                   1376: location for the history file.
                   1377: @end itemize
                   1378: 
                   1379: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
                   1380: @comment mentioning these.
                   1381: 
                   1382: All the Gforth environment variables default to sensible values if they
                   1383: are not set.
                   1384: 
                   1385: 
                   1386: @comment ----------------------------------------------
                   1387: @node Gforth Files, Startup speed, Environment variables, Gforth Environment
                   1388: @section Gforth files
                   1389: @cindex Gforth files
                   1390: 
                   1391: When you install Gforth on a Unix system, it installs files in these
                   1392: locations by default:
                   1393: 
                   1394: @itemize @bullet
                   1395: @item
                   1396: @file{/usr/local/bin/gforth}
                   1397: @item
                   1398: @file{/usr/local/bin/gforthmi}
                   1399: @item
                   1400: @file{/usr/local/man/man1/gforth.1} - man page.
                   1401: @item
                   1402: @file{/usr/local/info} - the Info version of this manual.
                   1403: @item
                   1404: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
                   1405: @item
                   1406: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
                   1407: @item
                   1408: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
                   1409: @item
                   1410: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
                   1411: @end itemize
                   1412: 
                   1413: You can select different places for installation by using
                   1414: @code{configure} options (listed with @code{configure --help}).
                   1415: 
                   1416: @comment ----------------------------------------------
                   1417: @node Startup speed,  , Gforth Files, Gforth Environment
                   1418: @section Startup speed
                   1419: @cindex Startup speed
                   1420: @cindex speed, startup
                   1421: 
                   1422: If Gforth is used for CGI scripts or in shell scripts, its startup
                   1423: speed may become a problem.  On a 300MHz 21064a under Linux-2.2.13 with
                   1424: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
                   1425: system time.
                   1426: 
                   1427: If startup speed is a problem, you may consider the following ways to
                   1428: improve it; or you may consider ways to reduce the number of startups
                   1429: (e.g., Fast-CGI).
                   1430: 
                   1431: The first step to improve startup speed is to statically link Gforth, by
                   1432: building it with @code{XLDFLAGS=-static}.  This requires more memory for
                   1433: the code and will therefore slow down the first invocation, but
                   1434: subsequent invocations avoid the dynamic linking overhead.  Another
                   1435: disadvantage is that Gforth won't profit from library upgrades.  As a
                   1436: result, @code{gforth-static -e bye} takes about 17.1ms user and
                   1437: 8.2ms system time.
                   1438: 
                   1439: The next step to improve startup speed is to use a non-relocatable image
                   1440: @ref{Non-Relocatable Image Files}.  You can create this image with
                   1441: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
                   1442: @code{gforth -i gforthnr.fi ...}.  This avoids the relocation overhead
                   1443: and a part of the copy-on-write overhead.  The disadvantage is that the
                   1444: nonrelocatable image does not work if the OS gives Gforth a different
                   1445: address for the dictionary, for whatever reason; so you better provide a
                   1446: fallback on a relocatable image.  @code{gforth-static -i gforthnr.fi -e
                   1447: bye} takes about 15.3ms user and 7.5ms system time.
                   1448: 
                   1449: The final step is to disable dictionary hashing in Gforth.  Gforth
                   1450: builds the hash table on startup, which takes much of the startup
                   1451: overhead. You can do this by commenting out the @code{include hash.fs}
                   1452: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
                   1453: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
                   1454: The disadvantages are that functionality like @code{table} and
                   1455: @code{ekey} is missing and that text interpretation (e.g., compiling)
                   1456: now takes much longer. So, you should only use this method if there is
                   1457: no significant text interpretation to perform (the script should be
                   1458: compiled into the image, among other things).  @code{gforth-static -i
                   1459: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
                   1460: 
                   1461: @c ******************************************************************
                   1462: @node Tutorial, Introduction, Gforth Environment, Top
                   1463: @chapter Forth Tutorial
                   1464: @cindex Tutorial
                   1465: @cindex Forth Tutorial
                   1466: 
                   1467: This tutorial can be used with any ANS-compliant Forth; any places that
                   1468: mention features specific to Gforth are marked as such and you can skip
                   1469: them, if you work with another Forth.  This tutorial does not explain
                   1470: all features of Forth, just enough to get you started and give you some
                   1471: ideas about the facilities available in Forth.  Read the rest of the
                   1472: manual and the standard when you are through this.
                   1473: 
                   1474: The intended way to use this tutorial is that you work through it while
                   1475: sitting in front of the console, take a look at the examples and predict
                   1476: what they will do, then try them out; if the outcome is not as expected,
                   1477: find out why (e.g., by trying out variations of the example), so you
                   1478: understand what's going on.  There are also some assignments that you
                   1479: should solve.
                   1480: 
                   1481: This tutorial assumes that you have programmed before and know what,
                   1482: e.g., a loop is.
                   1483: 
                   1484: @c !! explain compat library
                   1485: 
                   1486: @menu
                   1487: * Starting Gforth Tutorial::    
                   1488: * Syntax Tutorial::             
                   1489: * Crash Course Tutorial::       
                   1490: * Stack Tutorial::              
                   1491: * Arithmetics Tutorial::        
                   1492: * Stack Manipulation Tutorial::  
                   1493: * Using files for Forth code Tutorial::  
                   1494: * Comments Tutorial::           
                   1495: * Colon Definitions Tutorial::  
                   1496: * Decompilation Tutorial::      
                   1497: * Stack-Effect Comments Tutorial::  
                   1498: * Types Tutorial::              
                   1499: * Factoring Tutorial::          
                   1500: * Designing the stack effect Tutorial::  
                   1501: * Local Variables Tutorial::    
                   1502: * Conditional execution Tutorial::  
                   1503: * Flags and Comparisons Tutorial::  
                   1504: * General Loops Tutorial::      
                   1505: * Counted loops Tutorial::      
                   1506: * Recursion Tutorial::          
                   1507: * Leaving definitions or loops Tutorial::  
                   1508: * Return Stack Tutorial::       
                   1509: * Memory Tutorial::             
                   1510: * Characters and Strings Tutorial::  
                   1511: * Alignment Tutorial::          
                   1512: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                   1513: * Execution Tokens Tutorial::   
                   1514: * Exceptions Tutorial::         
                   1515: * Defining Words Tutorial::     
                   1516: * Arrays and Records Tutorial::  
                   1517: * POSTPONE Tutorial::           
                   1518: * Literal Tutorial::            
                   1519: * Advanced macros Tutorial::    
                   1520: * Compilation Tokens Tutorial::  
                   1521: * Wordlists and Search Order Tutorial::  
                   1522: @end menu
                   1523: 
                   1524: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
                   1525: @section Starting Gforth
                   1526: 
                   1527: You can start Gforth by typing its name:
                   1528: 
                   1529: @example
                   1530: gforth
                   1531: @end example
                   1532: 
                   1533: That puts you into interactive mode; you can leave Gforth by typing
                   1534: @code{bye}.  While in Gforth, you can edit the command line and access
                   1535: the command line history with cursor keys, similar to bash.
                   1536: 
                   1537: 
                   1538: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
                   1539: @section Syntax
                   1540: 
                   1541: A @dfn{word} is a sequence of arbitrary characters (expcept white
                   1542: space).  Words are separated by white space.  E.g., each of the
                   1543: following lines contains exactly one word:
                   1544: 
                   1545: @example
                   1546: word
                   1547: !@@#$%^&*()
                   1548: 1234567890
                   1549: 5!a
                   1550: @end example
                   1551: 
                   1552: A frequent beginner's error is to leave away necessary white space,
                   1553: resulting in an error like @samp{Undefined word}; so if you see such an
                   1554: error, check if you have put spaces wherever necessary.
                   1555: 
                   1556: @example
                   1557: ." hello, world" \ correct
                   1558: ."hello, world"  \ gives an "Undefined word" error
                   1559: @end example
                   1560: 
                   1561: Gforth and most other Forth systems ignores differences in case (it is
                   1562: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
                   1563: your system is case-sensitive, you may have to type all the examples
                   1564: given here in upper case.
                   1565: 
                   1566: 
                   1567: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
                   1568: @section Crash Course
                   1569: 
                   1570: Type
                   1571: 
                   1572: @example
                   1573: 0 0 !
                   1574: here execute
                   1575: ' catch >body 20 erase abort
                   1576: ' (quit) >body 20 erase
                   1577: @end example
                   1578: 
                   1579: The last two examples are guaranteed to destroy parts of Gforth (and
                   1580: most other systems), so you better leave Gforth afterwards (if it has
                   1581: not finished by itself).  On some systems you may have to kill gforth
                   1582: from outside (e.g., in Unix with @code{kill}).
                   1583: 
                   1584: Now that you know how to produce crashes (and that there's not much to
                   1585: them), let's learn how to produce meaningful programs.
                   1586: 
                   1587: 
                   1588: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
                   1589: @section Stack
                   1590: 
                   1591: The most obvious feature of Forth is the stack.  When you type in a
                   1592: number, it is pushed on the stack.  You can display the content of the
                   1593: stack with @code{.s}.
                   1594: 
                   1595: @example
                   1596: 1 2 .s
                   1597: 3 .s
                   1598: @end example
                   1599: 
                   1600: @code{.s} displays the top-of-stack to the right, i.e., the numbers
                   1601: appear in @code{.s} output as they appeared in the input.
                   1602: 
                   1603: You can print the top of stack element with @code{.}.
                   1604: 
                   1605: @example
                   1606: 1 2 3 . . .
                   1607: @end example
                   1608: 
                   1609: In general, words consume their stack arguments (@code{.s} is an
                   1610: exception).
                   1611: 
                   1612: @assignment
                   1613: What does the stack contain after @code{5 6 7 .}?
                   1614: @endassignment
                   1615: 
                   1616: 
                   1617: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
                   1618: @section Arithmetics
                   1619: 
                   1620: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
                   1621: operate on the top two stack items:
                   1622: 
                   1623: @example
                   1624: 2 2 + .
                   1625: 2 1 - .
                   1626: 7 3 mod .
                   1627: @end example
                   1628: 
                   1629: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
                   1630: as in the corresponding infix expression (this is generally the case in
                   1631: Forth).
                   1632: 
                   1633: Parentheses are superfluous (and not available), because the order of
                   1634: the words unambiguously determines the order of evaluation and the
                   1635: operands:
                   1636: 
                   1637: @example
                   1638: 3 4 + 5 * .
                   1639: 3 4 5 * + .
                   1640: @end example
                   1641: 
                   1642: @assignment
                   1643: What are the infix expressions corresponding to the Forth code above?
                   1644: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
                   1645: known as Postfix or RPN (Reverse Polish Notation).}.
                   1646: @endassignment
                   1647: 
                   1648: To change the sign, use @code{negate}:
                   1649: 
                   1650: @example
                   1651: 2 negate .
                   1652: @end example
                   1653: 
                   1654: @assignment
                   1655: Convert -(-3)*4-5 to Forth.
                   1656: @endassignment
                   1657: 
                   1658: @code{/mod} performs both @code{/} and @code{mod}.
                   1659: 
                   1660: @example
                   1661: 7 3 /mod . .
                   1662: @end example
                   1663: 
                   1664: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
                   1665: @section Stack Manipulation
                   1666: 
                   1667: Stack manipulation words rearrange the data on the stack.
                   1668: 
                   1669: @example
                   1670: 1 .s drop .s
                   1671: 1 .s dup .s drop drop .s
                   1672: 1 2 .s over .s drop drop drop
                   1673: 1 2 .s swap .s drop drop
                   1674: 1 2 3 .s rot .s drop drop drop
                   1675: @end example
                   1676: 
                   1677: These are the most important stack manipulation words.  There are also
                   1678: variants that manipulate twice as many stack items:
                   1679: 
                   1680: @example
                   1681: 1 2 3 4 .s 2swap .s 2drop 2drop
                   1682: @end example
                   1683: 
                   1684: Two more stack manipulation words are:
                   1685: 
                   1686: @example
                   1687: 1 2 .s nip .s drop
                   1688: 1 2 .s tuck .s 2drop drop
                   1689: @end example
                   1690: 
                   1691: @assignment
                   1692: Replace @code{nip} and @code{tuck} with combinations of other stack
                   1693: manipulation words.
                   1694: 
                   1695: @example
                   1696: Given:          How do you get:
                   1697: 1 2 3           3 2 1           
                   1698: 1 2 3           1 2 3 2                 
                   1699: 1 2 3           1 2 3 3                 
                   1700: 1 2 3           1 3 3           
                   1701: 1 2 3           2 1 3           
                   1702: 1 2 3 4         4 3 2 1         
                   1703: 1 2 3           1 2 3 1 2 3             
                   1704: 1 2 3 4         1 2 3 4 1 2             
                   1705: 1 2 3
                   1706: 1 2 3           1 2 3 4                 
                   1707: 1 2 3           1 3             
                   1708: @end example
                   1709: @endassignment
                   1710: 
                   1711: @example
                   1712: 5 dup * .
                   1713: @end example
                   1714: 
                   1715: @assignment
                   1716: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
                   1717: Write a piece of Forth code that expects two numbers on the stack
                   1718: (@var{a} and @var{b}, with @var{b} on top) and computes
                   1719: @code{(a-b)(a+1)}.
                   1720: @endassignment
                   1721: 
                   1722: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
                   1723: @section Using files for Forth code
                   1724: 
                   1725: While working at the Forth command line is convenient for one-line
                   1726: examples and short one-off code, you probably want to store your source
                   1727: code in files for convenient editing and persistence.  You can use your
                   1728: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
                   1729: Gforth}) to create @var{file} and use
                   1730: 
                   1731: @example
                   1732: s" @var{file}" included
                   1733: @end example
                   1734: 
                   1735: to load it into your Forth system.  The file name extension I use for
                   1736: Forth files is @samp{.fs}.
                   1737: 
                   1738: You can easily start Gforth with some files loaded like this:
                   1739: 
                   1740: @example
                   1741: gforth @var{file1} @var{file2}
                   1742: @end example
                   1743: 
                   1744: If an error occurs during loading these files, Gforth terminates,
                   1745: whereas an error during @code{INCLUDED} within Gforth usually gives you
                   1746: a Gforth command line.  Starting the Forth system every time gives you a
                   1747: clean start every time, without interference from the results of earlier
                   1748: tries.
                   1749: 
                   1750: I often put all the tests in a file, then load the code and run the
                   1751: tests with
                   1752: 
                   1753: @example
                   1754: gforth @var{code} @var{tests} -e bye
                   1755: @end example
                   1756: 
                   1757: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
                   1758: @code{-e bye} ensures that Gforth terminates afterwards so that I can
                   1759: restart this command without ado.
                   1760: 
                   1761: The advantage of this approach is that the tests can be repeated easily
                   1762: every time the program ist changed, making it easy to catch bugs
                   1763: introduced by the change.
                   1764: 
                   1765: 
                   1766: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
                   1767: @section Comments
                   1768: 
                   1769: @example
                   1770: \ That's a comment; it ends at the end of the line
                   1771: ( Another comment; it ends here: )  .s
                   1772: @end example
                   1773: 
                   1774: @code{\} and @code{(} are ordinary Forth words and therefore have to be
                   1775: separated with white space from the following text.
                   1776: 
                   1777: @example
                   1778: \This gives an "Undefined word" error
                   1779: @end example
                   1780: 
                   1781: The first @code{)} ends a comment started with @code{(}, so you cannot
                   1782: nest @code{(}-comments; and you cannot comment out text containing a
                   1783: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
                   1784: avoid @code{)} in word names.}.
                   1785: 
                   1786: I use @code{\}-comments for descriptive text and for commenting out code
                   1787: of one or more line; I use @code{(}-comments for describing the stack
                   1788: effect, the stack contents, or for commenting out sub-line pieces of
                   1789: code.
                   1790: 
                   1791: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
                   1792: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
                   1793: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
                   1794: with @kbd{M-q}.
                   1795: 
                   1796: 
                   1797: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
                   1798: @section Colon Definitions
                   1799: 
                   1800: are similar to procedures and functions in other programming languages.
                   1801: 
                   1802: @example
                   1803: : squared ( n -- n^2 )
                   1804:    dup * ;
                   1805: 5 squared .
                   1806: 7 squared .
                   1807: @end example
                   1808: 
                   1809: @code{:} starts the colon definition; its name is @code{squared}.  The
                   1810: following comment describes its stack effect.  The words @code{dup *}
                   1811: are not executed, but compiled into the definition.  @code{;} ends the
                   1812: colon definition.
                   1813: 
                   1814: The newly-defined word can be used like any other word, including using
                   1815: it in other definitions:
                   1816: 
                   1817: @example
                   1818: : cubed ( n -- n^3 )
                   1819:    dup squared * ;
                   1820: -5 cubed .
                   1821: : fourth-power ( n -- n^4 )
                   1822:    squared squared ;
                   1823: 3 fourth-power .
                   1824: @end example
                   1825: 
                   1826: @assignment
                   1827: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
                   1828: @code{/mod} in terms of other Forth words, and check if they work (hint:
                   1829: test your tests on the originals first).  Don't let the
                   1830: @samp{redefined}-Messages spook you, they are just warnings.
                   1831: @endassignment
                   1832: 
                   1833: 
                   1834: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
                   1835: @section Decompilation
                   1836: 
                   1837: You can decompile colon definitions with @code{see}:
                   1838: 
                   1839: @example
                   1840: see squared
                   1841: see cubed
                   1842: @end example
                   1843: 
                   1844: In Gforth @code{see} shows you a reconstruction of the source code from
                   1845: the executable code.  Informations that were present in the source, but
                   1846: not in the executable code, are lost (e.g., comments).
                   1847: 
                   1848: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
                   1849: @section Stack-Effect Comments
                   1850: 
                   1851: By convention the comment after the name of a definition describes the
                   1852: stack effect: The part in from of the @samp{--} describes the state of
                   1853: the stack before the execution of the definition, i.e., the parameters
                   1854: that are passed into the colon definition; the part behind the @samp{--}
                   1855: is the state of the stack after the execution of the definition, i.e.,
                   1856: the results of the definition.  The stack comment only shows the top
                   1857: stack items that the definition accesses and/or changes.
                   1858: 
                   1859: You should put a correct stack effect on every definition, even if it is
                   1860: just @code{( -- )}.  You should also add some descriptive comment to
                   1861: more complicated words (I usually do this in the lines following
                   1862: @code{:}).  If you don't do this, your code becomes unreadable (because
                   1863: you have to work through every definition before you can undertsand
                   1864: any).
                   1865: 
                   1866: @assignment
                   1867: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
                   1868: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
                   1869: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
                   1870: are done, you can compare your stack effects to this in this manual
                   1871: (@pxref{Word Index}).
                   1872: @endassignment
                   1873: 
                   1874: Sometimes programmers put comments at various places in colon
                   1875: definitions that describe the contents of the stack at that place (stack
                   1876: comments); i.e., they are like the first part of a stack-effect
                   1877: comment. E.g.,
                   1878: 
                   1879: @example
                   1880: : cubed ( n -- n^3 )
                   1881:    dup squared  ( n n^2 ) * ;
                   1882: @end example
                   1883: 
                   1884: In this case the stack comment is pretty superfluous, because the word
                   1885: is simple enough.  If you think it would be a good idea to add such a
                   1886: comment to increase readability, you should also consider factoring the
                   1887: word into several simpler words (@pxref{Factoring Tutorial,,
                   1888: Factoring}), which typically eliminates the need for the stack effect;
                   1889: however, if you decide not to refactor it, then having such a comment is
                   1890: better than not having it.
                   1891: 
                   1892: The names of the stack items in stack-effect and stack comments in the
                   1893: standard, in this manual, and in many programs specify the type through
                   1894: a type prefix, similar to Fortran and Hungarian notation.  The most
                   1895: frequent prefixes are:
                   1896: 
                   1897: @table @code
                   1898: @item n
                   1899: signed integer
                   1900: @item u
                   1901: unsigned integer
                   1902: @item c
                   1903: character
                   1904: @item f
                   1905: Boolean flags, i.e. @code{false} or @code{true}.
                   1906: @item a-addr,a-
                   1907: Cell-aligned address
                   1908: @item c-addr,c-
                   1909: Char-aligned address (note that a Char may have two bytes in Windows NT)
                   1910: @item xt
                   1911: Execution token, same size as Cell
                   1912: @item w,x
                   1913: Cell, can contain an integer or an address.  It usually takes 32, 64 or
                   1914: 16 bits (depending on your platform and Forth system). A cell is more
                   1915: commonly known as machine word, but the term @emph{word} already means
                   1916: something different in Forth.
                   1917: @item d
                   1918: signed double-cell integer
                   1919: @item ud
                   1920: unsigned double-cell integer
                   1921: @item r
                   1922: Float (on the FP stack)
                   1923: @end table
                   1924: 
                   1925: You can find a more complete list in @ref{Notation}.
                   1926: 
                   1927: @assignment
                   1928: Write stack-effect comments for all definitions you have written up to
                   1929: now.
                   1930: @endassignment
                   1931: 
                   1932: 
                   1933: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
                   1934: @section Types
                   1935: 
                   1936: In Forth the names of the operations are not overloaded; so similar
                   1937: operations on different types need different names; e.g., @code{+} adds
                   1938: integers, and you have to use @code{f+} to add floating-point numbers.
                   1939: The following prefixes are often used for related operations on
                   1940: different types:
                   1941: 
                   1942: @table @code
                   1943: @item (none)
                   1944: signed integer
                   1945: @item u
                   1946: unsigned integer
                   1947: @item c
                   1948: character
                   1949: @item d
                   1950: signed double-cell integer
                   1951: @item ud, du
                   1952: unsigned double-cell integer
                   1953: @item 2
                   1954: two cells (not-necessarily double-cell numbers)
                   1955: @item m, um
                   1956: mixed single-cell and double-cell operations
                   1957: @item f
                   1958: floating-point (note that in stack comments @samp{f} represents flags,
                   1959: and @samp{r} represents FP number).
                   1960: @end table
                   1961: 
                   1962: If there are no differences between the signed and the unsigned variant
                   1963: (e.g., for @code{+}), there is only the prefix-less variant.
                   1964: 
                   1965: Forth does not perform type checking, neither at compile time, nor at
                   1966: run time.  If you use the wrong oeration, the data are interpreted
                   1967: incorrectly:
                   1968: 
                   1969: @example
                   1970: -1 u.
                   1971: @end example
                   1972: 
                   1973: If you have only experience with type-checked languages until now, and
                   1974: have heard how important type-checking is, don't panic!  In my
                   1975: experience (and that of other Forthers), type errors in Forth code are
                   1976: usually easy to find (once you get used to it), the increased vigilance
                   1977: of the programmer tends to catch some harder errors in addition to most
                   1978: type errors, and you never have to work around the type system, so in
                   1979: most situations the lack of type-checking seems to be a win (projects to
                   1980: add type checking to Forth have not caught on).
                   1981: 
                   1982: 
                   1983: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
                   1984: @section Factoring
                   1985: 
                   1986: If you try to write longer definitions, you will soon find it hard to
                   1987: keep track of the stack contents.  Therefore, good Forth programmers
                   1988: tend to write only short definitions (e.g., three lines).  The art of
                   1989: finding meaningful short definitions is known as factoring (as in
                   1990: factoring polynomials).
                   1991: 
                   1992: Well-factored programs offer additional advantages: smaller, more
                   1993: general words, are easier to test and debug and can be reused more and
                   1994: better than larger, specialized words.
                   1995: 
                   1996: So, if you run into difficulties with stack management, when writing
                   1997: code, try to define meaningful factors for the word, and define the word
                   1998: in terms of those.  Even if a factor contains only two words, it is
                   1999: often helpful.
                   2000: 
                   2001: Good factoring is not easy, and even experienced Forth programmers often
                   2002: don't find the right solution right away, but only when rewriting the
                   2003: program.  So, if you don't come up with a good solution immediately,
                   2004: keep trying, don't despair.
                   2005: 
                   2006: @c example !!
                   2007: 
                   2008: 
                   2009: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
                   2010: @section Designing the stack effect
                   2011: 
                   2012: In other languages you can use an arbitrary order of parameters for a
                   2013: function; and since ther is only one result, you don't have to deal with
                   2014: the order of results, either.
                   2015: 
                   2016: In Forth (and other stack-based languages, e.g., Postscript) the
                   2017: parameter and result order of a definition is important and should be
                   2018: designed well.  The general guideline is to design the stack effect such
                   2019: that the word is simple to use in most cases, even if that complicates
                   2020: the implementation of the word.  Some concrete rules are:
                   2021: 
                   2022: @itemize @bullet
                   2023: 
                   2024: @item
                   2025: Words consume all of their parameters (e.g., @code{.}).
                   2026: 
                   2027: @item
                   2028: If there is a convention on the order of parameters (e.g., from
                   2029: mathematics or another programming language), stick with it (e.g.,
                   2030: @code{-}).
                   2031: 
                   2032: @item
                   2033: If one parameter usually requires only a short computation (e.g., it is
                   2034: a constant), pass it on the top of the stack.  Conversely, parameters
                   2035: that usually require a long sequence of code to compute should be passed
                   2036: as the bottom (i.e., first) parameter.  This makes the code easier to
                   2037: read, because reader does not need to keep track of the bottom item
                   2038: through a long sequence of code (or, alternatively, through stack
1.49      anton    2039: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48      anton    2040: address on top of the stack because it is usually simpler to compute
                   2041: than the stored value (often the address is just a variable).
                   2042: 
                   2043: @item
                   2044: Similarly, results that are usually consumed quickly should be returned
                   2045: on the top of stack, whereas a result that is often used in long
                   2046: computations should be passed as bottom result.  E.g., the file words
                   2047: like @code{open-file} return the error code on the top of stack, because
                   2048: it is usually consumed quickly by @code{throw}; moreover, the error code
                   2049: has to be checked before doing anything with the other results.
                   2050: 
                   2051: @end itemize
                   2052: 
                   2053: These rules are just general guidelines, don't lose sight of the overall
                   2054: goal to make the words easy to use.  E.g., if the convention rule
                   2055: conflicts with the computation-length rule, you might decide in favour
                   2056: of the convention if the word will be used rarely, and in favour of the
                   2057: computation-length rule if the word will be used frequently (because
                   2058: with frequent use the cost of breaking the computation-length rule would
                   2059: be quite high, and frequent use makes it easier to remember an
                   2060: unconventional order).
                   2061: 
                   2062: @c example !! structure package
                   2063: 
                   2064: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
                   2065: @section Local Variables
                   2066: 
                   2067: You can define local variables (@emph{locals}) in a colon definition:
                   2068: 
                   2069: @example
                   2070: : swap @{ a b -- b a @}
                   2071:   b a ;
                   2072: 1 2 swap .s 2drop
                   2073: @end example
                   2074: 
                   2075: (If your Forth system does not support this syntax, include
                   2076: @file{compat/anslocals.fs} first).
                   2077: 
                   2078: In this example @code{@{ a b -- b a @}} is the locals definition; it
                   2079: takes two cells from the stack, puts the top of stack in @code{b} and
                   2080: the next stack element in @code{a}.  @code{--} starts a comment ending
                   2081: with @code{@}}.  After the locals definition, using the name of the
                   2082: local will push its value on the stack.  You can leave the comment
                   2083: part (@code{-- b a}) away:
                   2084: 
                   2085: @example
                   2086: : swap ( x1 x2 -- x2 x1 )
                   2087:   @{ a b @} b a ;
                   2088: @end example
                   2089: 
                   2090: In Gforth you can have several locals definitions, anywhere in a colon
                   2091: definition; in contrast, in a standard program you can have only one
                   2092: locals definition per colon definition, and that locals definition must
                   2093: be outside any controll structure.
                   2094: 
                   2095: With locals you can write slightly longer definitions without running
                   2096: into stack trouble.  However, I recommend trying to write colon
                   2097: definitions without locals for exercise purposes to help you gain the
                   2098: essential factoring skills.
                   2099: 
                   2100: @assignment
                   2101: Rewrite your definitions until now with locals
                   2102: @endassignment
                   2103: 
                   2104: 
                   2105: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
                   2106: @section Conditional execution
                   2107: 
                   2108: In Forth you can use control structures only inside colon definitions.
                   2109: An @code{if}-structure looks like this:
                   2110: 
                   2111: @example
                   2112: : abs ( n1 -- +n2 )
                   2113:     dup 0 < if
                   2114:         negate
                   2115:     endif ;
                   2116: 5 abs .
                   2117: -5 abs .
                   2118: @end example
                   2119: 
                   2120: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
                   2121: the following code is performed, otherwise execution continues after the
1.51      pazsan   2122: @code{endif} (or @code{else}).  @code{<} compares the top two stack
1.48      anton    2123: elements and prioduces a flag:
                   2124: 
                   2125: @example
                   2126: 1 2 < .
                   2127: 2 1 < .
                   2128: 1 1 < .
                   2129: @end example
                   2130: 
                   2131: Actually the standard name for @code{endif} is @code{then}.  This
                   2132: tutorial presents the examples using @code{endif}, because this is often
                   2133: less confusing for people familiar with other programming languages
                   2134: where @code{then} has a different meaning.  If your system does not have
                   2135: @code{endif}, define it with
                   2136: 
                   2137: @example
                   2138: : endif postpone then ; immediate
                   2139: @end example
                   2140: 
                   2141: You can optionally use an @code{else}-part:
                   2142: 
                   2143: @example
                   2144: : min ( n1 n2 -- n )
                   2145:   2dup < if
                   2146:     drop
                   2147:   else
                   2148:     nip
                   2149:   endif ;
                   2150: 2 3 min .
                   2151: 3 2 min .
                   2152: @end example
                   2153: 
                   2154: @assignment
                   2155: Write @code{min} without @code{else}-part (hint: what's the definition
                   2156: of @code{nip}?).
                   2157: @endassignment
                   2158: 
                   2159: 
                   2160: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
                   2161: @section Flags and Comparisons
                   2162: 
                   2163: In a false-flag all bits are clear (0 when interpreted as integer).  In
                   2164: a canonical true-flag all bits are set (-1 as a twos-complement signed
                   2165: integer); in many contexts (e.g., @code{if}) any non-zero value is
                   2166: treated as true flag.
                   2167: 
                   2168: @example
                   2169: false .
                   2170: true .
                   2171: true hex u. decimal
                   2172: @end example
                   2173: 
                   2174: Comparison words produce canonical flags:
                   2175: 
                   2176: @example
                   2177: 1 1 = .
                   2178: 1 0= .
                   2179: 0 1 < .
                   2180: 0 0 < .
                   2181: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
                   2182: -1 1 < .
                   2183: @end example
                   2184: 
                   2185: Gforth supports all combinations of the prefixes @code{0 u d d0 du} (or
                   2186: none) and the comparisons @code{= <> < > <= >=}.  Only a part of these
                   2187: combinations are standard (see the standard or !! the glossary for
                   2188: details).
                   2189: 
                   2190: You can use @code{and or xor invert} can be used as operations on
                   2191: canonical flags.  Actually they are bitwise operations:
                   2192: 
                   2193: @example
                   2194: 1 2 and .
                   2195: 1 2 or .
                   2196: 1 3 xor .
                   2197: 1 invert .
                   2198: @end example
                   2199: 
                   2200: You can convert a zero/non-zero flag into a canonical flag with
                   2201: @code{0<>} (and complement it on the way with @code{0=}).
                   2202: 
                   2203: @example
                   2204: 1 0= .
                   2205: 1 0<> .
                   2206: @end example
                   2207: 
                   2208: You can use the all-bits-set feature of canonicasl flags and the bitwise
                   2209: operation of the Boolean operations to avoid @code{if}s:
                   2210: 
                   2211: @example
                   2212: : foo ( n1 -- n2 )
                   2213:   0= if
                   2214:     14
                   2215:   else
                   2216:     0
                   2217:   endif ;
                   2218: 0 foo .
                   2219: 1 foo .
                   2220: 
                   2221: : foo ( n1 -- n2 )
                   2222:   0= 14 and ;
                   2223: 0 foo .
                   2224: 1 foo .
                   2225: @end example
                   2226: 
                   2227: @assignment
                   2228: Write @code{min} without @code{if}.
                   2229: @endassignment
                   2230: 
                   2231: 
                   2232: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
                   2233: @section General Loops
                   2234: 
                   2235: The endless loop is the most simple one:
                   2236: 
                   2237: @example
                   2238: : endless ( -- )
                   2239:   0 begin
                   2240:     dup . 1+
                   2241:   again ;
                   2242: endless
                   2243: @end example
                   2244: 
                   2245: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
                   2246: does nothing at run-time, @code{again} jumps back to @code{begin}.
                   2247: 
                   2248: A loop with one exit at any place looks like this:
                   2249: 
                   2250: @example
                   2251: : log2 ( +n1 -- n2 )
                   2252: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2253:   assert( dup 0> )
                   2254:   2/ 0 begin
                   2255:     over 0> while
                   2256:       1+ swap 2/ swap
                   2257:   repeat
                   2258:   nip ;
                   2259: 7 log2 .
                   2260: 8 log2 .
                   2261: @end example
                   2262: 
                   2263: At run-time @code{while} consumes a flag; if it is 0, execution
1.51      pazsan   2264: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48      anton    2265: continues behind the @code{while}.  @code{Repeat} jumps back to
                   2266: @code{begin}, just like @code{again}.
                   2267: 
                   2268: In Forth there are many combinations/abbreviations, like @code{1+}.
                   2269: However, @code{2/} is not one of them; it shifts it's argument right by
                   2270: one bit (arithmetic shift right):
                   2271: 
                   2272: @example
                   2273: -5 2 / .
                   2274: -5 2/ .
                   2275: @end example
                   2276: 
                   2277: @code{assert(} is no standard word, but you can get it on systems other
                   2278: then Gforth by including @file{compat/assert.fs}.  You can see what it
                   2279: does by trying
                   2280: 
                   2281: @example
                   2282: 0 log2 .
                   2283: @end example
                   2284: 
                   2285: Here's a loop with an exit at the end:
                   2286: 
                   2287: @example
                   2288: : log2 ( +n1 -- n2 )
                   2289: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2290:   assert( dup 0 > )
                   2291:   -1 begin
                   2292:     1+ swap 2/ swap
                   2293:     over 0 <=
                   2294:   until
                   2295:   nip ;
                   2296: @end example
                   2297: 
                   2298: @code{Until} consumes a flag; if it is non-zero, execution continues at
                   2299: the @code{begin}, otherwise after the @code{until}.
                   2300: 
                   2301: @assignment
                   2302: Write a definition for computing the greatest common divisor.
                   2303: @endassignment
                   2304: 
                   2305: 
                   2306: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
                   2307: @section Counted loops
                   2308: 
                   2309: @example
                   2310: : ^ ( n1 u -- n )
                   2311: \ n = the uth power of u1
                   2312:   1 swap 0 u+do
                   2313:     over *
                   2314:   loop
                   2315:   nip ;
                   2316: 3 2 ^ .
                   2317: 4 3 ^ .
                   2318: @end example
                   2319: 
                   2320: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
                   2321: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
                   2322: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
                   2323: times (or not at all, if @code{u3-u4<0}).
                   2324: 
                   2325: You can see the stack effect design rules at work in the stack effect of
                   2326: the loop start words: Since the start value of the loop is more
                   2327: frequently constant than the end value, the start value is passed on
                   2328: the top-of-stack.
                   2329: 
                   2330: You can access the counter of a counted loop with @code{i}:
                   2331: 
                   2332: @example
                   2333: : fac ( u -- u! )
                   2334:   1 swap 1+ 1 u+do
                   2335:     i *
                   2336:   loop ;
                   2337: 5 fac .
                   2338: 7 fac .
                   2339: @end example
                   2340: 
                   2341: There is also @code{+do}, which expects signed numbers (important for
                   2342: deciding whether to enter the loop).
                   2343: 
                   2344: @assignment
                   2345: Write a definition for computing the nth Fibonacci number.
                   2346: @endassignment
                   2347: 
                   2348: !! +DO...+LOOP
                   2349: !! -DO...-LOOP
                   2350: 
                   2351: 
                   2352: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
                   2353: @section Recursion
                   2354: 
                   2355: Usually the name of a definition is not visible in the definition; but
                   2356: earlier definitions are usually visible:
                   2357: 
                   2358: @example
                   2359: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
                   2360: : / ( n1 n2 -- n )
                   2361:   dup 0= if
                   2362:     -10 throw \ report division by zero
                   2363:   endif
                   2364:   /           \ old version
                   2365: ;
                   2366: 1 0 /
                   2367: @end example
                   2368: 
                   2369: For recursive definitions you can use @code{recursive} (non-standard) or
                   2370: @code{recurse}:
                   2371: 
                   2372: @example
                   2373: : fac1 ( n -- n! ) recursive
                   2374:  dup 0> if
                   2375:    dup 1- fac1 *
                   2376:  else
                   2377:    drop 1
                   2378:  endif ;
                   2379: 7 fac1 .
                   2380: 
                   2381: : fac2 ( n -- n! )
                   2382:  dup 0> if
                   2383:    dup 1- recurse *
                   2384:  else
                   2385:    drop 1
                   2386:  endif ;
                   2387: 8 fac2 .
                   2388: @end example
                   2389: 
                   2390: @assignment
                   2391: Write a recursive definition for computing the nth Fibonacci number.
                   2392: @endassignment
                   2393: 
                   2394: 
                   2395: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
                   2396: @section Leaving definitions or loops
                   2397: 
                   2398: @code{EXIT} exits the current definition right away.  For every counted
                   2399: loop that is left in this way, an @code{UNLOOP} has to be performed
                   2400: before the @code{EXIT}:
                   2401: 
                   2402: @c !! real examples
                   2403: @example
                   2404: : ...
                   2405:  ... u+do
                   2406:    ... if
                   2407:      ... unloop exit
                   2408:    endif
                   2409:    ...
                   2410:  loop
                   2411:  ... ;
                   2412: @end example
                   2413: 
                   2414: @code{LEAVE} leaves the innermost counted loop right away:
                   2415: 
                   2416: @example
                   2417: : ...
                   2418:  ... u+do
                   2419:    ... if
                   2420:      ... leave
                   2421:    endif
                   2422:    ...
                   2423:  loop
                   2424:  ... ;
                   2425: @end example
                   2426: 
                   2427: 
                   2428: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
                   2429: @section Return Stack
                   2430: 
                   2431: In addition to the data stack Forth also has a second stack, the return
                   2432: stack; most Forth systems store the return addresses of procedure calls
                   2433: there (thus its name).  Programmers can also use this stack:
                   2434: 
                   2435: @example
                   2436: : foo ( n1 n2 -- )
                   2437:  .s
                   2438:  >r .s
1.50      anton    2439:  r@@ .
1.48      anton    2440:  >r .s
1.50      anton    2441:  r@@ .
1.48      anton    2442:  r> .
1.50      anton    2443:  r@@ .
1.48      anton    2444:  r> . ;
                   2445: 1 2 foo
                   2446: @end example
                   2447: 
                   2448: @code{>r} takes an element from the data stack and pushes it onto the
                   2449: return stack; conversely, @code{r>} moves an elementm from the return to
                   2450: the data stack; @code{r@@} pushes a copy of the top of the return stack
                   2451: on the return stack.
                   2452: 
                   2453: Forth programmers usually use the return stack for storing data
                   2454: temporarily, if using the data stack alone would be too complex, and
                   2455: factoring and locals are not an option:
                   2456: 
                   2457: @example
                   2458: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
                   2459:  rot >r rot r> ;
                   2460: @end example
                   2461: 
                   2462: The return address of the definition and the loop control parameters of
                   2463: counted loops usually reside on the return stack, so you have to take
                   2464: all items, that you have pushed on the return stack in a colon
                   2465: definition or counted loop, from the return stack before the definition
                   2466: or loop ends.  You cannot access items that you pushed on the return
                   2467: stack outside some definition or loop within the definition of loop.
                   2468: 
                   2469: If you miscount the return stack items, this usually ends in a crash:
                   2470: 
                   2471: @example
                   2472: : crash ( n -- )
                   2473:   >r ;
                   2474: 5 crash
                   2475: @end example
                   2476: 
                   2477: You cannot mix using locals and using the return stack (according to the
                   2478: standard; Gforth has no problem).  However, they solve the same
                   2479: problems, so this shouldn't be an issue.
                   2480: 
                   2481: @assignment
                   2482: Can you rewrite any of the definitions you wrote until now in a better
                   2483: way using the return stack?
                   2484: @endassignment
                   2485: 
                   2486: 
                   2487: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
                   2488: @section Memory
                   2489: 
                   2490: You can create a global variable @code{v} with
                   2491: 
                   2492: @example
                   2493: variable v ( -- addr )
                   2494: @end example
                   2495: 
                   2496: @code{v} pushes the address of a cell in memory on the stack.  This cell
                   2497: was reserved by @code{variable}.  You can use @code{!} (store) to store
                   2498: values into this cell and @code{@@} (fetch) to load the value from the
                   2499: stack into memory:
                   2500: 
                   2501: @example
                   2502: v .
                   2503: 5 v ! .s
1.50      anton    2504: v @@ .
1.48      anton    2505: @end example
                   2506: 
                   2507: You can also reserve more memory:
                   2508: 
                   2509: @example
                   2510: create v2 20 cells allot
                   2511: @end example
                   2512: 
                   2513: creates a word @code{v2} and reserves 20 cells; the address pushed by
                   2514: @code{v2} points to the start of these 20 cells.  You can use address
                   2515: arithmetic to access these cells:
                   2516: 
                   2517: @example
                   2518: 3 v2 5 cells + !
                   2519: @end example
                   2520: 
                   2521: You can reserve and initialize memory with @code{,}:
                   2522: 
                   2523: @example
                   2524: create v3
                   2525:   5 , 4 , 3 , 2 , 1 ,
1.50      anton    2526: v3 @@ .
                   2527: v3 cell+ @@ .
                   2528: v3 2 cells + @@ .
1.48      anton    2529: @end example
                   2530: 
                   2531: @assignment
                   2532: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
                   2533: @code{u} cells, with the first of these cells at @code{addr}, the next
                   2534: one at @code{addr cell+} etc.
                   2535: @endassignment
                   2536: 
                   2537: You can also reserve memory without creating a new word:
                   2538: 
                   2539: @example
                   2540: here 10 cells allot
                   2541: .s
                   2542: @end example
                   2543: 
                   2544: @code{Here} pushes the start address of the memory area.  You should
                   2545: store it somewhere, or you will have a hard time finding the memory area
                   2546: again.
                   2547: 
                   2548: @code{Allot} manages dictionary memory.  The dictionary memory contains
                   2549: the system's data structures for words etc. on Gforth and most other
                   2550: Forth systems.  It is managed like a stack: You can free the memory that
                   2551: you have just @code{allot}ed with
                   2552: 
                   2553: @example
                   2554: -10 cells allot
                   2555: @end example
                   2556: 
                   2557: Note that you cannot do this if you have created a new word in the
                   2558: meantime (because then your @code{allot}ed memory is no longer on the
                   2559: top of the dictionary ``stack'').
                   2560: 
                   2561: Alternatively, you can use @code{allocate} and @code{free} which allow
                   2562: freeing memory in any order:
                   2563: 
                   2564: @example
                   2565: 10 cells allocate throw .s
                   2566: 20 cells allocate throw .s
                   2567: swap
                   2568: free throw
                   2569: free throw
                   2570: @end example
                   2571: 
                   2572: The @code{throw}s deal with errors (e.g., out of memory).
                   2573: 
                   2574: And there is also a garbage collector @url{!!}, which eliminates the
                   2575: need to @code{free} memory explicitly.
                   2576: 
                   2577: 
                   2578: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
                   2579: @section Characters and Strings
                   2580: 
                   2581: On the stack characters take up a cell, like numbers.  In memory they
                   2582: have their own size (one 8-bit byte on most systems), and therefore
                   2583: require their own words for memory access:
                   2584: 
                   2585: @example
                   2586: create v4 
                   2587:   104 c, 97 c, 108 c, 108 c, 111 c,
1.50      anton    2588: v4 4 chars + c@@ .
1.48      anton    2589: @end example
                   2590: 
                   2591: The preferred representation of strings on the stack is @code{addr
                   2592: u-count}, where @code{addr} is the address of the first character and
                   2593: @code{u-count} is the number of characters in the string.
                   2594: 
                   2595: @example
                   2596: v4 5 type
                   2597: @end example
                   2598: 
                   2599: You get a string constant with
                   2600: 
                   2601: @example
                   2602: s" hello, world" .s
                   2603: type
                   2604: @end example
                   2605: 
                   2606: Make sure you have a space between @code{s"} and the string; @code{s"}
                   2607: is a normal Forth word and must be delimited with white space (try what
                   2608: happens when you remove the space).
                   2609: 
                   2610: However, this interpretive use of @code{s"} is quite restricted: the
                   2611: string exists only until the next call of @code{s"} (some Forth systems
                   2612: keep more than one of these strings, but usually they still have a
                   2613: limited lifetime.
                   2614: 
                   2615: @example
                   2616: s" hello," s" world" .s
                   2617: type
                   2618: type
                   2619: @end example
                   2620: 
                   2621: However, you can also use @code{s"} in a definition, and the resulting
                   2622: strings then live forever (well, as long as the definition):
                   2623: 
                   2624: @example
                   2625: : foo s" hello," s" world" ;
                   2626: foo .s
                   2627: type
                   2628: type
                   2629: @end example
                   2630: 
                   2631: @assignment
                   2632: @code{Emit ( c -- )} types @code{c} as character (not a number).
                   2633: Implement @code{type ( addr u -- )}.
                   2634: @endassignment
                   2635: 
                   2636: @node Alignment Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Characters and Strings Tutorial, Tutorial
                   2637: @section Alignment
                   2638: 
                   2639: On many processors cells have to be aligned in memory, if you want to
                   2640: access them with @code{@@} and @code{!} (and even if the processor does
                   2641: not require alignment, access to aligned cells are faster).
                   2642: 
                   2643: @code{Create} aligns @code{here} (i.e., the place where the next
                   2644: allocation will occur, and that the @code{create}d word points to).
                   2645: Likewise, the memory produced by @code{allocate} starts at an aligned
                   2646: address.  Adding a number of @code{cells} to an aligned address produces
                   2647: another aligned address.
                   2648: 
                   2649: However, address arithmetic involving @code{char+} and @code{chars} can
                   2650: create an address that is not cell-aligned.  @code{Aligned ( addr --
                   2651: a-addr )} produces the next aligned address:
                   2652: 
                   2653: @example
1.50      anton    2654: v3 char+ aligned .s @@ .
                   2655: v3 char+ .s @@ .
1.48      anton    2656: @end example
                   2657: 
                   2658: Similarly, @code{align} advances @code{here} to the next aligned
                   2659: address:
                   2660: 
                   2661: @example
                   2662: create v5 97 c,
                   2663: here .
                   2664: align here .
                   2665: 1000 ,
                   2666: @end example
                   2667: 
                   2668: Note that you should use aligned addresses even if your processor does
                   2669: not require them, if you want your program to be portable.
                   2670: 
                   2671: 
                   2672: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Alignment Tutorial, Tutorial
                   2673: @section Interpretation and Compilation Semantics and Immediacy
                   2674: 
                   2675: When a word is compiled, it behaves differently from being interpreted.
                   2676: E.g., consider @code{+}:
                   2677: 
                   2678: @example
                   2679: 1 2 + .
                   2680: : foo + ;
                   2681: @end example
                   2682: 
                   2683: These two behaviours are known as compilation and interpretation
                   2684: semantics.  For normal words (e.g., @code{+}), the compilation semantics
                   2685: is to append the interpretation semantics to the currently defined word
                   2686: (@code{foo} in the example above).  I.e., when @code{foo} is executed
                   2687: later, the interpretation semantics of @code{+} (i.e., adding two
                   2688: numbers) will be performed.
                   2689: 
                   2690: However, there are words with non-default compilation semantics, e.g.,
                   2691: the control-flow words like @code{if}.  You can use @code{immediate} to
                   2692: change the compilation semantics of the last defined word to be equal to
                   2693: the interpretation semantics:
                   2694: 
                   2695: @example
                   2696: : [FOO] ( -- )
                   2697:  5 . ; immediate
                   2698: 
                   2699: [FOO]
                   2700: : bar ( -- )
                   2701:   [FOO] ;
                   2702: bar
                   2703: see bar
                   2704: @end example
                   2705: 
                   2706: Two conventions to mark words with non-default compilation semnatics are
                   2707: names with brackets (more frequently used) and to write them all in
                   2708: upper case (less frequently used).
                   2709: 
                   2710: In Gforth (and many other systems) you can also remove the
                   2711: interpretation semantics with @code{compile-only} (the compilation
                   2712: semantics is derived from the original interpretation semantics):
                   2713: 
                   2714: @example
                   2715: : flip ( -- )
                   2716:  6 . ; compile-only \ but not immediate
                   2717: flip
                   2718: 
                   2719: : flop ( -- )
                   2720:  flip ;
                   2721: flop
                   2722: @end example
                   2723: 
                   2724: In this example the interpretation semantics of @code{flop} is equal to
                   2725: the original interpretation semantics of @code{flip}.
                   2726: 
                   2727: The text interpreter has two states: in interpret state, it performs the
                   2728: interpretation semantics of words it encounters; in compile state, it
                   2729: performs the compilation semantics of these words.
                   2730: 
                   2731: Among other things, @code{:} switches into compile state, and @code{;}
                   2732: switches back to interpret state.  They contain the factors @code{]}
                   2733: (switch to compile state) and @code{[} (switch to interpret state), that
                   2734: do nothing but switch the state.
                   2735: 
                   2736: @example
                   2737: : xxx ( -- )
                   2738:   [ 5 . ]
                   2739: ;
                   2740: 
                   2741: xxx
                   2742: see xxx
                   2743: @end example
                   2744: 
                   2745: These brackets are also the source of the naming convention mentioned
                   2746: above.
                   2747: 
                   2748: 
                   2749: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
                   2750: @section Execution Tokens
                   2751: 
                   2752: @code{' word} gives you the execution token (XT) of a word.  The XT is a
                   2753: cell representing the interpretation semantics of a word.  You can
                   2754: execute this semantics with @code{execute}:
                   2755: 
                   2756: @example
                   2757: ' + .s
                   2758: 1 2 rot execute .
                   2759: @end example
                   2760: 
                   2761: The XT is similar to a function pointer in C.  However, parameter
                   2762: passing through the stack makes it a little more flexible:
                   2763: 
                   2764: @example
                   2765: : map-array ( ... addr u xt -- ... )
1.50      anton    2766: \ executes xt ( ... x -- ... ) for every element of the array starting
                   2767: \ at addr and containing u elements
1.48      anton    2768:   @{ xt @}
                   2769:   cells over + swap ?do
1.50      anton    2770:     i @@ xt execute
1.48      anton    2771:   1 cells +loop ;
                   2772: 
                   2773: create a 3 , 4 , 2 , -1 , 4 ,
                   2774: a 5 ' . map-array .s
                   2775: 0 a 5 ' + map-array .
                   2776: s" max-n" environment? drop .s
                   2777: a 5 ' min map-array .
                   2778: @end example
                   2779: 
                   2780: You can use map-array with the XTs of words that consume one element
                   2781: more than they produce.  In theory you can also use it with other XTs,
                   2782: but the stack effect then depends on the size of the array, which is
                   2783: hard to understand.
                   2784: 
1.51      pazsan   2785: Since XTs are cell-sized, you can store them in memory and manipulate
                   2786: them on the stack like other cells.  You can also compile the XT into a
1.48      anton    2787: word with @code{compile,}:
                   2788: 
                   2789: @example
                   2790: : foo1 ( n1 n2 -- n )
                   2791:    [ ' + compile, ] ;
                   2792: see foo
                   2793: @end example
                   2794: 
                   2795: This is non-standard, because @code{compile,} has no compilation
                   2796: semantics in the standard, but it works in good Forth systems.  For the
                   2797: broken ones, use
                   2798: 
                   2799: @example
                   2800: : [compile,] compile, ; immediate
                   2801: 
                   2802: : foo1 ( n1 n2 -- n )
                   2803:    [ ' + ] [compile,] ;
                   2804: see foo
                   2805: @end example
                   2806: 
                   2807: @code{'} is a word with default compilation semantics; it parses the
                   2808: next word when its interpretation semantics are executed, not during
                   2809: compilation:
                   2810: 
                   2811: @example
                   2812: : foo ( -- xt )
                   2813:   ' ;
                   2814: see foo
                   2815: : bar ( ... "word" -- ... )
                   2816:   ' execute ;
                   2817: see bar
                   2818: 1 2 bar +
                   2819: @end example
                   2820: 
                   2821: You often want to parse a word during compilation and compile its XT so
                   2822: it will be pushed on the stack at run-time.  @code{[']} does this:
                   2823: 
                   2824: @example
                   2825: : xt-+ ( -- xt )
                   2826:   ['] + ;
                   2827: see xt-+
                   2828: 1 2 xt-+ execute .
                   2829: @end example
                   2830: 
                   2831: Many programmers tend to see @code{'} and the word it parses as one
                   2832: unit, and expect it to behave like @code{[']} when compiled, and are
                   2833: confused by the actual behaviour.  If you are, just remember that the
                   2834: Forth system just takes @code{'} as one unit and has no idea that it is
                   2835: a parsing word (attempts to convenience programmers in this issue have
                   2836: usually resulted in even worse pitfalls, see
                   2837: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz}).
                   2838: 
                   2839: Note that the state of the interpreter does not come into play when
1.51      pazsan   2840: creating and executing XTs.  I.e., even when you execute @code{'} in
1.48      anton    2841: compile state, it still gives you the interpretation semantics.  And
                   2842: whatever that state is, @code{execute} performs the semantics
1.51      pazsan   2843: represented by the XT (i.e., the interpretation semantics).
1.48      anton    2844: 
                   2845: 
                   2846: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
                   2847: @section Exceptions
                   2848: 
                   2849: @code{throw ( n -- )} causes an exception unless n is zero.
                   2850: 
                   2851: @example
                   2852: 100 throw .s
                   2853: 0 throw .s
                   2854: @end example
                   2855: 
                   2856: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
                   2857: it catches exceptions and pushes the number of the exception on the
                   2858: stack (or 0, if the xt executed without exception).  If there was an
                   2859: exception, the stacks have the same depth as when entering @code{catch}:
                   2860: 
                   2861: @example
                   2862: .s
                   2863: 3 0 ' / catch .s
                   2864: 3 2 ' / catch .s
                   2865: @end example
                   2866: 
                   2867: @assignment
                   2868: Try the same with @code{execute} instead of @code{catch}.
                   2869: @endassignment
                   2870: 
                   2871: @code{Throw} always jumps to the dynamically next enclosing
                   2872: @code{catch}, even if it has to leave several call levels to achieve
                   2873: this:
                   2874: 
                   2875: @example
                   2876: : foo 100 throw ;
                   2877: : foo1 foo ." after foo" ;
1.51      pazsan   2878: : bar ['] foo1 catch ;
1.48      anton    2879: bar
                   2880: @end example
                   2881: 
                   2882: It is often important to restore a value upon leaving a definition, even
                   2883: if the definition is left through an exception.  You can ensure this
                   2884: like this:
                   2885: 
                   2886: @example
                   2887: : ...
                   2888:    save-x
1.51      pazsan   2889:    ['] word-changing-x catch ( ... n )
1.48      anton    2890:    restore-x
                   2891:    ( ... n ) throw ;
                   2892: @end example
                   2893: 
                   2894: Gforth provides an alternative syntax in addition to @code{cacth}:
                   2895: @code{try ... recover ... endtry}.  If the code between @code{try} and
                   2896: @code{recover} has an exception, the stack depths are restored, the
                   2897: exception number is pushed on the stack, and the code between
                   2898: @code{recover} and @code{endtry} is performed.  E.g., the definition for
                   2899: @code{catch} is
                   2900: 
                   2901: @example
                   2902: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
                   2903:   try
                   2904:     execute 0
                   2905:   recover
                   2906:     nip
                   2907:   endtry ;
                   2908: @end example
                   2909: 
                   2910: The equivalent to the restoration code above is
                   2911: 
                   2912: @example
                   2913: : ...
                   2914:   save-x
                   2915:   try
                   2916:     word-changing-x
                   2917:   end-try
                   2918:   restore-x
                   2919:   throw ;
                   2920: @end example
                   2921: 
                   2922: As you can see, the @code{recover} part is optional.
                   2923: 
                   2924: 
                   2925: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
                   2926: @section Defining Words
                   2927: 
                   2928: @code{:}, @code{create}, and @code{variable} are definition words: They
                   2929: define other words.  @code{Constant} is another definition word:
                   2930: 
                   2931: @example
                   2932: 5 constant foo
                   2933: foo .
                   2934: @end example
                   2935: 
                   2936: You can also use the prefixes @code{2} (double-cell) and @code{f}
                   2937: (floating point) with @code{variable} and @code{constant}.
                   2938: 
                   2939: You can also define your own defining words.  E.g.:
                   2940: 
                   2941: @example
                   2942: : variable ( "name" -- )
                   2943:   create 0 , ;
                   2944: @end example
                   2945: 
                   2946: You can also define defining words that create words that do something
                   2947: other than just producing their address:
                   2948: 
                   2949: @example
                   2950: : constant ( n "name" -- )
                   2951:   create ,
                   2952: does> ( -- n )
1.50      anton    2953:   ( addr ) @@ ;
1.48      anton    2954: 
                   2955: 5 constant foo
                   2956: foo .
                   2957: @end example
                   2958: 
                   2959: The definition of @code{constant} above ends at the @code{does>}; i.e.,
                   2960: @code{does>} replaces @code{;}, but it also does something else: It
                   2961: changes the last defined word such that it pushes the address of the
                   2962: body of the word and then performs the code after the @code{does>}
                   2963: whenever it is called.
                   2964: 
                   2965: In the example above, @code{constant} uses @code{,} to store 5 into the
                   2966: body of @code{foo}.  When @code{foo} executes, it pushes the address of
                   2967: the body onto the stack, then (in the code after the @code{does>})
                   2968: fetches the 5 from there.
                   2969: 
                   2970: The stack comment near the @code{does>} reflects the stack effect of the
                   2971: defined word, not the stack effect of the code after the @code{does>}
                   2972: (the difference is that the code expects the address of the body that
                   2973: the stack comment does not show).
                   2974: 
                   2975: You can use these definition words to do factoring in cases that involve
                   2976: (other) definition words.  E.g., a field offset is always added to an
                   2977: address.  Instead of defining
                   2978: 
                   2979: @example
                   2980: 2 cells constant offset-field1
                   2981: @end example
                   2982: 
                   2983: and using this like
                   2984: 
                   2985: @example
                   2986: ( addr ) offset-field1 +
                   2987: @end example
                   2988: 
                   2989: you can define a definition word
                   2990: 
                   2991: @example
                   2992: : simple-field ( n "name" -- )
                   2993:   create ,
                   2994: does> ( n1 -- n1+n )
1.50      anton    2995:   ( addr ) @@ + ;
1.48      anton    2996: @end example
1.21      crook    2997: 
1.48      anton    2998: Definition and use of field offsets now look like this:
1.21      crook    2999: 
1.48      anton    3000: @example
                   3001: 2 cells simple-field field1
                   3002: ( addr ) field1
                   3003: @end example
1.21      crook    3004: 
1.48      anton    3005: If you want to do something with the word without performing the code
                   3006: after the @code{does>}, you can access the body of a @code{create}d word
                   3007: with @code{>body ( xt -- addr )}:
1.21      crook    3008: 
1.48      anton    3009: @example
                   3010: : value ( n "name" -- )
                   3011:   create ,
                   3012: does> ( -- n1 )
1.50      anton    3013:   @@ ;
1.48      anton    3014: : to ( n "name" -- )
                   3015:   ' >body ! ;
1.21      crook    3016: 
1.48      anton    3017: 5 value foo
                   3018: foo .
                   3019: 7 to foo
                   3020: foo .
                   3021: @end example
1.21      crook    3022: 
1.48      anton    3023: @assignment
                   3024: Define @code{defer ( "name" -- )}, which creates a word that stores an
                   3025: XT (at the start the XT of @code{abort}), and upon execution
                   3026: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
                   3027: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
                   3028: recursion is one application of @code{defer}.
                   3029: @endassignment
1.29      crook    3030: 
1.48      anton    3031: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
                   3032: @section Arrays and Records
1.29      crook    3033: 
1.48      anton    3034: Forth has no standard words for defining data structures such as arrays
                   3035: and records (structs in C terminology), but you can build them yourself
                   3036: based on address arithmetic.  You can also define words for defining
                   3037: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29      crook    3038: 
1.48      anton    3039: One of the first projects a Forth newcomer sets out upon when learning
                   3040: about defining words is an array defining word (possibly for
                   3041: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
                   3042: learn something from it.  However, don't be disappointed when you later
                   3043: learn that you have little use for these words (inappropriate use would
                   3044: be even worse).  I have not yet found a set of useful array words yet;
                   3045: the needs are just too diverse, and named, global arrays (the result of
                   3046: naive use of defining words) are often not flexible enough (e.g.,
                   3047: consider how to pass them as parameters).
1.29      crook    3048: 
1.48      anton    3049: On the other hand, there is a useful set of record words, and it has
                   3050: been defined in @file{compat/struct.fs}; these words are predefined in
                   3051: Gforth.  They are explained in depth elsewhere in this manual (see
                   3052: @pxref{Structures}).  The @code{simple-field} example above is
                   3053: simplified variant of fields in this package.
1.21      crook    3054: 
                   3055: 
1.48      anton    3056: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
                   3057: @section @code{POSTPONE}
1.21      crook    3058: 
1.48      anton    3059: You can compile the compilation semantics (instead of compiling the
                   3060: interpretation semantics) of a word with @code{POSTPONE}:
1.21      crook    3061: 
1.48      anton    3062: @example
                   3063: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51      pazsan   3064:  POSTPONE + ; immediate
1.48      anton    3065: : foo ( n1 n2 -- n )
                   3066:  MY-+ ;
                   3067: 1 2 foo .
                   3068: see foo
                   3069: @end example
1.21      crook    3070: 
1.48      anton    3071: During the definition of @code{foo} the text interpreter performs the
                   3072: compilation semantics of @code{MY-+}, which performs the compilation
                   3073: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
                   3074: 
                   3075: This example also displays separate stack comments for the compilation
                   3076: semantics and for the stack effect of the compiled code.  For words with
                   3077: default compilation semantics these stack effects are usually not
                   3078: displayed; the stack effect of the compilation semantics is always
                   3079: @code{( -- )} for these words, the stack effect for the compiled code is
                   3080: the stack effect of the interpretation semantics.
                   3081: 
                   3082: Note that the state of the interpreter does not come into play when
                   3083: performing the compilation semantics in this way.  You can also perform
                   3084: it interpretively, e.g.:
                   3085: 
                   3086: @example
                   3087: : foo2 ( n1 n2 -- n )
                   3088:  [ MY-+ ] ;
                   3089: 1 2 foo .
                   3090: see foo
                   3091: @end example
1.21      crook    3092: 
1.48      anton    3093: However, there are some broken Forth systems where this does not always
                   3094: work, and therefore this practice has been declared non-standard in
                   3095: 1999.
                   3096: @c !! repair.fs
                   3097: 
                   3098: Here is another example for using @code{POSTPONE}:
1.44      crook    3099: 
1.48      anton    3100: @example
                   3101: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
                   3102:  POSTPONE negate POSTPONE + ; immediate compile-only
                   3103: : bar ( n1 n2 -- n )
                   3104:   MY-- ;
                   3105: 2 1 bar .
                   3106: see bar
                   3107: @end example
1.21      crook    3108: 
1.48      anton    3109: You can define @code{ENDIF} in this way:
1.21      crook    3110: 
1.48      anton    3111: @example
                   3112: : ENDIF ( Compilation: orig -- )
                   3113:   POSTPONE then ; immediate
                   3114: @end example
1.21      crook    3115: 
1.48      anton    3116: @assignment
                   3117: Write @code{MY-2DUP} that has compilation semantics equivalent to
                   3118: @code{2dup}, but compiles @code{over over}.
                   3119: @endassignment
1.29      crook    3120: 
1.48      anton    3121: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
                   3122: @section @code{Literal}
1.29      crook    3123: 
1.48      anton    3124: You cannot @code{POSTPONE} numbers:
1.21      crook    3125: 
1.48      anton    3126: @example
                   3127: : [FOO] POSTPONE 500 ; immediate
1.21      crook    3128: @end example
                   3129: 
1.48      anton    3130: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29      crook    3131: 
1.48      anton    3132: @example
                   3133: : [FOO] ( compilation: --; run-time: -- n )
                   3134:   500 POSTPONE literal ; immediate
1.29      crook    3135: 
1.48      anton    3136: : flip foo ;
                   3137: flip .
                   3138: see flip
                   3139: @end example
1.29      crook    3140: 
1.48      anton    3141: @code{LITERAL} consumes a number at compile-time (when it's compilation
                   3142: semantics are executed) and pushes it at run-time (when the code it
                   3143: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
                   3144: number computed at compile time into the current word:
1.29      crook    3145: 
1.48      anton    3146: @example
                   3147: : bar ( -- n )
                   3148:   [ 2 2 + ] literal ;
                   3149: see bar
                   3150: @end example
1.29      crook    3151: 
1.48      anton    3152: @assignment
                   3153: Write @code{]L} which allows writing the example above as @code{: bar (
                   3154: -- n ) [ 2 2 + ]L ;}
                   3155: @endassignment
                   3156: 
                   3157: 
                   3158: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
                   3159: @section Advanced macros
                   3160: 
                   3161: Reconsider @code{map-array} from @ref{Execution Tokens
                   3162: Tutorial,, Execution Tokens}.  It frequently performs @code{execute}, a
                   3163: relatively expensive operation in some implementations.  You can use
                   3164: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
                   3165: and produce a word that contains the word to be performed directly:
                   3166: 
                   3167: @c use ]] ... [[
                   3168: @example
                   3169: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
                   3170: \ at run-time, execute xt ( ... x -- ... ) for each element of the
                   3171: \ array beginning at addr and containing u elements
                   3172:   @{ xt @}
                   3173:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50      anton    3174:     POSTPONE i POSTPONE @@ xt compile,
1.48      anton    3175:   1 cells POSTPONE literal POSTPONE +loop ;
                   3176: 
                   3177: : sum-array ( addr u -- n )
                   3178:  0 rot rot [ ' + compile-map-array ] ;
                   3179: see sum-array
                   3180: a 5 sum-array .
                   3181: @end example
                   3182: 
                   3183: You can use the full power of Forth for generating the code; here's an
                   3184: example where the code is generated in a loop:
                   3185: 
                   3186: @example
                   3187: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
                   3188: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50      anton    3189:   POSTPONE tuck POSTPONE @@
1.48      anton    3190:   POSTPONE literal POSTPONE * POSTPONE +
                   3191:   POSTPONE swap POSTPONE cell+ ;
                   3192: 
                   3193: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51      pazsan   3194: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48      anton    3195:   0 postpone literal postpone swap
                   3196:   [ ' compile-vmul-step compile-map-array ]
                   3197:   postpone drop ;
                   3198: see compile-vmul
                   3199: 
                   3200: : a-vmul ( addr -- n )
1.51      pazsan   3201: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48      anton    3202:  [ a 5 compile-vmul ] ;
                   3203: see a-vmul
                   3204: a a-vmul .
                   3205: @end example
                   3206: 
                   3207: This example uses @code{compile-map-array} to show off, but you could
                   3208: also use @code{map-array} instead (try it now).
                   3209: 
                   3210: You can use this technique for efficient multiplication of large
                   3211: matrices.  In matrix multiplication, you multiply every line of one
                   3212: matrix with every column of the other matrix.  You can generate the code
                   3213: for one line once, and use it for every column.  The only downside of
                   3214: this technique is that it is cumbersome to recover the memory consumed
                   3215: by the generated code when you are done (and in more complicated cases
                   3216: it is not possible portably).
                   3217: 
                   3218: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
                   3219: @section Compilation Tokens
                   3220: 
                   3221: This section is Gforth-specific.  You can skip it.
                   3222: 
                   3223: @code{' word compile,} compiles the interpretation semantics.  For words
                   3224: with default compilation semantics this is the same as performing the
                   3225: compilation semantics.  To represent the compilation semantics of other
                   3226: words (e.g., words like @code{if} that have no interpretation
                   3227: semantics), Gforth has the concept of a compilation token (CT,
                   3228: consisting of two cells), and words @code{comp'} and @code{[comp']}.
                   3229: You can perform the compilation semantics represented by a CT with
                   3230: @code{execute}:
1.29      crook    3231: 
1.48      anton    3232: @example
                   3233: : foo2 ( n1 n2 -- n )
                   3234:    [ comp' + execute ] ;
                   3235: see foo
                   3236: @end example
1.29      crook    3237: 
1.48      anton    3238: You can compile the compilation semantics represented by a CT with
                   3239: @code{postpone,}:
1.30      anton    3240: 
1.48      anton    3241: @example
                   3242: : foo3 ( -- )
                   3243:   [ comp' + postpone, ] ;
                   3244: see foo3
                   3245: @end example
1.30      anton    3246: 
1.51      pazsan   3247: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48      anton    3248: @code{comp'} is particularly useful for words that have no
                   3249: interpretation semantics:
1.29      crook    3250: 
1.30      anton    3251: @example
1.48      anton    3252: ' if
                   3253: comp' if .s
1.30      anton    3254: @end example
                   3255: 
1.29      crook    3256: 
1.48      anton    3257: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
                   3258: @section Wordlists and Search Order
                   3259: 
                   3260: The dictionary is not just a memory area that allows you to allocate
                   3261: memory with @code{allot}, it also contains the Forth words, arranged in
                   3262: several wordlists.  When searching for a word in a wordlist,
                   3263: conceptually you start searching at the youngest and proceed towards
                   3264: older words (in reality most systems nowadays use hash-tables); i.e., if
                   3265: you define a word with the same name as an older word, the new word
                   3266: shadows the older word.
                   3267: 
                   3268: Which wordlists are searched in which order is determined by the search
                   3269: order.  You can display the search order with @code{order}.  It displays
                   3270: first the search order, starting with the wordlist searched first, then
                   3271: it displays the wordlist that will contain newly defined words.
1.21      crook    3272: 
1.48      anton    3273: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21      crook    3274: 
1.48      anton    3275: @example
                   3276: wordlist constant mywords
                   3277: @end example
1.21      crook    3278: 
1.48      anton    3279: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
                   3280: defined words (the @emph{current} wordlist):
1.21      crook    3281: 
1.48      anton    3282: @example
                   3283: mywords set-current
                   3284: order
                   3285: @end example
1.26      crook    3286: 
1.48      anton    3287: Gforth does not display a name for the wordlist in @code{mywords}
                   3288: because this wordlist was created anonymously with @code{wordlist}.
1.21      crook    3289: 
1.48      anton    3290: You can get the current wordlist with @code{get-current ( -- wid)}.  If
                   3291: you want to put something into a specific wordlist without overall
                   3292: effect on the current wordlist, this typically looks like this:
1.21      crook    3293: 
1.48      anton    3294: @example
                   3295: get-current mywords set-current ( wid )
                   3296: create someword
                   3297: ( wid ) set-current
                   3298: @end example
1.21      crook    3299: 
1.48      anton    3300: You can write the search order with @code{set-order ( wid1 .. widn n --
                   3301: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
                   3302: searched wordlist is topmost.
1.21      crook    3303: 
1.48      anton    3304: @example
                   3305: get-order mywords swap 1+ set-order
                   3306: order
                   3307: @end example
1.21      crook    3308: 
1.48      anton    3309: Yes, the order of wordlists in the output of @code{order} is reversed
                   3310: from stack comments and the output of @code{.s} and thus unintuitive.
1.21      crook    3311: 
1.48      anton    3312: @assignment
                   3313: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
                   3314: wordlist to the search order.  Define @code{previous ( -- )}, which
                   3315: removes the first searched wordlist from the search order.  Experiment
                   3316: with boundary conditions (you will see some crashes or situations that
                   3317: are hard or impossible to leave).
                   3318: @endassignment
1.21      crook    3319: 
1.48      anton    3320: The search order is a powerful foundation for providing features similar
                   3321: to Modula-2 modules and C++ namespaces.  However, trying to modularize
                   3322: programs in this way has disadvantages for debugging and reuse/factoring
                   3323: that overcome the advantages in my experience (I don't do huge projects,
                   3324: though).  These disadvanategs are not so clear in other
                   3325: languages/programming environments, because these langauges are not so
                   3326: strong in debugging and reuse.
1.21      crook    3327: 
                   3328: 
1.29      crook    3329: @c ******************************************************************
1.48      anton    3330: @node Introduction, Words, Tutorial, Top
1.29      crook    3331: @comment node-name,     next,           previous, up
                   3332: @chapter An Introduction to ANS Forth
                   3333: @cindex Forth - an introduction
1.21      crook    3334: 
1.29      crook    3335: The primary purpose of this manual is to document Gforth. However, since
                   3336: Forth is not a widely-known language and there is a lack of up-to-date
                   3337: teaching material, it seems worthwhile to provide some introductory
1.49      anton    3338: material.  For other sources of Forth-related
                   3339: information, see @ref{Forth-related information}.
1.21      crook    3340: 
1.29      crook    3341: The examples in this section should work on any ANS Forth; the
                   3342: output shown was produced using Gforth. Each example attempts to
                   3343: reproduce the exact output that Gforth produces. If you try out the
                   3344: examples (and you should), what you should type is shown @kbd{like this}
                   3345: and Gforth's response is shown @code{like this}. The single exception is
1.30      anton    3346: that, where the example shows @key{RET} it means that you should
1.29      crook    3347: press the ``carriage return'' key. Unfortunately, some output formats for
                   3348: this manual cannot show the difference between @kbd{this} and
                   3349: @code{this} which will make trying out the examples harder (but not
                   3350: impossible).
1.21      crook    3351: 
1.29      crook    3352: Forth is an unusual language. It provides an interactive development
                   3353: environment which includes both an interpreter and compiler. Forth
                   3354: programming style encourages you to break a problem down into many
                   3355: @cindex factoring
                   3356: small fragments (@dfn{factoring}), and then to develop and test each
                   3357: fragment interactively. Forth advocates assert that breaking the
                   3358: edit-compile-test cycle used by conventional programming languages can
                   3359: lead to great productivity improvements.
1.21      crook    3360: 
1.29      crook    3361: @menu
                   3362: * Introducing the Text Interpreter::
                   3363: * Stacks and Postfix notation::
                   3364: * Your first definition::
                   3365: * How does that work?::
                   3366: * Forth is written in Forth::
                   3367: * Review - elements of a Forth system::
                   3368: * Where to go next::
                   3369: * Exercises::
                   3370: @end menu
1.21      crook    3371: 
1.29      crook    3372: @comment ----------------------------------------------
                   3373: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
                   3374: @section Introducing the Text Interpreter
                   3375: @cindex text interpreter
                   3376: @cindex outer interpreter
1.21      crook    3377: 
1.30      anton    3378: @c IMO this is too detailed and the pace is too slow for
                   3379: @c an introduction.  If you know German, take a look at
                   3380: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
                   3381: @c to see how I do it - anton 
                   3382: 
1.44      crook    3383: @c nac-> Where I have accepted your comments 100% and modified the text
                   3384: @c accordingly, I have deleted your comments. Elsewhere I have added a
                   3385: @c response like this to attempt to rationalise what I have done. Of
                   3386: @c course, this is a very clumsy mechanism for something that would be
                   3387: @c done far more efficiently over a beer. Please delete any dialogue
                   3388: @c you consider closed.
                   3389: 
1.29      crook    3390: When you invoke the Forth image, you will see a startup banner printed
                   3391: and nothing else (if you have Gforth installed on your system, try
1.30      anton    3392: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29      crook    3393: its command line interpreter, which is called the @dfn{Text Interpreter}
                   3394: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
1.49      anton    3395: about the text interpreter as you read through this chapter, for more
                   3396: detail @pxref{The Text Interpreter}).
1.21      crook    3397: 
1.29      crook    3398: Although it's not obvious, Forth is actually waiting for your
1.30      anton    3399: input. Type a number and press the @key{RET} key:
1.21      crook    3400: 
1.26      crook    3401: @example
1.30      anton    3402: @kbd{45@key{RET}}  ok
1.26      crook    3403: @end example
1.21      crook    3404: 
1.29      crook    3405: Rather than give you a prompt to invite you to input something, the text
                   3406: interpreter prints a status message @i{after} it has processed a line
                   3407: of input. The status message in this case (``@code{ ok}'' followed by
                   3408: carriage-return) indicates that the text interpreter was able to process
                   3409: all of your input successfully. Now type something illegal:
                   3410: 
                   3411: @example
1.30      anton    3412: @kbd{qwer341@key{RET}}
1.29      crook    3413: :1: Undefined word
                   3414: qwer341
                   3415: ^^^^^^^
                   3416: $400D2BA8 Bounce
                   3417: $400DBDA8 no.extensions
                   3418: @end example
1.23      crook    3419: 
1.29      crook    3420: The exact text, other than the ``Undefined word'' may differ slightly on
                   3421: your system, but the effect is the same; when the text interpreter
                   3422: detects an error, it discards any remaining text on a line, resets
1.49      anton    3423: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
                   3424: messages}.
1.23      crook    3425: 
1.29      crook    3426: The text interpreter waits for you to press carriage-return, and then
                   3427: processes your input line. Starting at the beginning of the line, it
                   3428: breaks the line into groups of characters separated by spaces. For each
                   3429: group of characters in turn, it makes two attempts to do something:
1.23      crook    3430: 
1.29      crook    3431: @itemize @bullet
                   3432: @item
1.44      crook    3433: @cindex name dictionary
1.29      crook    3434: It tries to treat it as a command. It does this by searching a @dfn{name
                   3435: dictionary}. If the group of characters matches an entry in the name
                   3436: dictionary, the name dictionary provides the text interpreter with
                   3437: information that allows the text interpreter perform some actions. In
                   3438: Forth jargon, we say that the group
                   3439: @cindex word
                   3440: @cindex definition
                   3441: @cindex execution token
                   3442: @cindex xt
                   3443: of characters names a @dfn{word}, that the dictionary search returns an
                   3444: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
                   3445: word, and that the text interpreter executes the xt. Often, the terms
                   3446: @dfn{word} and @dfn{definition} are used interchangeably.
                   3447: @item
                   3448: If the text interpreter fails to find a match in the name dictionary, it
                   3449: tries to treat the group of characters as a number in the current number
                   3450: base (when you start up Forth, the current number base is base 10). If
                   3451: the group of characters legitimately represents a number, the text
                   3452: interpreter pushes the number onto a stack (we'll learn more about that
                   3453: in the next section).
                   3454: @end itemize
1.23      crook    3455: 
1.29      crook    3456: If the text interpreter is unable to do either of these things with any
                   3457: group of characters, it discards the group of characters and the rest of
                   3458: the line, then prints an error message. If the text interpreter reaches
                   3459: the end of the line without error, it prints the status message ``@code{ ok}''
                   3460: followed by carriage-return.
1.21      crook    3461: 
1.29      crook    3462: This is the simplest command we can give to the text interpreter:
1.23      crook    3463: 
                   3464: @example
1.30      anton    3465: @key{RET}  ok
1.23      crook    3466: @end example
1.21      crook    3467: 
1.29      crook    3468: The text interpreter did everything we asked it to do (nothing) without
                   3469: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
                   3470: command:
1.21      crook    3471: 
1.23      crook    3472: @example
1.30      anton    3473: @kbd{12 dup fred dup@key{RET}}
1.29      crook    3474: :1: Undefined word
                   3475: 12 dup fred dup
                   3476:        ^^^^
                   3477: $400D2BA8 Bounce
                   3478: $400DBDA8 no.extensions
1.23      crook    3479: @end example
1.21      crook    3480: 
1.29      crook    3481: When you press the carriage-return key, the text interpreter starts to
                   3482: work its way along the line:
1.21      crook    3483: 
1.29      crook    3484: @itemize @bullet
                   3485: @item
                   3486: When it gets to the space after the @code{2}, it takes the group of
                   3487: characters @code{12} and looks them up in the name
                   3488: dictionary@footnote{We can't tell if it found them or not, but assume
                   3489: for now that it did not}. There is no match for this group of characters
                   3490: in the name dictionary, so it tries to treat them as a number. It is
                   3491: able to do this successfully, so it puts the number, 12, ``on the stack''
                   3492: (whatever that means).
                   3493: @item
                   3494: The text interpreter resumes scanning the line and gets the next group
                   3495: of characters, @code{dup}. It looks it up in the name dictionary and
                   3496: (you'll have to take my word for this) finds it, and executes the word
                   3497: @code{dup} (whatever that means).
                   3498: @item
                   3499: Once again, the text interpreter resumes scanning the line and gets the
                   3500: group of characters @code{fred}. It looks them up in the name
                   3501: dictionary, but can't find them. It tries to treat them as a number, but
                   3502: they don't represent any legal number.
                   3503: @end itemize
1.21      crook    3504: 
1.29      crook    3505: At this point, the text interpreter gives up and prints an error
                   3506: message. The error message shows exactly how far the text interpreter
                   3507: got in processing the line. In particular, it shows that the text
                   3508: interpreter made no attempt to do anything with the final character
                   3509: group, @code{dup}, even though we have good reason to believe that the
                   3510: text interpreter would have no problem looking that word up and
                   3511: executing it a second time.
1.21      crook    3512: 
                   3513: 
1.29      crook    3514: @comment ----------------------------------------------
                   3515: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
                   3516: @section Stacks, postfix notation and parameter passing
                   3517: @cindex text interpreter
                   3518: @cindex outer interpreter
1.21      crook    3519: 
1.29      crook    3520: In procedural programming languages (like C and Pascal), the
                   3521: building-block of programs is the @dfn{function} or @dfn{procedure}. These
                   3522: functions or procedures are called with @dfn{explicit parameters}. For
                   3523: example, in C we might write:
1.21      crook    3524: 
1.23      crook    3525: @example
1.29      crook    3526: total = total + new_volume(length,height,depth);
1.23      crook    3527: @end example
1.21      crook    3528: 
1.23      crook    3529: @noindent
1.29      crook    3530: where new_volume is a function-call to another piece of code, and total,
                   3531: length, height and depth are all variables. length, height and depth are
                   3532: parameters to the function-call.
1.21      crook    3533: 
1.29      crook    3534: In Forth, the equivalent of the function or procedure is the
                   3535: @dfn{definition} and parameters are implicitly passed between
                   3536: definitions using a shared stack that is visible to the
                   3537: programmer. Although Forth does support variables, the existence of the
                   3538: stack means that they are used far less often than in most other
                   3539: programming languages. When the text interpreter encounters a number, it
                   3540: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30      anton    3541: actual number is implementation-dependent ...) and the particular stack
1.29      crook    3542: used for any operation is implied unambiguously by the operation being
                   3543: performed. The stack used for all integer operations is called the @dfn{data
                   3544: stack} and, since this is the stack used most commonly, references to
                   3545: ``the data stack'' are often abbreviated to ``the stack''.
1.21      crook    3546: 
1.29      crook    3547: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21      crook    3548: 
1.23      crook    3549: @example
1.30      anton    3550: @kbd{1 2 3@key{RET}}  ok
1.23      crook    3551: @end example
1.21      crook    3552: 
1.29      crook    3553: Then this instructs the text interpreter to placed three numbers on the
                   3554: (data) stack. An analogy for the behaviour of the stack is to take a
                   3555: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
                   3556: the table. The 3 was the last card onto the pile (``last-in'') and if
                   3557: you take a card off the pile then, unless you're prepared to fiddle a
                   3558: bit, the card that you take off will be the 3 (``first-out''). The
                   3559: number that will be first-out of the stack is called the @dfn{top of
                   3560: stack}, which
                   3561: @cindex TOS definition
                   3562: is often abbreviated to @dfn{TOS}.
1.21      crook    3563: 
1.29      crook    3564: To understand how parameters are passed in Forth, consider the
                   3565: behaviour of the definition @code{+} (pronounced ``plus''). You will not
                   3566: be surprised to learn that this definition performs addition. More
                   3567: precisely, it adds two number together and produces a result. Where does
                   3568: it get the two numbers from? It takes the top two numbers off the
                   3569: stack. Where does it place the result? On the stack. You can act-out the
                   3570: behaviour of @code{+} with your playing cards like this:
1.21      crook    3571: 
                   3572: @itemize @bullet
                   3573: @item
1.29      crook    3574: Pick up two cards from the stack on the table
1.21      crook    3575: @item
1.29      crook    3576: Stare at them intently and ask yourself ``what @i{is} the sum of these two
                   3577: numbers''
1.21      crook    3578: @item
1.29      crook    3579: Decide that the answer is 5
1.21      crook    3580: @item
1.29      crook    3581: Shuffle the two cards back into the pack and find a 5
1.21      crook    3582: @item
1.29      crook    3583: Put a 5 on the remaining ace that's on the table.
1.21      crook    3584: @end itemize
                   3585: 
1.29      crook    3586: If you don't have a pack of cards handy but you do have Forth running,
                   3587: you can use the definition @code{.s} to show the current state of the stack,
                   3588: without affecting the stack. Type:
1.21      crook    3589: 
                   3590: @example
1.30      anton    3591: @kbd{clearstack 1 2 3@key{RET}} ok
                   3592: @kbd{.s@key{RET}} <3> 1 2 3  ok
1.23      crook    3593: @end example
                   3594: 
1.29      crook    3595: The text interpreter looks up the word @code{clearstack} and executes
                   3596: it; it tidies up the stack and removes any entries that may have been
                   3597: left on it by earlier examples. The text interpreter pushes each of the
                   3598: three numbers in turn onto the stack. Finally, the text interpreter
                   3599: looks up the word @code{.s} and executes it. The effect of executing
                   3600: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
                   3601: followed by a list of all the items on the stack; the item on the far
                   3602: right-hand side is the TOS.
1.21      crook    3603: 
1.29      crook    3604: You can now type:
1.21      crook    3605: 
1.29      crook    3606: @example
1.30      anton    3607: @kbd{+ .s@key{RET}} <2> 1 5  ok
1.29      crook    3608: @end example
1.21      crook    3609: 
1.29      crook    3610: @noindent
                   3611: which is correct; there are now 2 items on the stack and the result of
                   3612: the addition is 5.
1.23      crook    3613: 
1.29      crook    3614: If you're playing with cards, try doing a second addition: pick up the
                   3615: two cards, work out that their sum is 6, shuffle them into the pack,
                   3616: look for a 6 and place that on the table. You now have just one item on
                   3617: the stack. What happens if you try to do a third addition? Pick up the
                   3618: first card, pick up the second card -- ah! There is no second card. This
                   3619: is called a @dfn{stack underflow} and consitutes an error. If you try to
                   3620: do the same thing with Forth it will report an error (probably a Stack
                   3621: Underflow or an Invalid Memory Address error).
1.23      crook    3622: 
1.29      crook    3623: The opposite situation to a stack underflow is a @dfn{stack overflow},
                   3624: which simply accepts that there is a finite amount of storage space
                   3625: reserved for the stack. To stretch the playing card analogy, if you had
                   3626: enough packs of cards and you piled the cards up on the table, you would
                   3627: eventually be unable to add another card; you'd hit the ceiling. Gforth
                   3628: allows you to set the maximum size of the stacks. In general, the only
                   3629: time that you will get a stack overflow is because a definition has a
                   3630: bug in it and is generating data on the stack uncontrollably.
1.23      crook    3631: 
1.29      crook    3632: There's one final use for the playing card analogy. If you model your
                   3633: stack using a pack of playing cards, the maximum number of items on
                   3634: your stack will be 52 (I assume you didn't use the Joker). The maximum
                   3635: @i{value} of any item on the stack is 13 (the King). In fact, the only
                   3636: possible numbers are positive integer numbers 1 through 13; you can't
                   3637: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
                   3638: think about some of the cards, you can accommodate different
                   3639: numbers. For example, you could think of the Jack as representing 0,
                   3640: the Queen as representing -1 and the King as representing -2. Your
1.45      crook    3641: @i{range} remains unchanged (you can still only represent a total of 13
1.29      crook    3642: numbers) but the numbers that you can represent are -2 through 10.
1.28      crook    3643: 
1.29      crook    3644: In that analogy, the limit was the amount of information that a single
                   3645: stack entry could hold, and Forth has a similar limit. In Forth, the
                   3646: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
                   3647: implementation dependent and affects the maximum value that a stack
                   3648: entry can hold. A Standard Forth provides a cell size of at least
                   3649: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21      crook    3650: 
1.29      crook    3651: Forth does not do any type checking for you, so you are free to
                   3652: manipulate and combine stack items in any way you wish. A convenient way
                   3653: of treating stack items is as 2's complement signed integers, and that
                   3654: is what Standard words like @code{+} do. Therefore you can type:
1.21      crook    3655: 
1.29      crook    3656: @example
1.30      anton    3657: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
1.29      crook    3658: @end example
1.21      crook    3659: 
1.29      crook    3660: If you use numbers and definitions like @code{+} in order to turn Forth
                   3661: into a great big pocket calculator, you will realise that it's rather
                   3662: different from a normal calculator. Rather than typing 2 + 3 = you had
                   3663: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
                   3664: result). The terminology used to describe this difference is to say that
                   3665: your calculator uses @dfn{Infix Notation} (parameters and operators are
                   3666: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
                   3667: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21      crook    3668: 
1.29      crook    3669: Whilst postfix notation might look confusing to begin with, it has
                   3670: several important advantages:
1.21      crook    3671: 
1.23      crook    3672: @itemize @bullet
                   3673: @item
1.29      crook    3674: it is unambiguous
1.23      crook    3675: @item
1.29      crook    3676: it is more concise
1.23      crook    3677: @item
1.29      crook    3678: it fits naturally with a stack-based system
1.23      crook    3679: @end itemize
1.21      crook    3680: 
1.29      crook    3681: To examine these claims in more detail, consider these sums:
1.21      crook    3682: 
1.29      crook    3683: @example
                   3684: 6 + 5 * 4 =
                   3685: 4 * 5 + 6 =
                   3686: @end example
1.21      crook    3687: 
1.29      crook    3688: If you're just learning maths or your maths is very rusty, you will
                   3689: probably come up with the answer 44 for the first and 26 for the
                   3690: second. If you are a bit of a whizz at maths you will remember the
                   3691: @i{convention} that multiplication takes precendence over addition, and
                   3692: you'd come up with the answer 26 both times. To explain the answer 26
                   3693: to someone who got the answer 44, you'd probably rewrite the first sum
                   3694: like this:
1.21      crook    3695: 
1.29      crook    3696: @example
                   3697: 6 + (5 * 4) =
                   3698: @end example
1.21      crook    3699: 
1.29      crook    3700: If what you really wanted was to perform the addition before the
                   3701: multiplication, you would have to use parentheses to force it.
1.21      crook    3702: 
1.29      crook    3703: If you did the first two sums on a pocket calculator you would probably
                   3704: get the right answers, unless you were very cautious and entered them using
                   3705: these keystroke sequences:
1.21      crook    3706: 
1.29      crook    3707: 6 + 5 = * 4 =
                   3708: 4 * 5 = + 6 =
1.21      crook    3709: 
1.29      crook    3710: Postfix notation is unambiguous because the order that the operators
                   3711: are applied is always explicit; that also means that parentheses are
                   3712: never required. The operators are @i{active} (the act of quoting the
                   3713: operator makes the operation occur) which removes the need for ``=''.
1.28      crook    3714: 
1.29      crook    3715: The sum 6 + 5 * 4 can be written (in postfix notation) in two
                   3716: equivalent ways:
1.26      crook    3717: 
                   3718: @example
1.29      crook    3719: 6 5 4 * +      or:
                   3720: 5 4 * 6 +
1.26      crook    3721: @end example
1.23      crook    3722: 
1.29      crook    3723: An important thing that you should notice about this notation is that
                   3724: the @i{order} of the numbers does not change; if you want to subtract
                   3725: 2 from 10 you type @code{10 2 -}.
1.1       anton    3726: 
1.29      crook    3727: The reason that Forth uses postfix notation is very simple to explain: it
                   3728: makes the implementation extremely simple, and it follows naturally from
                   3729: using the stack as a mechanism for passing parameters. Another way of
                   3730: thinking about this is to realise that all Forth definitions are
                   3731: @i{active}; they execute as they are encountered by the text
                   3732: interpreter. The result of this is that the syntax of Forth is trivially
                   3733: simple.
1.1       anton    3734: 
                   3735: 
                   3736: 
1.29      crook    3737: @comment ----------------------------------------------
                   3738: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
                   3739: @section Your first Forth definition
                   3740: @cindex first definition
1.1       anton    3741: 
1.29      crook    3742: Until now, the examples we've seen have been trivial; we've just been
                   3743: using Forth as a bigger-than-pocket calculator. Also, each calculation
                   3744: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
                   3745: again@footnote{That's not quite true. If you press the up-arrow key on
                   3746: your keyboard you should be able to scroll back to any earlier command,
                   3747: edit it and re-enter it.} In this section we'll see how to add new
                   3748: words to Forth's vocabulary.
1.1       anton    3749: 
1.29      crook    3750: The easiest way to create a new word is to use a @dfn{colon
                   3751: definition}. We'll define a few and try them out before worrying too
                   3752: much about how they work. Try typing in these examples; be careful to
                   3753: copy the spaces accurately:
1.1       anton    3754: 
1.29      crook    3755: @example
                   3756: : add-two 2 + . ;
                   3757: : greet ." Hello and welcome" ;
                   3758: : demo 5 add-two ;
                   3759: @end example
1.1       anton    3760: 
1.29      crook    3761: @noindent
                   3762: Now try them out:
1.1       anton    3763: 
1.29      crook    3764: @example
1.30      anton    3765: @kbd{greet@key{RET}} Hello and welcome  ok
                   3766: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
                   3767: @kbd{4 add-two@key{RET}} 6  ok
                   3768: @kbd{demo@key{RET}} 7  ok
                   3769: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
1.29      crook    3770: @end example
1.1       anton    3771: 
1.29      crook    3772: The first new thing that we've introduced here is the pair of words
                   3773: @code{:} and @code{;}. These are used to start and terminate a new
                   3774: definition, respectively. The first word after the @code{:} is the name
                   3775: for the new definition.
1.1       anton    3776: 
1.29      crook    3777: As you can see from the examples, a definition is built up of words that
                   3778: have already been defined; Forth makes no distinction between
                   3779: definitions that existed when you started the system up, and those that
                   3780: you define yourself.
1.1       anton    3781: 
1.29      crook    3782: The examples also introduce the words @code{.} (dot), @code{."}
                   3783: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
                   3784: the stack and displays it. It's like @code{.s} except that it only
                   3785: displays the top item of the stack and it is destructive; after it has
                   3786: executed, the number is no longer on the stack. There is always one
                   3787: space printed after the number, and no spaces before it. Dot-quote
                   3788: defines a string (a sequence of characters) that will be printed when
                   3789: the word is executed. The string can contain any printable characters
                   3790: except @code{"}. A @code{"} has a special function; it is not a Forth
                   3791: word but it acts as a delimiter (the way that delimiters work is
                   3792: described in the next section). Finally, @code{dup} duplicates the value
                   3793: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1       anton    3794: 
1.29      crook    3795: We already know that the text interpreter searches through the
                   3796: dictionary to locate names. If you've followed the examples earlier, you
                   3797: will already have a definition called @code{add-two}. Lets try modifying
                   3798: it by typing in a new definition:
1.1       anton    3799: 
1.29      crook    3800: @example
1.30      anton    3801: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
1.29      crook    3802: @end example
1.5       anton    3803: 
1.29      crook    3804: Forth recognised that we were defining a word that already exists, and
                   3805: printed a message to warn us of that fact. Let's try out the new
                   3806: definition:
1.5       anton    3807: 
1.29      crook    3808: @example
1.30      anton    3809: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
1.29      crook    3810: @end example
1.1       anton    3811: 
1.29      crook    3812: @noindent
                   3813: All that we've actually done here, though, is to create a new
                   3814: definition, with a particular name. The fact that there was already a
                   3815: definition with the same name did not make any difference to the way
                   3816: that the new definition was created (except that Forth printed a warning
                   3817: message). The old definition of add-two still exists (try @code{demo}
                   3818: again to see that this is true). Any new definition will use the new
                   3819: definition of @code{add-two}, but old definitions continue to use the
                   3820: version that already existed at the time that they were @code{compiled}.
1.1       anton    3821: 
1.29      crook    3822: Before you go on to the next section, try defining and redefining some
                   3823: words of your own.
1.1       anton    3824: 
1.29      crook    3825: @comment ----------------------------------------------
                   3826: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
                   3827: @section How does that work?
                   3828: @cindex parsing words
1.1       anton    3829: 
1.30      anton    3830: @c That's pretty deep (IMO way too deep) for an introduction. - anton
                   3831: 
                   3832: @c Is it a good idea to talk about the interpretation semantics of a
                   3833: @c number? We don't have an xt to go along with it. - anton
                   3834: 
                   3835: @c Now that I have eliminated execution semantics, I wonder if it would not
                   3836: @c be better to keep them (or add run-time semantics), to make it easier to
                   3837: @c explain what compilation semantics usually does. - anton
                   3838: 
1.44      crook    3839: @c nac-> I removed the term ``default compilation sematics'' from the
                   3840: @c introductory chapter. Removing ``execution semantics'' was making
                   3841: @c everything simpler to explain, then I think the use of this term made
                   3842: @c everything more complex again. I replaced it with ``default
                   3843: @c semantics'' (which is used elsewhere in the manual) by which I mean
                   3844: @c ``a definition that has neither the immediate nor the compile-only
                   3845: @c flag set''. I reworded big chunks of the ``how does that work''
                   3846: @c section (and, unusually for me, I think I even made it shorter!).  See
                   3847: @c what you think -- I know I have not addressed your primary concern
                   3848: @c that it is too heavy-going for an introduction. From what I understood
                   3849: @c of your course notes it looks as though they might be a good framework. 
                   3850: @c Things that I've tried to capture here are some things that came as a
                   3851: @c great revelation here when I first understood them. Also, I like the
                   3852: @c fact that a very simple code example shows up almost all of the issues
                   3853: @c that you need to understand to see how Forth works. That's unique and
                   3854: @c worthwhile to emphasise.
                   3855: 
1.29      crook    3856: Now we're going to take another look at the definition of @code{add-two}
                   3857: from the previous section. From our knowledge of the way that the text
                   3858: interpreter works, we would have expected this result when we tried to
                   3859: define @code{add-two}:
1.21      crook    3860: 
1.29      crook    3861: @example
1.44      crook    3862: @kbd{: add-two 2 + . ;@key{RET}}
1.29      crook    3863:   ^^^^^^^
                   3864: Error: Undefined word
                   3865: @end example
1.28      crook    3866: 
1.29      crook    3867: The reason that this didn't happen is bound up in the way that @code{:}
                   3868: works. The word @code{:} does two special things. The first special
                   3869: thing that it does prevents the text interpreter from ever seeing the
                   3870: characters @code{add-two}. The text interpreter uses a variable called
                   3871: @cindex modifying >IN
1.44      crook    3872: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29      crook    3873: input line. When it encounters the word @code{:} it behaves in exactly
                   3874: the same way as it does for any other word; it looks it up in the name
                   3875: dictionary, finds its xt and executes it. When @code{:} executes, it
                   3876: looks at the input buffer, finds the word @code{add-two} and advances the
                   3877: value of @code{>IN} to point past it. It then does some other stuff
                   3878: associated with creating the new definition (including creating an entry
                   3879: for @code{add-two} in the name dictionary). When the execution of @code{:}
                   3880: completes, control returns to the text interpreter, which is oblivious
                   3881: to the fact that it has been tricked into ignoring part of the input
                   3882: line.
1.21      crook    3883: 
1.29      crook    3884: @cindex parsing words
                   3885: Words like @code{:} -- words that advance the value of @code{>IN} and so
                   3886: prevent the text interpreter from acting on the whole of the input line
                   3887: -- are called @dfn{parsing words}.
1.21      crook    3888: 
1.29      crook    3889: @cindex @code{state} - effect on the text interpreter
                   3890: @cindex text interpreter - effect of state
                   3891: The second special thing that @code{:} does is change the value of a
                   3892: variable called @code{state}, which affects the way that the text
                   3893: interpreter behaves. When Gforth starts up, @code{state} has the value
                   3894: 0, and the text interpreter is said to be @dfn{interpreting}. During a
                   3895: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44      crook    3896: the text interpreter is said to be @dfn{compiling}.
                   3897: 
                   3898: In this example, the text interpreter is compiling when it processes the
                   3899: string ``@code{2 + . ;}''. It still breaks the string down into
                   3900: character sequences in the same way. However, instead of pushing the
                   3901: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
                   3902: into the definition of @code{add-two} that will make the number @code{2} get
                   3903: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
                   3904: the behaviours of @code{+} and @code{.} are also compiled into the
                   3905: definition.
                   3906: 
                   3907: One category of words don't get compiled. These so-called @dfn{immediate
                   3908: words} get executed (performed @i{now}) regardless of whether the text
                   3909: interpreter is interpreting or compiling. The word @code{;} is an
                   3910: immediate word. Rather than being compiled into the definition, it
                   3911: executes. Its effect is to terminate the current definition, which
                   3912: includes changing the value of @code{state} back to 0.
                   3913: 
                   3914: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
                   3915: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
                   3916: definition.
1.28      crook    3917: 
1.30      anton    3918: In Forth, every word or number can be described in terms of two
1.29      crook    3919: properties:
1.28      crook    3920: 
                   3921: @itemize @bullet
                   3922: @item
1.29      crook    3923: @cindex interpretation semantics
1.44      crook    3924: Its @dfn{interpretation semantics} describe how it will behave when the
                   3925: text interpreter encounters it in @dfn{interpret} state. The
                   3926: interpretation semantics of a word are represented by an @dfn{execution
                   3927: token}.
1.28      crook    3928: @item
1.29      crook    3929: @cindex compilation semantics
1.44      crook    3930: Its @dfn{compilation semantics} describe how it will behave when the
                   3931: text interpreter encounters it in @dfn{compile} state. The compilation
                   3932: semantics of a word are represented in an implementation-dependent way;
                   3933: Gforth uses a @dfn{compilation token}.
1.29      crook    3934: @end itemize
                   3935: 
                   3936: @noindent
                   3937: Numbers are always treated in a fixed way:
                   3938: 
                   3939: @itemize @bullet
1.28      crook    3940: @item
1.44      crook    3941: When the number is @dfn{interpreted}, its behaviour is to push the
                   3942: number onto the stack.
1.28      crook    3943: @item
1.30      anton    3944: When the number is @dfn{compiled}, a piece of code is appended to the
                   3945: current definition that pushes the number when it runs. (In other words,
                   3946: the compilation semantics of a number are to postpone its interpretation
                   3947: semantics until the run-time of the definition that it is being compiled
                   3948: into.)
1.29      crook    3949: @end itemize
                   3950: 
1.44      crook    3951: Words don't behave in such a regular way, but most have @i{default
                   3952: semantics} which means that they behave like this:
1.29      crook    3953: 
                   3954: @itemize @bullet
1.28      crook    3955: @item
1.30      anton    3956: The @dfn{interpretation semantics} of the word are to do something useful.
                   3957: @item
1.29      crook    3958: The @dfn{compilation semantics} of the word are to append its
1.30      anton    3959: @dfn{interpretation semantics} to the current definition (so that its
                   3960: run-time behaviour is to do something useful).
1.28      crook    3961: @end itemize
                   3962: 
1.30      anton    3963: @cindex immediate words
1.44      crook    3964: The actual behaviour of any particular word can be controlled by using
                   3965: the words @code{immediate} and @code{compile-only} when the word is
                   3966: defined. These words set flags in the name dictionary entry of the most
                   3967: recently defined word, and these flags are retrieved by the text
                   3968: interpreter when it finds the word in the name dictionary.
                   3969: 
                   3970: A word that is marked as @dfn{immediate} has compilation semantics that
                   3971: are identical to its interpretation semantics. In other words, it
                   3972: behaves like this:
1.29      crook    3973: 
                   3974: @itemize @bullet
                   3975: @item
1.30      anton    3976: The @dfn{interpretation semantics} of the word are to do something useful.
1.29      crook    3977: @item
1.30      anton    3978: The @dfn{compilation semantics} of the word are to do something useful
                   3979: (and actually the same thing); i.e., it is executed during compilation.
1.29      crook    3980: @end itemize
1.28      crook    3981: 
1.44      crook    3982: Marking a word as @dfn{compile-only} prohibits the text interpreter from
                   3983: performing the interpretation semantics of the word directly; an attempt
                   3984: to do so will generate an error. It is never necessary to use
                   3985: @code{compile-only} (and it is not even part of ANS Forth, though it is
                   3986: provided by many implementations) but it is good etiquette to apply it
                   3987: to a word that will not behave correctly (and might have unexpected
                   3988: side-effects) in interpret state. For example, it is only legal to use
                   3989: the conditional word @code{IF} within a definition. If you forget this
                   3990: and try to use it elsewhere, the fact that (in Gforth) it is marked as
                   3991: @code{compile-only} allows the text interpreter to generate a helpful
                   3992: error message rather than subjecting you to the consequences of your
                   3993: folly.
                   3994: 
1.29      crook    3995: This example shows the difference between an immediate and a
                   3996: non-immediate word:
1.28      crook    3997: 
1.29      crook    3998: @example
                   3999: : show-state state @@ . ;
                   4000: : show-state-now show-state ; immediate
                   4001: : word1 show-state ;
                   4002: : word2 show-state-now ;
1.28      crook    4003: @end example
1.23      crook    4004: 
1.29      crook    4005: The word @code{immediate} after the definition of @code{show-state-now}
                   4006: makes that word an immediate word. These definitions introduce a new
                   4007: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
                   4008: variable, and leaves it on the stack. Therefore, the behaviour of
                   4009: @code{show-state} is to print a number that represents the current value
                   4010: of @code{state}.
1.28      crook    4011: 
1.29      crook    4012: When you execute @code{word1}, it prints the number 0, indicating that
                   4013: the system is interpreting. When the text interpreter compiled the
                   4014: definition of @code{word1}, it encountered @code{show-state} whose
1.30      anton    4015: compilation semantics are to append its interpretation semantics to the
1.29      crook    4016: current definition. When you execute @code{word1}, it performs the
1.30      anton    4017: interpretation semantics of @code{show-state}.  At the time that @code{word1}
1.29      crook    4018: (and therefore @code{show-state}) are executed, the system is
                   4019: interpreting.
1.28      crook    4020: 
1.30      anton    4021: When you pressed @key{RET} after entering the definition of @code{word2},
1.29      crook    4022: you should have seen the number -1 printed, followed by ``@code{
                   4023: ok}''. When the text interpreter compiled the definition of
                   4024: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30      anton    4025: whose compilation semantics are therefore to perform its interpretation
1.29      crook    4026: semantics. It is executed straight away (even before the text
                   4027: interpreter has moved on to process another group of characters; the
                   4028: @code{;} in this example). The effect of executing it are to display the
                   4029: value of @code{state} @i{at the time that the definition of}
                   4030: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
                   4031: system is compiling at this time. If you execute @code{word2} it does
                   4032: nothing at all.
1.28      crook    4033: 
1.29      crook    4034: @cindex @code{."}, how it works
                   4035: Before leaving the subject of immediate words, consider the behaviour of
                   4036: @code{."} in the definition of @code{greet}, in the previous
                   4037: section. This word is both a parsing word and an immediate word. Notice
                   4038: that there is a space between @code{."} and the start of the text
                   4039: @code{Hello and welcome}, but that there is no space between the last
                   4040: letter of @code{welcome} and the @code{"} character. The reason for this
                   4041: is that @code{."} is a Forth word; it must have a space after it so that
                   4042: the text interpreter can identify it. The @code{"} is not a Forth word;
                   4043: it is a @dfn{delimiter}. The examples earlier show that, when the string
                   4044: is displayed, there is neither a space before the @code{H} nor after the
                   4045: @code{e}. Since @code{."} is an immediate word, it executes at the time
                   4046: that @code{greet} is defined. When it executes, its behaviour is to
                   4047: search forward in the input line looking for the delimiter. When it
                   4048: finds the delimiter, it updates @code{>IN} to point past the
                   4049: delimiter. It also compiles some magic code into the definition of
                   4050: @code{greet}; the xt of a run-time routine that prints a text string. It
                   4051: compiles the string @code{Hello and welcome} into memory so that it is
                   4052: available to be printed later. When the text interpreter gains control,
                   4053: the next word it finds in the input stream is @code{;} and so it
                   4054: terminates the definition of @code{greet}.
1.28      crook    4055: 
                   4056: 
                   4057: @comment ----------------------------------------------
1.29      crook    4058: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
                   4059: @section Forth is written in Forth
                   4060: @cindex structure of Forth programs
                   4061: 
                   4062: When you start up a Forth compiler, a large number of definitions
                   4063: already exist. In Forth, you develop a new application using bottom-up
                   4064: programming techniques to create new definitions that are defined in
                   4065: terms of existing definitions. As you create each definition you can
                   4066: test and debug it interactively.
                   4067: 
                   4068: If you have tried out the examples in this section, you will probably
                   4069: have typed them in by hand; when you leave Gforth, your definitions will
                   4070: be lost. You can avoid this by using a text editor to enter Forth source
                   4071: code into a file, and then loading code from the file using
1.49      anton    4072: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29      crook    4073: processed by the text interpreter, just as though you had typed it in by
                   4074: hand@footnote{Actually, there are some subtle differences -- see
                   4075: @ref{The Text Interpreter}.}.
                   4076: 
                   4077: Gforth also supports the traditional Forth alternative to using text
1.49      anton    4078: files for program entry (@pxref{Blocks}).
1.28      crook    4079: 
1.29      crook    4080: In common with many, if not most, Forth compilers, most of Gforth is
                   4081: actually written in Forth. All of the @file{.fs} files in the
                   4082: installation directory@footnote{For example,
1.30      anton    4083: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29      crook    4084: study to see examples of Forth programming.
1.28      crook    4085: 
1.29      crook    4086: Gforth maintains a history file that records every line that you type to
                   4087: the text interpreter. This file is preserved between sessions, and is
                   4088: used to provide a command-line recall facility. If you enter long
                   4089: definitions by hand, you can use a text editor to paste them out of the
                   4090: history file into a Forth source file for reuse at a later time
1.49      anton    4091: (for more information @pxref{Command-line editing}).
1.28      crook    4092: 
                   4093: 
                   4094: @comment ----------------------------------------------
1.29      crook    4095: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
                   4096: @section Review - elements of a Forth system
                   4097: @cindex elements of a Forth system
1.28      crook    4098: 
1.29      crook    4099: To summarise this chapter:
1.28      crook    4100: 
                   4101: @itemize @bullet
                   4102: @item
1.29      crook    4103: Forth programs use @dfn{factoring} to break a problem down into small
                   4104: fragments called @dfn{words} or @dfn{definitions}.
                   4105: @item
                   4106: Forth program development is an interactive process.
                   4107: @item
                   4108: The main command loop that accepts input, and controls both
                   4109: interpretation and compilation, is called the @dfn{text interpreter}
                   4110: (also known as the @dfn{outer interpreter}).
                   4111: @item
                   4112: Forth has a very simple syntax, consisting of words and numbers
                   4113: separated by spaces or carriage-return characters. Any additional syntax
                   4114: is imposed by @dfn{parsing words}.
                   4115: @item
                   4116: Forth uses a stack to pass parameters between words. As a result, it
                   4117: uses postfix notation.
                   4118: @item
                   4119: To use a word that has previously been defined, the text interpreter
                   4120: searches for the word in the @dfn{name dictionary}.
                   4121: @item
1.30      anton    4122: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28      crook    4123: @item
1.29      crook    4124: The text interpreter uses the value of @code{state} to select between
                   4125: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
                   4126: semantics} of a word that it encounters.
1.28      crook    4127: @item
1.30      anton    4128: The relationship between the @dfn{interpretation semantics} and
                   4129: @dfn{compilation semantics} for a word
1.29      crook    4130: depend upon the way in which the word was defined (for example, whether
                   4131: it is an @dfn{immediate} word).
1.28      crook    4132: @item
1.29      crook    4133: Forth definitions can be implemented in Forth (called @dfn{high-level
                   4134: definitions}) or in some other way (usually a lower-level language and
                   4135: as a result often called @dfn{low-level definitions}, @dfn{code
                   4136: definitions} or @dfn{primitives}).
1.28      crook    4137: @item
1.29      crook    4138: Many Forth systems are implemented mainly in Forth.
1.28      crook    4139: @end itemize
                   4140: 
                   4141: 
1.29      crook    4142: @comment ----------------------------------------------
1.48      anton    4143: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29      crook    4144: @section Where To Go Next
                   4145: @cindex where to go next
1.28      crook    4146: 
1.29      crook    4147: Amazing as it may seem, if you have read (and understood) this far, you
                   4148: know almost all the fundamentals about the inner workings of a Forth
                   4149: system. You certainly know enough to be able to read and understand the
                   4150: rest of this manual and the ANS Forth document, to learn more about the
                   4151: facilities that Forth in general and Gforth in particular provide. Even
                   4152: scarier, you know almost enough to implement your own Forth system.
1.30      anton    4153: However, that's not a good idea just yet... better to try writing some
1.29      crook    4154: programs in Gforth.
1.28      crook    4155: 
1.29      crook    4156: Forth has such a rich vocabulary that it can be hard to know where to
                   4157: start in learning it. This section suggests a few sets of words that are
                   4158: enough to write small but useful programs. Use the word index in this
                   4159: document to learn more about each word, then try it out and try to write
                   4160: small definitions using it. Start by experimenting with these words:
1.28      crook    4161: 
                   4162: @itemize @bullet
                   4163: @item
1.29      crook    4164: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
                   4165: @item
                   4166: Comparison: @code{MIN MAX =}
                   4167: @item
                   4168: Logic: @code{AND OR XOR NOT}
                   4169: @item
                   4170: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28      crook    4171: @item
1.29      crook    4172: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28      crook    4173: @item
1.29      crook    4174: Input/Output: @code{. ." EMIT CR KEY}
1.28      crook    4175: @item
1.29      crook    4176: Defining words: @code{: ; CREATE}
1.28      crook    4177: @item
1.29      crook    4178: Memory allocation words: @code{ALLOT ,}
1.28      crook    4179: @item
1.29      crook    4180: Tools: @code{SEE WORDS .S MARKER}
                   4181: @end itemize
                   4182: 
                   4183: When you have mastered those, go on to:
                   4184: 
                   4185: @itemize @bullet
1.28      crook    4186: @item
1.29      crook    4187: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28      crook    4188: @item
1.29      crook    4189: Memory access: @code{@@ !}
1.28      crook    4190: @end itemize
1.23      crook    4191: 
1.29      crook    4192: When you have mastered these, there's nothing for it but to read through
                   4193: the whole of this manual and find out what you've missed.
                   4194: 
                   4195: @comment ----------------------------------------------
1.48      anton    4196: @node Exercises,  , Where to go next, Introduction
1.29      crook    4197: @section Exercises
                   4198: @cindex exercises
                   4199: 
                   4200: TODO: provide a set of programming excercises linked into the stuff done
                   4201: already and into other sections of the manual. Provide solutions to all
                   4202: the exercises in a .fs file in the distribution.
                   4203: 
                   4204: @c Get some inspiration from Starting Forth and Kelly&Spies.
                   4205: 
                   4206: @c excercises:
                   4207: @c 1. take inches and convert to feet and inches.
                   4208: @c 2. take temperature and convert from fahrenheight to celcius;
                   4209: @c    may need to care about symmetric vs floored??
                   4210: @c 3. take input line and do character substitution
                   4211: @c    to encipher or decipher
                   4212: @c 4. as above but work on a file for in and out
                   4213: @c 5. take input line and convert to pig-latin 
                   4214: @c
                   4215: @c thing of sets of things to exercise then come up with
                   4216: @c problems that need those things.
                   4217: 
                   4218: 
1.26      crook    4219: @c ******************************************************************
1.29      crook    4220: @node Words, Error messages, Introduction, Top
1.1       anton    4221: @chapter Forth Words
1.26      crook    4222: @cindex words
1.1       anton    4223: 
                   4224: @menu
                   4225: * Notation::                    
1.21      crook    4226: * Comments::
                   4227: * Boolean Flags::
1.1       anton    4228: * Arithmetic::                  
                   4229: * Stack Manipulation::          
1.5       anton    4230: * Memory::                      
1.1       anton    4231: * Control Structures::          
                   4232: * Defining Words::              
1.47      crook    4233: * Interpretation and Compilation Semantics::
                   4234: * Tokens for Words::            
1.21      crook    4235: * The Text Interpreter::
                   4236: * Word Lists::                   
                   4237: * Environmental Queries::
1.12      anton    4238: * Files::                       
                   4239: * Blocks::                      
                   4240: * Other I/O::                   
                   4241: * Programming Tools::           
                   4242: * Assembler and Code Words::    
                   4243: * Threading Words::             
1.26      crook    4244: * Locals::                      
                   4245: * Structures::                  
                   4246: * Object-oriented Forth::       
1.21      crook    4247: * Passing Commands to the OS::
1.47      crook    4248: * Keeping track of Time::
1.21      crook    4249: * Miscellaneous Words::
1.1       anton    4250: @end menu
                   4251: 
1.21      crook    4252: @node Notation, Comments, Words, Words
1.1       anton    4253: @section Notation
                   4254: @cindex notation of glossary entries
                   4255: @cindex format of glossary entries
                   4256: @cindex glossary notation format
                   4257: @cindex word glossary entry format
                   4258: 
                   4259: The Forth words are described in this section in the glossary notation
                   4260: that has become a de-facto standard for Forth texts, i.e.,
                   4261: 
                   4262: @format
1.29      crook    4263: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
1.1       anton    4264: @end format
1.29      crook    4265: @i{Description}
1.1       anton    4266: 
                   4267: @table @var
                   4268: @item word
1.28      crook    4269: The name of the word.
1.1       anton    4270: 
                   4271: @item Stack effect
                   4272: @cindex stack effect
1.29      crook    4273: The stack effect is written in the notation @code{@i{before} --
                   4274: @i{after}}, where @i{before} and @i{after} describe the top of
1.1       anton    4275: stack entries before and after the execution of the word. The rest of
                   4276: the stack is not touched by the word. The top of stack is rightmost,
                   4277: i.e., a stack sequence is written as it is typed in. Note that Gforth
                   4278: uses a separate floating point stack, but a unified stack
1.29      crook    4279: notation. Also, return stack effects are not shown in @i{stack
                   4280: effect}, but in @i{Description}. The name of a stack item describes
1.1       anton    4281: the type and/or the function of the item. See below for a discussion of
                   4282: the types.
                   4283: 
                   4284: All words have two stack effects: A compile-time stack effect and a
                   4285: run-time stack effect. The compile-time stack-effect of most words is
1.29      crook    4286: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1       anton    4287: this standard behaviour, or the word does other unusual things at
                   4288: compile time, both stack effects are shown; otherwise only the run-time
                   4289: stack effect is shown.
                   4290: 
                   4291: @cindex pronounciation of words
                   4292: @item pronunciation
                   4293: How the word is pronounced.
                   4294: 
                   4295: @cindex wordset
                   4296: @item wordset
1.21      crook    4297: The ANS Forth standard is divided into several word sets. A standard
                   4298: system need not support all of them. Therefore, in theory, the fewer
                   4299: word sets your program uses the more portable it will be. However, we
                   4300: suspect that most ANS Forth systems on personal machines will feature
1.26      crook    4301: all word sets. Words that are not defined in ANS Forth have
1.21      crook    4302: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1       anton    4303: describes words that will work in future releases of Gforth;
                   4304: @code{gforth-internal} words are more volatile. Environmental query
                   4305: strings are also displayed like words; you can recognize them by the
1.21      crook    4306: @code{environment} in the word set field.
1.1       anton    4307: 
                   4308: @item Description
                   4309: A description of the behaviour of the word.
                   4310: @end table
                   4311: 
                   4312: @cindex types of stack items
                   4313: @cindex stack item types
                   4314: The type of a stack item is specified by the character(s) the name
                   4315: starts with:
                   4316: 
                   4317: @table @code
                   4318: @item f
                   4319: @cindex @code{f}, stack item type
                   4320: Boolean flags, i.e. @code{false} or @code{true}.
                   4321: @item c
                   4322: @cindex @code{c}, stack item type
                   4323: Char
                   4324: @item w
                   4325: @cindex @code{w}, stack item type
                   4326: Cell, can contain an integer or an address
                   4327: @item n
                   4328: @cindex @code{n}, stack item type
                   4329: signed integer
                   4330: @item u
                   4331: @cindex @code{u}, stack item type
                   4332: unsigned integer
                   4333: @item d
                   4334: @cindex @code{d}, stack item type
                   4335: double sized signed integer
                   4336: @item ud
                   4337: @cindex @code{ud}, stack item type
                   4338: double sized unsigned integer
                   4339: @item r
                   4340: @cindex @code{r}, stack item type
                   4341: Float (on the FP stack)
1.21      crook    4342: @item a-
1.1       anton    4343: @cindex @code{a_}, stack item type
                   4344: Cell-aligned address
1.21      crook    4345: @item c-
1.1       anton    4346: @cindex @code{c_}, stack item type
                   4347: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21      crook    4348: @item f-
1.1       anton    4349: @cindex @code{f_}, stack item type
                   4350: Float-aligned address
1.21      crook    4351: @item df-
1.1       anton    4352: @cindex @code{df_}, stack item type
                   4353: Address aligned for IEEE double precision float
1.21      crook    4354: @item sf-
1.1       anton    4355: @cindex @code{sf_}, stack item type
                   4356: Address aligned for IEEE single precision float
                   4357: @item xt
                   4358: @cindex @code{xt}, stack item type
                   4359: Execution token, same size as Cell
                   4360: @item wid
                   4361: @cindex @code{wid}, stack item type
1.21      crook    4362: Word list ID, same size as Cell
1.1       anton    4363: @item f83name
                   4364: @cindex @code{f83name}, stack item type
                   4365: Pointer to a name structure
                   4366: @item "
                   4367: @cindex @code{"}, stack item type
1.12      anton    4368: string in the input stream (not on the stack). The terminating character
                   4369: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1       anton    4370: quotes.
                   4371: @end table
                   4372: 
1.21      crook    4373: @node Comments, Boolean Flags, Notation, Words
                   4374: @section Comments
1.26      crook    4375: @cindex comments
1.21      crook    4376: 
1.29      crook    4377: Forth supports two styles of comment; the traditional @i{in-line} comment,
                   4378: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21      crook    4379: 
1.44      crook    4380: 
1.23      crook    4381: doc-(
1.21      crook    4382: doc-\
1.23      crook    4383: doc-\G
1.21      crook    4384: 
1.44      crook    4385: 
1.21      crook    4386: @node Boolean Flags, Arithmetic, Comments, Words
                   4387: @section Boolean Flags
1.26      crook    4388: @cindex Boolean flags
1.21      crook    4389: 
                   4390: A Boolean flag is cell-sized. A cell with all bits clear represents the
                   4391: flag @code{false} and a flag with all bits set represents the flag
1.26      crook    4392: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29      crook    4393: a cell that has @i{any} bit set as @code{true}.
1.21      crook    4394: 
1.44      crook    4395: 
1.21      crook    4396: doc-true
                   4397: doc-false
1.29      crook    4398: doc-on
                   4399: doc-off
1.21      crook    4400: 
1.44      crook    4401: 
1.21      crook    4402: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1       anton    4403: @section Arithmetic
                   4404: @cindex arithmetic words
                   4405: 
                   4406: @cindex division with potentially negative operands
                   4407: Forth arithmetic is not checked, i.e., you will not hear about integer
                   4408: overflow on addition or multiplication, you may hear about division by
                   4409: zero if you are lucky. The operator is written after the operands, but
                   4410: the operands are still in the original order. I.e., the infix @code{2-1}
                   4411: corresponds to @code{2 1 -}. Forth offers a variety of division
                   4412: operators. If you perform division with potentially negative operands,
                   4413: you do not want to use @code{/} or @code{/mod} with its undefined
                   4414: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
                   4415: former, @pxref{Mixed precision}).
1.26      crook    4416: @comment TODO discuss the different division forms and the std approach
1.1       anton    4417: 
                   4418: @menu
                   4419: * Single precision::            
                   4420: * Bitwise operations::          
1.21      crook    4421: * Double precision::            Double-cell integer arithmetic
                   4422: * Numeric comparison::
1.29      crook    4423: * Mixed precision::             Operations with single and double-cell integers
1.1       anton    4424: * Floating Point::              
                   4425: @end menu
                   4426: 
                   4427: @node Single precision, Bitwise operations, Arithmetic, Arithmetic
                   4428: @subsection Single precision
                   4429: @cindex single precision arithmetic words
                   4430: 
1.21      crook    4431: By default, numbers in Forth are single-precision integers that are 1
1.26      crook    4432: cell in size. They can be signed or unsigned, depending upon how you
1.49      anton    4433: treat them. For the rules used by the text interpreter for recognising
                   4434: single-precision integers see @ref{Number Conversion}.
1.21      crook    4435: 
1.44      crook    4436: 
1.1       anton    4437: doc-+
1.21      crook    4438: doc-1+
1.1       anton    4439: doc--
1.21      crook    4440: doc-1-
1.1       anton    4441: doc-*
                   4442: doc-/
                   4443: doc-mod
                   4444: doc-/mod
                   4445: doc-negate
                   4446: doc-abs
                   4447: doc-min
                   4448: doc-max
1.21      crook    4449: doc-d>s
1.27      crook    4450: doc-floored
1.1       anton    4451: 
1.44      crook    4452: 
1.21      crook    4453: @node Bitwise operations, Double precision, Single precision, Arithmetic
1.1       anton    4454: @subsection Bitwise operations
                   4455: @cindex bitwise operation words
                   4456: 
1.44      crook    4457: 
1.1       anton    4458: doc-and
                   4459: doc-or
                   4460: doc-xor
                   4461: doc-invert
1.21      crook    4462: doc-lshift
                   4463: doc-rshift
1.1       anton    4464: doc-2*
1.21      crook    4465: doc-d2*
1.1       anton    4466: doc-2/
1.21      crook    4467: doc-d2/
                   4468: 
1.44      crook    4469: 
1.21      crook    4470: @node Double precision, Numeric comparison, Bitwise operations, Arithmetic
                   4471: @subsection Double precision
                   4472: @cindex double precision arithmetic words
                   4473: 
1.49      anton    4474: For the rules used by the text interpreter for
                   4475: recognising double-precision integers, see @ref{Number Conversion}.
1.21      crook    4476: 
                   4477: A double precision number is represented by a cell pair, with the most
1.31      anton    4478: significant cell at the TOS. It is trivial to convert an unsigned
1.26      crook    4479: single to an (unsigned) double; simply push a @code{0} onto the
                   4480: TOS. Since numbers are represented by Gforth using 2's complement
                   4481: arithmetic, converting a signed single to a (signed) double requires
1.31      anton    4482: sign-extension across the most significant cell. This can be achieved
1.26      crook    4483: using @code{s>d}. The moral of the story is that you cannot convert a
                   4484: number without knowing whether it represents an unsigned or a
                   4485: signed number.
1.21      crook    4486: 
1.44      crook    4487: 
1.21      crook    4488: doc-s>d
                   4489: doc-d+
                   4490: doc-d-
                   4491: doc-dnegate
                   4492: doc-dabs
                   4493: doc-dmin
                   4494: doc-dmax
                   4495: 
1.44      crook    4496: 
1.21      crook    4497: @node Numeric comparison, Mixed precision, Double precision, Arithmetic
                   4498: @subsection Numeric comparison
                   4499: @cindex numeric comparison words
                   4500: 
1.44      crook    4501: 
1.28      crook    4502: doc-<
                   4503: doc-<=
                   4504: doc-<>
                   4505: doc-=
                   4506: doc->
                   4507: doc->=
                   4508: 
1.21      crook    4509: doc-0<
1.23      crook    4510: doc-0<=
1.21      crook    4511: doc-0<>
                   4512: doc-0=
1.23      crook    4513: doc-0>
                   4514: doc-0>=
1.28      crook    4515: 
                   4516: doc-u<
                   4517: doc-u<=
1.44      crook    4518: @c u<> and u= exist but are the same as <> and =
1.31      anton    4519: @c doc-u<>
                   4520: @c doc-u=
1.28      crook    4521: doc-u>
                   4522: doc-u>=
                   4523: 
                   4524: doc-within
                   4525: 
                   4526: doc-d<
                   4527: doc-d<=
                   4528: doc-d<>
                   4529: doc-d=
                   4530: doc-d>
                   4531: doc-d>=
1.23      crook    4532: 
1.21      crook    4533: doc-d0<
1.23      crook    4534: doc-d0<=
                   4535: doc-d0<>
1.21      crook    4536: doc-d0=
1.23      crook    4537: doc-d0>
                   4538: doc-d0>=
                   4539: 
1.21      crook    4540: doc-du<
1.28      crook    4541: doc-du<=
1.44      crook    4542: @c du<> and du= exist but are the same as d<> and d=
1.31      anton    4543: @c doc-du<>
                   4544: @c doc-du=
1.28      crook    4545: doc-du>
                   4546: doc-du>=
1.1       anton    4547: 
1.44      crook    4548: 
1.21      crook    4549: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1       anton    4550: @subsection Mixed precision
                   4551: @cindex mixed precision arithmetic words
                   4552: 
1.44      crook    4553: 
1.1       anton    4554: doc-m+
                   4555: doc-*/
                   4556: doc-*/mod
                   4557: doc-m*
                   4558: doc-um*
                   4559: doc-m*/
                   4560: doc-um/mod
                   4561: doc-fm/mod
                   4562: doc-sm/rem
                   4563: 
1.44      crook    4564: 
1.21      crook    4565: @node Floating Point,  , Mixed precision, Arithmetic
1.1       anton    4566: @subsection Floating Point
                   4567: @cindex floating point arithmetic words
                   4568: 
1.49      anton    4569: For the rules used by the text interpreter for
                   4570: recognising floating-point numbers see @ref{Number Conversion}.
1.1       anton    4571: 
1.32      anton    4572: Gforth has a separate floating point
1.26      crook    4573: stack, but the documentation uses the unified notation.
1.1       anton    4574: 
                   4575: @cindex floating-point arithmetic, pitfalls
                   4576: Floating point numbers have a number of unpleasant surprises for the
                   4577: unwary (e.g., floating point addition is not associative) and even a few
                   4578: for the wary. You should not use them unless you know what you are doing
                   4579: or you don't care that the results you get are totally bogus. If you
                   4580: want to learn about the problems of floating point numbers (and how to
                   4581: avoid them), you might start with @cite{David Goldberg, What Every
                   4582: Computer Scientist Should Know About Floating-Point Arithmetic, ACM
1.17      anton    4583: Computing Surveys 23(1):5@minus{}48, March 1991}
1.47      crook    4584: (@uref{http://www.validgh.com/goldberg/paper.ps}).
1.1       anton    4585: 
1.44      crook    4586: 
1.21      crook    4587: doc-d>f
                   4588: doc-f>d
1.1       anton    4589: doc-f+
                   4590: doc-f-
                   4591: doc-f*
                   4592: doc-f/
                   4593: doc-fnegate
                   4594: doc-fabs
                   4595: doc-fmax
                   4596: doc-fmin
                   4597: doc-floor
                   4598: doc-fround
                   4599: doc-f**
                   4600: doc-fsqrt
                   4601: doc-fexp
                   4602: doc-fexpm1
                   4603: doc-fln
                   4604: doc-flnp1
                   4605: doc-flog
                   4606: doc-falog
1.32      anton    4607: doc-f2*
                   4608: doc-f2/
                   4609: doc-1/f
                   4610: doc-precision
                   4611: doc-set-precision
                   4612: 
                   4613: @cindex angles in trigonometric operations
                   4614: @cindex trigonometric operations
                   4615: Angles in floating point operations are given in radians (a full circle
                   4616: has 2 pi radians).
                   4617: 
1.1       anton    4618: doc-fsin
                   4619: doc-fcos
                   4620: doc-fsincos
                   4621: doc-ftan
                   4622: doc-fasin
                   4623: doc-facos
                   4624: doc-fatan
                   4625: doc-fatan2
                   4626: doc-fsinh
                   4627: doc-fcosh
                   4628: doc-ftanh
                   4629: doc-fasinh
                   4630: doc-facosh
                   4631: doc-fatanh
1.21      crook    4632: doc-pi
1.28      crook    4633: 
1.32      anton    4634: @cindex equality of floats
                   4635: @cindex floating-point comparisons
1.31      anton    4636: One particular problem with floating-point arithmetic is that comparison
                   4637: for equality often fails when you would expect it to succeed.  For this
                   4638: reason approximate equality is often preferred (but you still have to
                   4639: know what you are doing).  The comparison words are:
                   4640: 
                   4641: doc-f~rel
                   4642: doc-f~abs
                   4643: doc-f=
                   4644: doc-f~
                   4645: doc-f<>
                   4646: 
                   4647: doc-f<
                   4648: doc-f<=
                   4649: doc-f>
                   4650: doc-f>=
                   4651: 
1.21      crook    4652: doc-f0<
1.28      crook    4653: doc-f0<=
                   4654: doc-f0<>
1.21      crook    4655: doc-f0=
1.28      crook    4656: doc-f0>
                   4657: doc-f0>=
                   4658: 
1.1       anton    4659: 
                   4660: @node Stack Manipulation, Memory, Arithmetic, Words
                   4661: @section Stack Manipulation
                   4662: @cindex stack manipulation words
                   4663: 
                   4664: @cindex floating-point stack in the standard
1.21      crook    4665: Gforth maintains a number of separate stacks:
                   4666: 
1.29      crook    4667: @cindex data stack
                   4668: @cindex parameter stack
1.21      crook    4669: @itemize @bullet
                   4670: @item
1.29      crook    4671: A data stack (also known as the @dfn{parameter stack}) -- for
                   4672: characters, cells, addresses, and double cells.
1.21      crook    4673: 
1.29      crook    4674: @cindex floating-point stack
1.21      crook    4675: @item
1.44      crook    4676: A floating point stack -- for holding floating point (FP) numbers.
1.21      crook    4677: 
1.29      crook    4678: @cindex return stack
1.21      crook    4679: @item
1.44      crook    4680: A return stack -- for holding the return addresses of colon
1.32      anton    4681: definitions and other (non-FP) data.
1.21      crook    4682: 
1.29      crook    4683: @cindex locals stack
1.21      crook    4684: @item
1.44      crook    4685: A locals stack -- for holding local variables.
1.21      crook    4686: @end itemize
                   4687: 
1.1       anton    4688: @menu
                   4689: * Data stack::                  
                   4690: * Floating point stack::        
                   4691: * Return stack::                
                   4692: * Locals stack::                
                   4693: * Stack pointer manipulation::  
                   4694: @end menu
                   4695: 
                   4696: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
                   4697: @subsection Data stack
                   4698: @cindex data stack manipulation words
                   4699: @cindex stack manipulations words, data stack
                   4700: 
1.44      crook    4701: 
1.1       anton    4702: doc-drop
                   4703: doc-nip
                   4704: doc-dup
                   4705: doc-over
                   4706: doc-tuck
                   4707: doc-swap
1.21      crook    4708: doc-pick
1.1       anton    4709: doc-rot
                   4710: doc--rot
                   4711: doc-?dup
                   4712: doc-roll
                   4713: doc-2drop
                   4714: doc-2nip
                   4715: doc-2dup
                   4716: doc-2over
                   4717: doc-2tuck
                   4718: doc-2swap
                   4719: doc-2rot
                   4720: 
1.44      crook    4721: 
1.1       anton    4722: @node Floating point stack, Return stack, Data stack, Stack Manipulation
                   4723: @subsection Floating point stack
                   4724: @cindex floating-point stack manipulation words
                   4725: @cindex stack manipulation words, floating-point stack
                   4726: 
1.32      anton    4727: Whilst every sane Forth has a separate floating-point stack, it is not
                   4728: strictly required; an ANS Forth system could theoretically keep
                   4729: floating-point numbers on the data stack. As an additional difficulty,
                   4730: you don't know how many cells a floating-point number takes. It is
                   4731: reportedly possible to write words in a way that they work also for a
                   4732: unified stack model, but we do not recommend trying it. Instead, just
                   4733: say that your program has an environmental dependency on a separate
                   4734: floating-point stack.
                   4735: 
                   4736: doc-floating-stack
                   4737: 
1.1       anton    4738: doc-fdrop
                   4739: doc-fnip
                   4740: doc-fdup
                   4741: doc-fover
                   4742: doc-ftuck
                   4743: doc-fswap
1.21      crook    4744: doc-fpick
1.1       anton    4745: doc-frot
                   4746: 
1.44      crook    4747: 
1.1       anton    4748: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
                   4749: @subsection Return stack
                   4750: @cindex return stack manipulation words
                   4751: @cindex stack manipulation words, return stack
                   4752: 
1.32      anton    4753: @cindex return stack and locals
                   4754: @cindex locals and return stack
                   4755: A Forth system is allowed to keep local variables on the
                   4756: return stack. This is reasonable, as local variables usually eliminate
                   4757: the need to use the return stack explicitly. So, if you want to produce
                   4758: a standard compliant program and you are using local variables in a
                   4759: word, forget about return stack manipulations in that word (refer to the
                   4760: standard document for the exact rules).
                   4761: 
1.1       anton    4762: doc->r
                   4763: doc-r>
                   4764: doc-r@
                   4765: doc-rdrop
                   4766: doc-2>r
                   4767: doc-2r>
                   4768: doc-2r@
                   4769: doc-2rdrop
                   4770: 
1.44      crook    4771: 
1.1       anton    4772: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
                   4773: @subsection Locals stack
                   4774: 
1.47      crook    4775: Gforth uses an extra locals stack. It is described, along with the
                   4776: reasons for its existence, in @ref{Implementation,Implementation of locals}.
1.21      crook    4777: 
1.1       anton    4778: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
                   4779: @subsection Stack pointer manipulation
                   4780: @cindex stack pointer manipulation words
                   4781: 
1.44      crook    4782: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21      crook    4783: doc-sp0
1.1       anton    4784: doc-sp@
                   4785: doc-sp!
1.21      crook    4786: doc-fp0
1.1       anton    4787: doc-fp@
                   4788: doc-fp!
1.21      crook    4789: doc-rp0
1.1       anton    4790: doc-rp@
                   4791: doc-rp!
1.21      crook    4792: doc-lp0
1.1       anton    4793: doc-lp@
                   4794: doc-lp!
                   4795: 
1.44      crook    4796: 
1.1       anton    4797: @node Memory, Control Structures, Stack Manipulation, Words
                   4798: @section Memory
1.26      crook    4799: @cindex memory words
1.1       anton    4800: 
1.32      anton    4801: @menu
                   4802: * Memory model::                
                   4803: * Dictionary allocation::       
                   4804: * Heap Allocation::             
                   4805: * Memory Access::               
                   4806: * Address arithmetic::          
                   4807: * Memory Blocks::               
                   4808: @end menu
                   4809: 
                   4810: @node Memory model, Dictionary allocation, Memory, Memory
                   4811: @subsection ANS Forth and Gforth memory models
                   4812: 
                   4813: @c The ANS Forth description is a mess (e.g., is the heap part of
                   4814: @c the dictionary?), so let's not stick to closely with it.
                   4815: 
                   4816: ANS Forth considers a Forth system as consisting of several memories, of
                   4817: which only @dfn{data space} is managed and accessible with the memory
                   4818: words.  Memory not necessarily in data space includes the stacks, the
                   4819: code (called code space) and the headers (called name space). In Gforth
                   4820: everything is in data space, but the code for the primitives is usually
                   4821: read-only.
                   4822: 
                   4823: Data space is divided into a number of areas: The (data space portion of
                   4824: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
                   4825: refer to the search data structure embodied in word lists and headers,
                   4826: because it is used for looking up names, just as you would in a
                   4827: conventional dictionary.}, the heap, and a number of system-allocated
                   4828: buffers.
                   4829: 
                   4830: In ANS Forth data space is also divided into contiguous regions.  You
                   4831: can only use address arithmetic within a contiguous region, not between
                   4832: them.  Usually each allocation gives you one contiguous region, but the
1.33      anton    4833: dictionary allocation words have additional rules (@pxref{Dictionary
1.32      anton    4834: allocation}).
                   4835: 
                   4836: Gforth provides one big address space, and address arithmetic can be
                   4837: performed between any addresses. However, in the dictionary headers or
                   4838: code are interleaved with data, so almost the only contiguous data space
                   4839: regions there are those described by ANS Forth as contiguous; but you
                   4840: can be sure that the dictionary is allocated towards increasing
                   4841: addresses even between contiguous regions.  The memory order of
                   4842: allocations in the heap is platform-dependent (and possibly different
                   4843: from one run to the next).
                   4844: 
                   4845: @subsubsection ANS Forth dictionary details
                   4846: 
                   4847: This section is just informative, you can skip it if you are in a hurry.
1.27      crook    4848: 
1.29      crook    4849: When you create a colon definition, the text interpreter compiles the
1.32      anton    4850: code for the definition into the code space and compiles the name
                   4851: of the definition into the header space, together with other
1.27      crook    4852: information about the definition (such as its execution token).
                   4853: 
1.44      crook    4854: When you create a variable, the execution of @code{Variable} will
1.32      anton    4855: compile some code, assign one cell in data space, and compile the name
                   4856: of the variable into the header space.
1.27      crook    4857: 
                   4858: @cindex memory regions - relationship between them
                   4859: ANS Forth does not specify the relationship between the three memory
                   4860: regions, and specifies that a Standard program must not access code or
                   4861: data space directly -- it may only access data space directly. In
                   4862: addition, the Standard defines what relationships you may and may not
                   4863: rely on when allocating regions in data space. These constraints are
                   4864: simply a reflection of the many diverse techniques that are used to
                   4865: implement Forth systems; understanding and following the requirements of
                   4866: the Standard allows you to write portable programs -- programs that run
                   4867: in the same way on any of these diverse systems. Another way of looking
                   4868: at this is to say that ANS Forth was designed to permit compliant Forth
                   4869: systems to be implemented in many diverse ways.
                   4870: 
                   4871: @cindex memory regions - how they are assigned
1.29      crook    4872: Here are some examples of ways in which name, code and data spaces
                   4873: might be assigned in different Forth implementations:
1.27      crook    4874: 
                   4875: @itemize @bullet
                   4876: @item
                   4877: For a Forth system that runs from RAM under a general-purpose operating
                   4878: system, it can be convenient to interleave name, code and data spaces in
                   4879: a single contiguous memory region. This organisation can be
                   4880: memory-efficient (for example, because the relationship between the name
1.32      anton    4881: dictionary entry and the associated code space entry can be
1.27      crook    4882: implicit, rather than requiring an explicit memory pointer to reference
1.32      anton    4883: from the header space and the code space). This is the
1.27      crook    4884: organisation used by Gforth, as this example@footnote{The addresses
                   4885: in the example have been truncated to fit it onto the page, and the
                   4886: addresses and data shown will not match the output from your system} shows:
                   4887: @example
                   4888: hex
                   4889: variable fred 123456 fred !
                   4890: variable jim abcd jim !
                   4891: : foo + / - ;
                   4892: ' fred 10 - 50 dump 
                   4893: ..80: 5C 46 0E 40  84 66 72 65 - 64 20 20 20  20 20 20 20  \F.@.fred       
1.50      anton    4894: ..90: D0 9B 04 08  00 00 00 00 - 56 34 12 00  80 46 0E 40  ........V4...F.@@
1.27      crook    4895: ..A0: 83 6A 69 6D  20 20 20 20 - D0 9B 04 08  00 00 00 00  .jim    ........
                   4896: ..B0: CD AB 00 00  9C 46 0E 40 - 83 66 6F 6F  20 20 20 20  .....F.@.foo    
                   4897: ..C0: 80 9B 04 08  00 00 00 00 - E4 2E 05 08  0C 2F 05 08  ............./..
                   4898: @end example
                   4899: 
                   4900: @item
                   4901: For a high-performance system running on a modern RISC processor with a
                   4902: modified Harvard architecture (one that has a unified main memory but
                   4903: separate instruction and data caches), it is desirable to separate
                   4904: processor instructions from processor data. This encourages a high cache
1.32      anton    4905: density and therefore a high cache hit rate. The Forth code space
1.27      crook    4906: is not necessarily made up entirely of processor instructions; its
                   4907: nature is dependent upon the Forth implementation. 
                   4908: 
                   4909: @item
                   4910: A Forth compiler that runs on a segmented 8086 processor could be
                   4911: designed to interleave the name, code and data spaces within a single
                   4912: 64Kbyte segment. A more common implementation choice is to use a
                   4913: separate 64Kbyte segment for each region, which provides more memory
                   4914: overall but provides an address map in which only the data space is
                   4915: accessible.
                   4916: 
                   4917: @item
                   4918: Microprocessors exist that run Forth (or many of the primitives required
                   4919: to implement the Forth virtual machine efficiently) directly. On these
                   4920: processors, the relationship between name, code and data spaces may be
1.32      anton    4921: imposed as a side-effect of the architecture of the processor.
1.27      crook    4922: 
                   4923: @item
                   4924: A Forth compiler that executes from ROM on an embedded system needs its
                   4925: data space separated from the name and code spaces so that the data
                   4926: space can be mapped to a RAM area.
                   4927: 
                   4928: @item 
                   4929: A Forth compiler that runs on an embedded system may have a requirement
                   4930: for a small memory footprint. On such a system it can be useful to
1.32      anton    4931: separate the header space from the data and code spaces; once the
                   4932: application has been compiled, the header space is no longer
1.27      crook    4933: required@footnote{more strictly speaking, most applications can be
1.32      anton    4934: designed so that this is the case}. The header space can be deleted
1.29      crook    4935: entirely, or could be stored in memory on a remote @i{host} system for
1.27      crook    4936: debug and development purposes. In the latter case, the compiler running
1.29      crook    4937: on the @i{target} system could implement a protocol across a
1.32      anton    4938: communication link that would allow it to interrogate the header space.
1.27      crook    4939: @end itemize
                   4940: 
1.32      anton    4941: @node Dictionary allocation, Heap Allocation, Memory model, Memory
                   4942: @subsection Dictionary allocation
1.27      crook    4943: @cindex reserving data space
                   4944: @cindex data space - reserving some
                   4945: 
1.32      anton    4946: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
                   4947: you want to deallocate X, you also deallocate everything
                   4948: allocated after X.
                   4949: 
                   4950: The allocations using the words below are contiguous and grow the region
                   4951: towards increasing addresses.  Other words that allocate dictionary
                   4952: memory of any kind (i.e., defining words including @code{:noname}) end
                   4953: the contiguous region and start a new one.
                   4954: 
                   4955: In ANS Forth only @code{create}d words are guaranteed to produce an
                   4956: address that is the start of the following contiguous region.  In
                   4957: particular, the cell allocated by @code{variable} is not guaranteed to
                   4958: be contiguous with following @code{allot}ed memory.
                   4959: 
                   4960: You can deallocate memory by using @code{allot} with a negative argument
                   4961: (with some restrictions, see @code{allot}). For larger deallocations use
                   4962: @code{marker}.
1.27      crook    4963: 
1.29      crook    4964: 
1.27      crook    4965: doc-here
                   4966: doc-unused
                   4967: doc-allot
                   4968: doc-c,
1.29      crook    4969: doc-f,
1.27      crook    4970: doc-,
                   4971: doc-2,
1.29      crook    4972: @cindex user space
                   4973: doc-udp
                   4974: doc-uallot
1.27      crook    4975: 
1.32      anton    4976: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
                   4977: course you should allocate memory in an aligned way, too. I.e., before
                   4978: allocating allocating a cell, @code{here} must be cell-aligned, etc.
                   4979: The words below align @code{here} if it is not already.  Basically it is
                   4980: only already aligned for a type, if the last allocation was a multiple
                   4981: of the size of this type and if @code{here} was aligned for this type
                   4982: before.
                   4983: 
                   4984: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
                   4985: ANS Forth (@code{maxalign}ed in Gforth).
                   4986: 
                   4987: doc-align
                   4988: doc-falign
                   4989: doc-sfalign
                   4990: doc-dfalign
                   4991: doc-maxalign
                   4992: doc-cfalign
                   4993: 
                   4994: 
                   4995: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
                   4996: @subsection Heap allocation
                   4997: @cindex heap allocation
                   4998: @cindex dynamic allocation of memory
                   4999: @cindex memory-allocation word set
                   5000: 
                   5001: Heap allocation supports deallocation of allocated memory in any
                   5002: order. Dictionary allocation is not affected by it (i.e., it does not
                   5003: end a contiguous region). In Gforth, these words are implemented using
                   5004: the standard C library calls malloc(), free() and resize().
                   5005: 
                   5006: doc-allocate
                   5007: doc-free
                   5008: doc-resize
                   5009: 
1.27      crook    5010: 
1.32      anton    5011: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1       anton    5012: @subsection Memory Access
                   5013: @cindex memory access words
                   5014: 
1.44      crook    5015: 
1.1       anton    5016: doc-@
                   5017: doc-!
                   5018: doc-+!
                   5019: doc-c@
                   5020: doc-c!
                   5021: doc-2@
                   5022: doc-2!
                   5023: doc-f@
                   5024: doc-f!
                   5025: doc-sf@
                   5026: doc-sf!
                   5027: doc-df@
                   5028: doc-df!
                   5029: 
1.32      anton    5030: @node Address arithmetic, Memory Blocks, Memory Access, Memory
                   5031: @subsection Address arithmetic
1.1       anton    5032: @cindex address arithmetic words
                   5033: 
1.32      anton    5034: Address arithmetic is the foundation on which data structures like
                   5035: arrays, records (@pxref{Structures}) and objects (@pxref{Object-oriented
                   5036: Forth}) are built.
                   5037: 
1.1       anton    5038: ANS Forth does not specify the sizes of the data types. Instead, it
                   5039: offers a number of words for computing sizes and doing address
1.29      crook    5040: arithmetic. Address arithmetic is performed in terms of address units
                   5041: (aus); on most systems the address unit is one byte. Note that a
                   5042: character may have more than one au, so @code{chars} is no noop (on
                   5043: systems where it is a noop, it compiles to nothing).
1.1       anton    5044: 
                   5045: @cindex alignment of addresses for types
                   5046: ANS Forth also defines words for aligning addresses for specific
                   5047: types. Many computers require that accesses to specific data types
                   5048: must only occur at specific addresses; e.g., that cells may only be
                   5049: accessed at addresses divisible by 4. Even if a machine allows unaligned
                   5050: accesses, it can usually perform aligned accesses faster. 
                   5051: 
                   5052: For the performance-conscious: alignment operations are usually only
                   5053: necessary during the definition of a data structure, not during the
                   5054: (more frequent) accesses to it.
                   5055: 
                   5056: ANS Forth defines no words for character-aligning addresses. This is not
                   5057: an oversight, but reflects the fact that addresses that are not
                   5058: char-aligned have no use in the standard and therefore will not be
                   5059: created.
                   5060: 
                   5061: @cindex @code{CREATE} and alignment
1.29      crook    5062: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1       anton    5063: are cell-aligned; in addition, Gforth guarantees that these addresses
                   5064: are aligned for all purposes.
                   5065: 
1.26      crook    5066: Note that the ANS Forth word @code{char} has nothing to do with address
                   5067: arithmetic.
1.1       anton    5068: 
1.44      crook    5069: 
1.1       anton    5070: doc-chars
                   5071: doc-char+
                   5072: doc-cells
                   5073: doc-cell+
                   5074: doc-cell
                   5075: doc-aligned
                   5076: doc-floats
                   5077: doc-float+
                   5078: doc-float
                   5079: doc-faligned
                   5080: doc-sfloats
                   5081: doc-sfloat+
                   5082: doc-sfaligned
                   5083: doc-dfloats
                   5084: doc-dfloat+
                   5085: doc-dfaligned
                   5086: doc-maxaligned
                   5087: doc-cfaligned
                   5088: doc-address-unit-bits
                   5089: 
1.44      crook    5090: 
1.32      anton    5091: @node Memory Blocks,  , Address arithmetic, Memory
1.1       anton    5092: @subsection Memory Blocks
                   5093: @cindex memory block words
1.27      crook    5094: @cindex character strings - moving and copying
                   5095: 
1.49      anton    5096: Memory blocks often represent character strings; For ways of storing
                   5097: character strings in memory see @ref{String Formats}.  For other
                   5098: string-processing words see @ref{Displaying characters and strings}.
1.1       anton    5099: 
1.32      anton    5100: Some of these words work on address units. Others work on character
                   5101: units (increments of @code{CHAR}), and expect a @code{CHAR}-aligned
                   5102: address. Choose the correct operation depending upon your data type.
1.21      crook    5103: 
                   5104: When copying characters between overlapping memory regions, choose
                   5105: carefully between @code{cmove} and @code{cmove>}.
                   5106: 
1.29      crook    5107: You can only use any of these words @i{portably} to access data space.
1.21      crook    5108: 
1.27      crook    5109: @comment TODO - think the naming of the arguments is wrong for move
1.29      crook    5110: @comment well, really it seems to be the Standard that's wrong; it
                   5111: @comment describes MOVE as a word that requires a CELL-aligned source
                   5112: @comment and destination address but a xtranfer count that need not
                   5113: @comment be a multiple of CELL.
1.44      crook    5114: 
1.1       anton    5115: doc-move
                   5116: doc-erase
                   5117: doc-cmove
                   5118: doc-cmove>
                   5119: doc-fill
                   5120: doc-blank
1.21      crook    5121: doc-compare
                   5122: doc-search
1.27      crook    5123: doc--trailing
                   5124: doc-/string
                   5125: 
1.44      crook    5126: 
1.27      crook    5127: @comment TODO examples
                   5128: 
1.1       anton    5129: 
1.26      crook    5130: @node Control Structures, Defining Words, Memory, Words
1.1       anton    5131: @section Control Structures
                   5132: @cindex control structures
                   5133: 
1.33      anton    5134: Control structures in Forth cannot be used interpretively, only in a
                   5135: colon definition@footnote{To be precise, they have no interpretation
                   5136: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
                   5137: not like this limitation, but have not seen a satisfying way around it
                   5138: yet, although many schemes have been proposed.
1.1       anton    5139: 
                   5140: @menu
1.33      anton    5141: * Selection::                   IF ... ELSE ... ENDIF
                   5142: * Simple Loops::                BEGIN ...
1.29      crook    5143: * Counted Loops::               DO
                   5144: * Arbitrary control structures::
                   5145: * Calls and returns::
1.1       anton    5146: * Exception Handling::          
                   5147: @end menu
                   5148: 
                   5149: @node Selection, Simple Loops, Control Structures, Control Structures
                   5150: @subsection Selection
                   5151: @cindex selection control structures
                   5152: @cindex control structures for selection
                   5153: 
1.33      anton    5154: @c what's the purpose of all these @i? Maybe we should define a macro
                   5155: @c so we can produce logical markup.  - anton
                   5156: 
1.44      crook    5157: @c nac-> When I started working on the manual, a mixture of @i and @var
                   5158: @c were used inconsistently in code examples and \Glossary entries. These
                   5159: @c two behave differently in info format so I decided to standardize on @i.
                   5160: @c Logical markup would be better but texi isn't really upto it, and
                   5161: @c texi2html just ignores macros.
1.47      crook    5162: @c nac02dec1999-> update: the latest texinfo release can spit out html
                   5163: @c and it handles macros, so we could do some logical markup. Unfortunately
                   5164: @c texinfo will not split html output, which would be a big pain if you
                   5165: @c wanted to put the document on the web, which would be nice.
1.44      crook    5166: 
1.1       anton    5167: @cindex @code{IF} control structure
                   5168: @example
1.29      crook    5169: @i{flag}
1.1       anton    5170: IF
1.29      crook    5171:   @i{code}
1.1       anton    5172: ENDIF
                   5173: @end example
1.21      crook    5174: @noindent
1.33      anton    5175: 
1.44      crook    5176: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
                   5177: with any bit set represents truth) @i{code} is executed.
1.33      anton    5178: 
1.1       anton    5179: @example
1.29      crook    5180: @i{flag}
1.1       anton    5181: IF
1.29      crook    5182:   @i{code1}
1.1       anton    5183: ELSE
1.29      crook    5184:   @i{code2}
1.1       anton    5185: ENDIF
                   5186: @end example
                   5187: 
1.44      crook    5188: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
                   5189: executed.
1.33      anton    5190: 
1.1       anton    5191: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
                   5192: standard, and @code{ENDIF} is not, although it is quite popular. We
                   5193: recommend using @code{ENDIF}, because it is less confusing for people
                   5194: who also know other languages (and is not prone to reinforcing negative
                   5195: prejudices against Forth in these people). Adding @code{ENDIF} to a
                   5196: system that only supplies @code{THEN} is simple:
                   5197: @example
1.21      crook    5198: : ENDIF   POSTPONE THEN ; immediate
1.1       anton    5199: @end example
                   5200: 
                   5201: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
                   5202: (adv.)}  has the following meanings:
                   5203: @quotation
                   5204: ... 2b: following next after in order ... 3d: as a necessary consequence
                   5205: (if you were there, then you saw them).
                   5206: @end quotation
                   5207: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
                   5208: and many other programming languages has the meaning 3d.]
                   5209: 
1.21      crook    5210: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1       anton    5211: you can avoid using @code{?dup}. Using these alternatives is also more
1.26      crook    5212: efficient than using @code{?dup}. Definitions in ANS Forth
1.1       anton    5213: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
                   5214: @file{compat/control.fs}.
                   5215: 
                   5216: @cindex @code{CASE} control structure
                   5217: @example
1.29      crook    5218: @i{n}
1.1       anton    5219: CASE
1.29      crook    5220:   @i{n1} OF @i{code1} ENDOF
                   5221:   @i{n2} OF @i{code2} ENDOF
1.1       anton    5222:   @dots{}
                   5223: ENDCASE
                   5224: @end example
                   5225: 
1.29      crook    5226: Executes the first @i{codei}, where the @i{ni} is equal to
                   5227: @i{n}. A default case can be added by simply writing the code after
                   5228: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
1.1       anton    5229: but must not consume it.
                   5230: 
                   5231: @node Simple Loops, Counted Loops, Selection, Control Structures
                   5232: @subsection Simple Loops
                   5233: @cindex simple loops
                   5234: @cindex loops without count 
                   5235: 
                   5236: @cindex @code{WHILE} loop
                   5237: @example
                   5238: BEGIN
1.29      crook    5239:   @i{code1}
                   5240:   @i{flag}
1.1       anton    5241: WHILE
1.29      crook    5242:   @i{code2}
1.1       anton    5243: REPEAT
                   5244: @end example
                   5245: 
1.29      crook    5246: @i{code1} is executed and @i{flag} is computed. If it is true,
                   5247: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1       anton    5248: false, execution continues after the @code{REPEAT}.
                   5249: 
                   5250: @cindex @code{UNTIL} loop
                   5251: @example
                   5252: BEGIN
1.29      crook    5253:   @i{code}
                   5254:   @i{flag}
1.1       anton    5255: UNTIL
                   5256: @end example
                   5257: 
1.29      crook    5258: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1       anton    5259: 
                   5260: @cindex endless loop
                   5261: @cindex loops, endless
                   5262: @example
                   5263: BEGIN
1.29      crook    5264:   @i{code}
1.1       anton    5265: AGAIN
                   5266: @end example
                   5267: 
                   5268: This is an endless loop.
                   5269: 
                   5270: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
                   5271: @subsection Counted Loops
                   5272: @cindex counted loops
                   5273: @cindex loops, counted
                   5274: @cindex @code{DO} loops
                   5275: 
                   5276: The basic counted loop is:
                   5277: @example
1.29      crook    5278: @i{limit} @i{start}
1.1       anton    5279: ?DO
1.29      crook    5280:   @i{body}
1.1       anton    5281: LOOP
                   5282: @end example
                   5283: 
1.29      crook    5284: This performs one iteration for every integer, starting from @i{start}
                   5285: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21      crook    5286: accessed with @code{i}. For example, the loop:
1.1       anton    5287: @example
                   5288: 10 0 ?DO
                   5289:   i .
                   5290: LOOP
                   5291: @end example
1.21      crook    5292: @noindent
                   5293: prints @code{0 1 2 3 4 5 6 7 8 9}
                   5294: 
1.1       anton    5295: The index of the innermost loop can be accessed with @code{i}, the index
                   5296: of the next loop with @code{j}, and the index of the third loop with
                   5297: @code{k}.
                   5298: 
1.44      crook    5299: 
1.1       anton    5300: doc-i
                   5301: doc-j
                   5302: doc-k
                   5303: 
1.44      crook    5304: 
1.1       anton    5305: The loop control data are kept on the return stack, so there are some
1.21      crook    5306: restrictions on mixing return stack accesses and counted loop words. In
                   5307: particuler, if you put values on the return stack outside the loop, you
                   5308: cannot read them inside the loop@footnote{well, not in a way that is
                   5309: portable.}. If you put values on the return stack within a loop, you
                   5310: have to remove them before the end of the loop and before accessing the
                   5311: index of the loop.
1.1       anton    5312: 
                   5313: There are several variations on the counted loop:
                   5314: 
1.21      crook    5315: @itemize @bullet
                   5316: @item
                   5317: @code{LEAVE} leaves the innermost counted loop immediately; execution
                   5318: continues after the associated @code{LOOP} or @code{NEXT}. For example:
                   5319: 
                   5320: @example
                   5321: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
                   5322: @end example
                   5323: prints @code{0 1 2 3}
                   5324: 
1.1       anton    5325: 
1.21      crook    5326: @item
                   5327: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
                   5328: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
                   5329: return stack so @code{EXIT} can get to its return address. For example:
                   5330: 
                   5331: @example
                   5332: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
                   5333: @end example
                   5334: prints @code{0 1 2 3}
                   5335: 
                   5336: 
                   5337: @item
1.29      crook    5338: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1       anton    5339: (and @code{LOOP} iterates until they become equal by wrap-around
                   5340: arithmetic). This behaviour is usually not what you want. Therefore,
                   5341: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29      crook    5342: @code{?DO}), which do not enter the loop if @i{start} is greater than
                   5343: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1       anton    5344: unsigned loop parameters.
                   5345: 
1.21      crook    5346: @item
                   5347: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
                   5348: the loop, independent of the loop parameters. Do not use @code{DO}, even
                   5349: if you know that the loop is entered in any case. Such knowledge tends
                   5350: to become invalid during maintenance of a program, and then the
                   5351: @code{DO} will make trouble.
                   5352: 
                   5353: @item
1.29      crook    5354: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
                   5355: index by @i{n} instead of by 1. The loop is terminated when the border
                   5356: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1       anton    5357: 
1.21      crook    5358: @example
                   5359: 4 0 +DO  i .  2 +LOOP
                   5360: @end example
                   5361: @noindent
                   5362: prints @code{0 2}
                   5363: 
                   5364: @example
                   5365: 4 1 +DO  i .  2 +LOOP
                   5366: @end example
                   5367: @noindent
                   5368: prints @code{1 3}
1.1       anton    5369: 
                   5370: 
                   5371: @cindex negative increment for counted loops
                   5372: @cindex counted loops with negative increment
1.29      crook    5373: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1       anton    5374: 
1.21      crook    5375: @example
                   5376: -1 0 ?DO  i .  -1 +LOOP
                   5377: @end example
                   5378: @noindent
                   5379: prints @code{0 -1}
1.1       anton    5380: 
1.21      crook    5381: @example
                   5382: 0 0 ?DO  i .  -1 +LOOP
                   5383: @end example
                   5384: prints nothing.
1.1       anton    5385: 
1.29      crook    5386: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
                   5387: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
                   5388: index by @i{u} each iteration. The loop is terminated when the border
                   5389: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1       anton    5390: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
                   5391: 
1.21      crook    5392: @example
                   5393: -2 0 -DO  i .  1 -LOOP
                   5394: @end example
                   5395: @noindent
                   5396: prints @code{0 -1}
1.1       anton    5397: 
1.21      crook    5398: @example
                   5399: -1 0 -DO  i .  1 -LOOP
                   5400: @end example
                   5401: @noindent
                   5402: prints @code{0}
                   5403: 
                   5404: @example
                   5405: 0 0 -DO  i .  1 -LOOP
                   5406: @end example
                   5407: @noindent
                   5408: prints nothing.
1.1       anton    5409: 
1.21      crook    5410: @end itemize
1.1       anton    5411: 
                   5412: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26      crook    5413: @code{-LOOP} are not defined in ANS Forth. However, an implementation
                   5414: for these words that uses only standard words is provided in
                   5415: @file{compat/loops.fs}.
1.1       anton    5416: 
                   5417: 
                   5418: @cindex @code{FOR} loops
1.26      crook    5419: Another counted loop is:
1.1       anton    5420: @example
1.29      crook    5421: @i{n}
1.1       anton    5422: FOR
1.29      crook    5423:   @i{body}
1.1       anton    5424: NEXT
                   5425: @end example
                   5426: This is the preferred loop of native code compiler writers who are too
1.26      crook    5427: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29      crook    5428: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
                   5429: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26      crook    5430: Forth systems may behave differently, even if they support @code{FOR}
                   5431: loops. To avoid problems, don't use @code{FOR} loops.
1.1       anton    5432: 
                   5433: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
                   5434: @subsection Arbitrary control structures
                   5435: @cindex control structures, user-defined
                   5436: 
                   5437: @cindex control-flow stack
                   5438: ANS Forth permits and supports using control structures in a non-nested
                   5439: way. Information about incomplete control structures is stored on the
                   5440: control-flow stack. This stack may be implemented on the Forth data
                   5441: stack, and this is what we have done in Gforth.
                   5442: 
                   5443: @cindex @code{orig}, control-flow stack item
                   5444: @cindex @code{dest}, control-flow stack item
                   5445: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
                   5446: entry represents a backward branch target. A few words are the basis for
                   5447: building any control structure possible (except control structures that
                   5448: need storage, like calls, coroutines, and backtracking).
                   5449: 
1.44      crook    5450: 
1.1       anton    5451: doc-if
                   5452: doc-ahead
                   5453: doc-then
                   5454: doc-begin
                   5455: doc-until
                   5456: doc-again
                   5457: doc-cs-pick
                   5458: doc-cs-roll
                   5459: 
1.44      crook    5460: 
1.21      crook    5461: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
                   5462: manipulate the control-flow stack in a portable way. Without them, you
                   5463: would need to know how many stack items are occupied by a control-flow
                   5464: entry (many systems use one cell. In Gforth they currently take three,
                   5465: but this may change in the future).
                   5466: 
1.1       anton    5467: Some standard control structure words are built from these words:
                   5468: 
1.44      crook    5469: 
1.1       anton    5470: doc-else
                   5471: doc-while
                   5472: doc-repeat
                   5473: 
1.44      crook    5474: 
                   5475: @noindent
1.1       anton    5476: Gforth adds some more control-structure words:
                   5477: 
1.44      crook    5478: 
1.1       anton    5479: doc-endif
                   5480: doc-?dup-if
                   5481: doc-?dup-0=-if
                   5482: 
1.44      crook    5483: 
                   5484: @noindent
1.1       anton    5485: Counted loop words constitute a separate group of words:
                   5486: 
1.44      crook    5487: 
1.1       anton    5488: doc-?do
                   5489: doc-+do
                   5490: doc-u+do
                   5491: doc--do
                   5492: doc-u-do
                   5493: doc-do
                   5494: doc-for
                   5495: doc-loop
                   5496: doc-+loop
                   5497: doc--loop
                   5498: doc-next
                   5499: doc-leave
                   5500: doc-?leave
                   5501: doc-unloop
                   5502: doc-done
                   5503: 
1.44      crook    5504: 
1.21      crook    5505: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
                   5506: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1       anton    5507: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
                   5508: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
                   5509: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
                   5510: resolved (by using one of the loop-ending words or @code{DONE}).
                   5511: 
1.44      crook    5512: @noindent
1.26      crook    5513: Another group of control structure words are:
1.1       anton    5514: 
1.44      crook    5515: 
1.1       anton    5516: doc-case
                   5517: doc-endcase
                   5518: doc-of
                   5519: doc-endof
                   5520: 
1.44      crook    5521: 
1.21      crook    5522: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
                   5523: @code{CS-ROLL}.
1.1       anton    5524: 
                   5525: @subsubsection Programming Style
1.47      crook    5526: @cindex control structures programming style
                   5527: @cindex programming style, arbitrary control structures
1.1       anton    5528: 
                   5529: In order to ensure readability we recommend that you do not create
                   5530: arbitrary control structures directly, but define new control structure
                   5531: words for the control structure you want and use these words in your
1.26      crook    5532: program. For example, instead of writing:
1.1       anton    5533: 
                   5534: @example
1.26      crook    5535: BEGIN
1.1       anton    5536:   ...
1.26      crook    5537: IF [ 1 CS-ROLL ]
1.1       anton    5538:   ...
1.26      crook    5539: AGAIN THEN
1.1       anton    5540: @end example
                   5541: 
1.21      crook    5542: @noindent
1.1       anton    5543: we recommend defining control structure words, e.g.,
                   5544: 
                   5545: @example
1.26      crook    5546: : WHILE ( DEST -- ORIG DEST )
                   5547:  POSTPONE IF
                   5548:  1 CS-ROLL ; immediate
                   5549: 
                   5550: : REPEAT ( orig dest -- )
                   5551:  POSTPONE AGAIN
                   5552:  POSTPONE THEN ; immediate
1.1       anton    5553: @end example
                   5554: 
1.21      crook    5555: @noindent
1.1       anton    5556: and then using these to create the control structure:
                   5557: 
                   5558: @example
1.26      crook    5559: BEGIN
1.1       anton    5560:   ...
1.26      crook    5561: WHILE
1.1       anton    5562:   ...
1.26      crook    5563: REPEAT
1.1       anton    5564: @end example
                   5565: 
                   5566: That's much easier to read, isn't it? Of course, @code{REPEAT} and
                   5567: @code{WHILE} are predefined, so in this example it would not be
                   5568: necessary to define them.
                   5569: 
                   5570: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
                   5571: @subsection Calls and returns
                   5572: @cindex calling a definition
                   5573: @cindex returning from a definition
                   5574: 
1.3       anton    5575: @cindex recursive definitions
                   5576: A definition can be called simply be writing the name of the definition
1.26      crook    5577: to be called. Normally a definition is invisible during its own
1.3       anton    5578: definition. If you want to write a directly recursive definition, you
1.26      crook    5579: can use @code{recursive} to make the current definition visible, or
                   5580: @code{recurse} to call the current definition directly.
1.3       anton    5581: 
1.44      crook    5582: 
1.3       anton    5583: doc-recursive
                   5584: doc-recurse
                   5585: 
1.44      crook    5586: 
1.21      crook    5587: @comment TODO add example of the two recursion methods
1.12      anton    5588: @quotation
                   5589: @progstyle
                   5590: I prefer using @code{recursive} to @code{recurse}, because calling the
                   5591: definition by name is more descriptive (if the name is well-chosen) than
                   5592: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
                   5593: implementation, it is much better to read (and think) ``now sort the
                   5594: partitions'' than to read ``now do a recursive call''.
                   5595: @end quotation
1.3       anton    5596: 
1.29      crook    5597: For mutual recursion, use @code{Defer}red words, like this:
1.3       anton    5598: 
                   5599: @example
1.28      crook    5600: Defer foo
1.3       anton    5601: 
                   5602: : bar ( ... -- ... )
                   5603:  ... foo ... ;
                   5604: 
                   5605: :noname ( ... -- ... )
                   5606:  ... bar ... ;
                   5607: IS foo
                   5608: @end example
                   5609: 
1.44      crook    5610: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33      anton    5611: 
1.26      crook    5612: The current definition returns control to the calling definition when
1.33      anton    5613: the end of the definition is reached or @code{EXIT} is encountered.
1.1       anton    5614: 
                   5615: doc-exit
                   5616: doc-;s
                   5617: 
1.44      crook    5618: 
1.1       anton    5619: @node Exception Handling,  , Calls and returns, Control Structures
                   5620: @subsection Exception Handling
1.26      crook    5621: @cindex exceptions
1.1       anton    5622: 
1.26      crook    5623: If your program detects a fatal error condition, the simplest action
                   5624: that it can take is to @code{quit}. This resets the return stack and
                   5625: restarts the text interpreter, but does not print any error message.
1.21      crook    5626: 
1.26      crook    5627: The next stage in severity is to execute @code{abort}, which has the
                   5628: same effect as @code{quit}, with the addition that it resets the data
                   5629: stack.
1.1       anton    5630: 
1.26      crook    5631: A slightly more sophisticated approach is use use @code{abort"}, which
                   5632: compiles a string to be used as an error message and does a conditional
                   5633: @code{abort} at run-time. For example:
1.1       anton    5634: 
1.26      crook    5635: @example
1.30      anton    5636: @kbd{: checker abort" That flag was true" ." A false flag" ;@key{RET}}  ok
                   5637: @kbd{0 checker@key{RET}} A false flag ok
                   5638: @kbd{1 checker@key{RET}}
1.26      crook    5639: :1: That flag was true
                   5640: 1 checker
                   5641:   ^^^^^^^
                   5642: $400D1648 throw 
                   5643: $400E4660
                   5644: @end example
1.1       anton    5645: 
1.26      crook    5646: These simple techniques allow a program to react to a fatal error
                   5647: condition, but they are not exactly user-friendly. The ANS Forth
                   5648: Exception word set provides the pair of words @code{throw} and
                   5649: @code{catch}, which can be used to provide sophisticated error-handling.
1.1       anton    5650: 
1.26      crook    5651: @code{catch} has a similar behaviour to @code{execute}, in that it takes
1.29      crook    5652: an @i{xt} as a parameter and starts execution of the xt. However,
1.26      crook    5653: before passing control to the xt, @code{catch} pushes an
1.29      crook    5654: @dfn{exception frame} onto the @dfn{exception stack}. This exception
1.26      crook    5655: frame is used to restore the system to a known state if a detected error
                   5656: occurs during the execution of the xt. A typical way to use @code{catch}
                   5657: would be:
1.1       anton    5658: 
1.26      crook    5659: @example
                   5660: ... ['] foo catch IF ...
                   5661: @end example
1.1       anton    5662: 
1.33      anton    5663: @c TOS is undefined. - anton
1.44      crook    5664: 
                   5665: @c nac-> TODO -- I need to look at this example again.
                   5666: 
1.26      crook    5667: Whilst @code{foo} executes, it can call other words to any level of
                   5668: nesting, as usual.  If @code{foo} (and all the words that it calls)
1.33      anton    5669: execute successfully, control will ultimately pass to the word following
                   5670: the @code{catch}, and there will be a 0 at TOS.  However, if any word
                   5671: detects an error, it can terminate the execution of @code{foo} by
                   5672: pushing a non-zero error code onto the stack and then performing a
                   5673: @code{throw}. The execution of @code{throw} will pass control to the
                   5674: word following the @code{catch}, but this time the TOS will hold the
                   5675: error code. Therefore, the @code{IF} in the example can be used to
                   5676: determine whether @code{foo} executed successfully.
1.1       anton    5677: 
1.26      crook    5678: This simple example shows how you can use @code{throw} and @code{catch}
                   5679: to ``take over'' exception handling from the system:
1.1       anton    5680: @example
1.26      crook    5681: : my-div ['] / catch if ." DIVIDE ERROR" else ." OK.. " . then ;
1.1       anton    5682: @end example
                   5683: 
1.26      crook    5684: The next example is more sophisticated and shows a multi-level
                   5685: @code{throw} and @code{catch}. To understand this example, start at the
                   5686: definition of @code{top-level} and work backwards:
                   5687: 
1.1       anton    5688: @example
1.26      crook    5689: : lowest-level ( -- c )
                   5690:     key dup 27 = if
1.44      crook    5691:         1 throw \ ESCAPE key pressed
1.26      crook    5692:     else
1.44      crook    5693:         ." lowest-level successful" CR
1.26      crook    5694:     then
                   5695: ;
                   5696: 
                   5697: : lower-level ( -- c )
                   5698:     lowest-level
                   5699:     \ at this level consider a CTRL-U to be a fatal error
                   5700:     dup 21 = if \ CTRL-U
1.44      crook    5701:         2 throw
1.26      crook    5702:     else
1.44      crook    5703:         ." lower-level successful" CR
1.26      crook    5704:     then
                   5705: ;
                   5706: 
                   5707: : low-level ( -- c )
                   5708:     ['] lower-level catch
                   5709:     ?dup if
1.44      crook    5710:         \ error occurred - do we recognise it?
                   5711:         dup 1 = if
                   5712:             \ ESCAPE key pressed.. pretend it was an E
                   5713:             [char] E
                   5714:         else throw \ propogate the error upwards
                   5715:         then
1.26      crook    5716:     then
                   5717:     ." low-level successfull" CR
                   5718: ;
                   5719: 
                   5720: : top-level ( -- )
                   5721:     CR ['] low-level catch \ CATCH is used like EXECUTE
                   5722:     ?dup if \ error occurred..
1.44      crook    5723:         ." Error " . ." occurred - contact your supplier"
1.26      crook    5724:     else
1.44      crook    5725:         ." The '" emit ." ' key was pressed" CR
1.26      crook    5726:     then
                   5727: ;
1.1       anton    5728: @end example
                   5729: 
1.26      crook    5730: The ANS Forth document assigns @code{throw} codes thus:
1.1       anton    5731: 
1.26      crook    5732: @itemize @bullet
                   5733: @item
                   5734: codes in the range -1 -- -255 are reserved to be assigned by the
                   5735: Standard. Assignments for codes in the range -1 -- -58 are currently
                   5736: documented in the Standard. In particular, @code{-1 throw} is equivalent
                   5737: to @code{abort} and @code{-2 throw} is equivalent to @code{abort"}.
                   5738: @item
                   5739: codes in the range -256 -- -4095 are reserved to be assigned by the system.
                   5740: @item
                   5741: all other codes may be assigned by programs.
                   5742: @end itemize
1.1       anton    5743: 
1.26      crook    5744: Gforth provides the word @code{exception} as a mechanism for assigning
                   5745: system throw codes to applications. This allows multiple applications to
                   5746: co-exist in memory without any clash of @code{throw} codes. A definition
                   5747: of @code{exception} in ANS Forth is provided in
                   5748: @file{compat/exception.fs}.
1.1       anton    5749: 
1.44      crook    5750: 
1.26      crook    5751: doc-quit
                   5752: doc-abort
                   5753: doc-abort"
1.1       anton    5754: 
1.26      crook    5755: doc-catch
1.29      crook    5756: doc-throw
                   5757: doc---exception-exception
                   5758: 
                   5759: 
1.44      crook    5760: 
1.29      crook    5761: @c -------------------------------------------------------------
1.47      crook    5762: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29      crook    5763: @section Defining Words
                   5764: @cindex defining words
                   5765: 
1.47      crook    5766: Defining words are used to extend Forth by creating new entries in the dictionary.
                   5767: 
1.29      crook    5768: @menu
1.44      crook    5769: * CREATE::
                   5770: * Variables::                   Variables and user variables
                   5771: * Constants::
                   5772: * Values::                      Initialised variables
1.29      crook    5773: * Colon Definitions::
1.44      crook    5774: * Anonymous Definitions::       Definitions without names
1.29      crook    5775: * User-defined Defining Words::
1.44      crook    5776: * Deferred words::              Allow forward references
                   5777: * Aliases::
1.29      crook    5778: * Supplying names::
                   5779: @end menu
                   5780: 
1.44      crook    5781: @node CREATE, Variables, Defining Words, Defining Words
                   5782: @subsection @code{CREATE}
1.29      crook    5783: @cindex simple defining words
                   5784: @cindex defining words, simple
                   5785: 
                   5786: Defining words are used to create new entries in the dictionary. The
                   5787: simplest defining word is @code{CREATE}. @code{CREATE} is used like
                   5788: this:
                   5789: 
                   5790: @example
                   5791: CREATE new-word1
                   5792: @end example
                   5793: 
                   5794: @code{CREATE} is a parsing word that generates a dictionary entry for
                   5795: @code{new-word1}. When @code{new-word1} is executed, all that it does is
                   5796: leave an address on the stack. The address represents the value of
                   5797: the data space pointer (@code{HERE}) at the time that @code{new-word1}
                   5798: was defined. Therefore, @code{CREATE} is a way of associating a name
                   5799: with the address of a region of memory.
                   5800: 
1.34      anton    5801: doc-create
                   5802: 
1.29      crook    5803: By extending this example to reserve some memory in data space, we end
                   5804: up with a @i{variable}. Here are two different ways to do it:
                   5805: 
                   5806: @example
                   5807: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
                   5808: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
                   5809: @end example
                   5810: 
                   5811: The variable can be examined and modified using @code{@@} (``fetch'') and
                   5812: @code{!} (``store'') like this:
                   5813: 
                   5814: @example
                   5815: new-word2 @@ .      \ get address, fetch from it and display
                   5816: 1234 new-word2 !   \ new value, get address, store to it
                   5817: @end example
                   5818: 
1.44      crook    5819: @cindex arrays
                   5820: A similar mechanism can be used to create arrays. For example, an
                   5821: 80-character text input buffer:
1.29      crook    5822: 
                   5823: @example
1.44      crook    5824: CREATE text-buf 80 chars allot
                   5825: 
                   5826: text-buf 0 chars c@@ \ the 1st character (offset 0)
                   5827: text-buf 3 chars c@@ \ the 4th character (offset 3)
                   5828: @end example
1.29      crook    5829: 
1.44      crook    5830: You can build arbitrarily complex data structures by allocating
1.49      anton    5831: appropriate areas of memory. For further discussions of this, and to
                   5832: learn about some Gforth tools that make it easier, see
                   5833: @xref{Structures}.
1.44      crook    5834: 
                   5835: 
                   5836: @node Variables, Constants, CREATE, Defining Words
                   5837: @subsection Variables
                   5838: @cindex variables
                   5839: 
                   5840: The previous section showed how a sequence of commands could be used to
                   5841: generate a variable.  As a final refinement, the whole code sequence can
                   5842: be wrapped up in a defining word (pre-empting the subject of the next
                   5843: section), making it easier to create new variables:
                   5844: 
                   5845: @example
                   5846: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
                   5847: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
                   5848: 
                   5849: myvariableX foo \ variable foo starts off with an unknown value
                   5850: myvariable0 joe \ whilst joe is initialised to 0
1.29      crook    5851: 
                   5852: 45 3 * foo !   \ set foo to 135
                   5853: 1234 joe !     \ set joe to 1234
                   5854: 3 joe +!       \ increment joe by 3.. to 1237
                   5855: @end example
                   5856: 
                   5857: Not surprisingly, there is no need to define @code{myvariable}, since
1.44      crook    5858: Forth already has a definition @code{Variable}. ANS Forth does not
                   5859: require a @code{Variable} to be initialised when it is created (i.e., it
                   5860: behaves like @code{myvariableX}). In contrast, Gforth's @code{Variable}
                   5861: initialises the variable to 0 (i.e., it behaves exactly like
                   5862: @code{myvariable0}). Forth also provides @code{2Variable} and
1.47      crook    5863: @code{fvariable} for double and floating-point variables, respectively
                   5864: -- both are initialised to 0 in Gforth. If you use a @code{Variable} to
                   5865: store a boolean, you can use @code{on} and @code{off} to toggle its
                   5866: state.
1.29      crook    5867: 
1.34      anton    5868: doc-variable
                   5869: doc-2variable
                   5870: doc-fvariable
                   5871: 
1.29      crook    5872: @cindex user variables
                   5873: @cindex user space
                   5874: The defining word @code{User} behaves in the same way as @code{Variable}.
                   5875: The difference is that it reserves space in @i{user (data) space} rather
                   5876: than normal data space. In a Forth system that has a multi-tasker, each
                   5877: task has its own set of user variables.
                   5878: 
1.34      anton    5879: doc-user
                   5880: 
1.29      crook    5881: @comment TODO is that stuff about user variables strictly correct? Is it
                   5882: @comment just terminal tasks that have user variables?
                   5883: @comment should document tasker.fs (with some examples) elsewhere
                   5884: @comment in this manual, then expand on user space and user variables.
                   5885: 
1.44      crook    5886: 
                   5887: @node Constants, Values, Variables, Defining Words
                   5888: @subsection Constants
                   5889: @cindex constants
                   5890: 
                   5891: @code{Constant} allows you to declare a fixed value and refer to it by
                   5892: name. For example:
1.29      crook    5893: 
                   5894: @example
                   5895: 12 Constant INCHES-PER-FOOT
                   5896: 3E+08 fconstant SPEED-O-LIGHT
                   5897: @end example
                   5898: 
                   5899: A @code{Variable} can be both read and written, so its run-time
                   5900: behaviour is to supply an address through which its current value can be
                   5901: manipulated. In contrast, the value of a @code{Constant} cannot be
                   5902: changed once it has been declared@footnote{Well, often it can be -- but
                   5903: not in a Standard, portable way. It's safer to use a @code{Value} (read
                   5904: on).} so it's not necessary to supply the address -- it is more
                   5905: efficient to return the value of the constant directly. That's exactly
                   5906: what happens; the run-time effect of a constant is to put its value on
1.49      anton    5907: the top of the stack (You can find one
                   5908: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29      crook    5909: 
                   5910: Gforth also provides @code{2Constant} and @code{fconstant} for defining
                   5911: double and floating-point constants, respectively.
                   5912: 
1.34      anton    5913: doc-constant
                   5914: doc-2constant
                   5915: doc-fconstant
                   5916: 
                   5917: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44      crook    5918: @c nac-> How could that not be true in an ANS Forth? You can't define a
                   5919: @c constant, use it and then delete the definition of the constant..
                   5920: @c I agree that it's rather deep, but IMO it is an important difference
                   5921: @c relative to other programming languages.. often it's annoying: it
                   5922: @c certainly changes my programming style relative to C.
                   5923: 
1.29      crook    5924: Constants in Forth behave differently from their equivalents in other
                   5925: programming languages. In other languages, a constant (such as an EQU in
                   5926: assembler or a #define in C) only exists at compile-time; in the
                   5927: executable program the constant has been translated into an absolute
                   5928: number and, unless you are using a symbolic debugger, it's impossible to
                   5929: know what abstract thing that number represents. In Forth a constant has
1.44      crook    5930: an entry in the header space and remains there after the code that uses
                   5931: it has been defined. In fact, it must remain in the dictionary since it
                   5932: has run-time duties to perform. For example:
1.29      crook    5933: 
                   5934: @example
                   5935: 12 Constant INCHES-PER-FOOT
                   5936: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
                   5937: @end example
                   5938: 
                   5939: @cindex in-lining of constants
                   5940: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
                   5941: associated with the constant @code{INCHES-PER-FOOT}. If you use
                   5942: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
                   5943: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
                   5944: attempt to optimise constants by in-lining them where they are used. You
                   5945: can force Gforth to in-line a constant like this:
                   5946: 
                   5947: @example
                   5948: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
                   5949: @end example
                   5950: 
                   5951: If you use @code{see} to decompile @i{this} version of
                   5952: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49      anton    5953: longer present. To understand how this works, read
                   5954: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29      crook    5955: 
                   5956: In-lining constants in this way might improve execution time
                   5957: fractionally, and can ensure that a constant is now only referenced at
                   5958: compile-time. However, the definition of the constant still remains in
                   5959: the dictionary. Some Forth compilers provide a mechanism for controlling
                   5960: a second dictionary for holding transient words such that this second
                   5961: dictionary can be deleted later in order to recover memory
                   5962: space. However, there is no standard way of doing this.
                   5963: 
                   5964: 
1.44      crook    5965: @node Values, Colon Definitions, Constants, Defining Words
                   5966: @subsection Values
                   5967: @cindex values
1.34      anton    5968: 
1.44      crook    5969: A @code{Value} is like a @code{Variable} but with two important
                   5970: differences:
1.29      crook    5971: 
                   5972: @itemize @bullet
                   5973: @item
1.44      crook    5974: A @code{Value} is initialised when it is declared; like a
                   5975: @code{Constant} but unlike a @code{Variable}.
1.29      crook    5976: @item
1.44      crook    5977: A @code{Value} returns its value rather than its address when it is
                   5978: executed; i.e., it has the same run-time behaviour as @code{Constant}.
1.29      crook    5979: @end itemize
                   5980: 
1.44      crook    5981: A @code{Value} needs an additional word, @code{TO} to allow its value to
                   5982: be changed. Here are some examples:
1.29      crook    5983: 
                   5984: @example
1.44      crook    5985: 12 Value APPLES \ Define APPLES with an initial value of 12
                   5986: 34 TO APPLES    \ Change the value of APPLES. TO is a parsing word
                   5987: APPLES          \ puts 34 on the top of the stack.
1.29      crook    5988: @end example
                   5989: 
1.44      crook    5990: doc-value
                   5991: doc-to
1.29      crook    5992: 
1.35      anton    5993: 
1.44      crook    5994: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
                   5995: @subsection Colon Definitions
                   5996: @cindex colon definitions
1.35      anton    5997: 
                   5998: @example
1.44      crook    5999: : name ( ... -- ... )
                   6000:     word1 word2 word3 ;
1.29      crook    6001: @end example
                   6002: 
1.44      crook    6003: @noindent
                   6004: Creates a word called @code{name} that, upon execution, executes
                   6005: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29      crook    6006: 
1.49      anton    6007: The explanation above is somewhat superficial. For simple examples of
                   6008: colon definitions see @ref{Your first definition}.  For an in-depth
                   6009: discussion of some of the issues involved, see @xref{Interpretation and
                   6010: Compilation Semantics}.
1.29      crook    6011: 
1.44      crook    6012: doc-:
                   6013: doc-;
1.1       anton    6014: 
1.34      anton    6015: 
1.44      crook    6016: @node Anonymous Definitions, User-defined Defining Words, Colon Definitions, Defining Words
                   6017: @subsection Anonymous Definitions
                   6018: @cindex colon definitions
                   6019: @cindex defining words without name
1.34      anton    6020: 
1.44      crook    6021: Sometimes you want to define an @dfn{anonymous word}; a word without a
                   6022: name. You can do this with:
1.1       anton    6023: 
1.44      crook    6024: doc-:noname
1.1       anton    6025: 
1.44      crook    6026: This leaves the execution token for the word on the stack after the
                   6027: closing @code{;}. Here's an example in which a deferred word is
                   6028: initialised with an @code{xt} from an anonymous colon definition:
1.1       anton    6029: 
1.29      crook    6030: @example
1.44      crook    6031: Defer deferred
                   6032: :noname ( ... -- ... )
                   6033:   ... ;
                   6034: IS deferred
1.29      crook    6035: @end example
1.26      crook    6036: 
1.44      crook    6037: @noindent
                   6038: Gforth provides an alternative way of doing this, using two separate
                   6039: words:
1.27      crook    6040: 
1.44      crook    6041: doc-noname
                   6042: @cindex execution token of last defined word
                   6043: doc-lastxt
1.1       anton    6044: 
1.44      crook    6045: @noindent
                   6046: The previous example can be rewritten using @code{noname} and
                   6047: @code{lastxt}:
1.1       anton    6048: 
1.26      crook    6049: @example
1.44      crook    6050: Defer deferred
                   6051: noname : ( ... -- ... )
                   6052:   ... ;
                   6053: lastxt IS deferred
1.26      crook    6054: @end example
1.1       anton    6055: 
1.29      crook    6056: @noindent
1.44      crook    6057: @code{noname} works with any defining word, not just @code{:}.
                   6058: 
                   6059: @code{lastxt} also works when the last word was not defined as
                   6060: @code{noname}. It also has the useful property that is is valid as soon
                   6061: as the header for a definition has been built. Thus:
                   6062: 
                   6063: @example
                   6064: lastxt . : foo [ lastxt . ] ; ' foo .
                   6065: @end example
1.1       anton    6066: 
1.44      crook    6067: @noindent
                   6068: prints 3 numbers; the last two are the same.
1.26      crook    6069: 
1.1       anton    6070: 
1.44      crook    6071: @node User-defined Defining Words, Deferred words, Anonymous Definitions, Defining Words
1.26      crook    6072: @subsection User-defined Defining Words
                   6073: @cindex user-defined defining words
                   6074: @cindex defining words, user-defined
1.1       anton    6075: 
1.29      crook    6076: You can create a new defining word by wrapping defining-time code around
                   6077: an existing defining word and putting the sequence in a colon
                   6078: definition. For example, suppose that you have a word @code{stats} that
                   6079: gathers statistics about colon definitions given the @i{xt} of the
                   6080: definition, and you want every colon definition in your application to
                   6081: make a call to @code{stats}. You can define and use a new version of
                   6082: @code{:} like this:
                   6083: 
                   6084: @example
                   6085: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
                   6086:   ... ;  \ other code
                   6087: 
                   6088: : my: : lastxt postpone literal ['] stats compile, ;
                   6089: 
                   6090: my: foo + - ;
                   6091: @end example
                   6092: 
                   6093: When @code{foo} is defined using @code{my:} these steps occur:
                   6094: 
                   6095: @itemize @bullet
                   6096: @item
                   6097: @code{my:} is executed.
                   6098: @item
                   6099: The @code{:} within the definition (the one between @code{my:} and
                   6100: @code{lastxt}) is executed, and does just what it always does; it parses
                   6101: the input stream for a name, builds a dictionary header for the name
                   6102: @code{foo} and switches @code{state} from interpret to compile.
                   6103: @item
                   6104: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
                   6105: being defined -- @code{foo} -- onto the stack.
                   6106: @item
                   6107: The code that was produced by @code{postpone literal} is executed; this
                   6108: causes the value on the stack to be compiled as a literal in the code
                   6109: area of @code{foo}.
                   6110: @item
                   6111: The code @code{['] stats} compiles a literal into the definition of
                   6112: @code{my:}. When @code{compile,} is executed, that literal -- the
                   6113: execution token for @code{stats} -- is layed down in the code area of
                   6114: @code{foo} , following the literal@footnote{Strictly speaking, the
                   6115: mechanism that @code{compile,} uses to convert an @i{xt} into something
                   6116: in the code area is implementation-dependent. A threaded implementation
                   6117: might spit out the execution token directly whilst another
                   6118: implementation might spit out a native code sequence.}.
                   6119: @item
                   6120: At this point, the execution of @code{my:} is complete, and control
                   6121: returns to the text interpreter. The text interpreter is in compile
                   6122: state, so subsequent text @code{+ -} is compiled into the definition of
                   6123: @code{foo} and the @code{;} terminates the definition as always.
                   6124: @end itemize
                   6125: 
                   6126: You can use @code{see} to decompile a word that was defined using
                   6127: @code{my:} and see how it is different from a normal @code{:}
                   6128: definition. For example:
                   6129: 
                   6130: @example
                   6131: : bar + - ;  \ like foo but using : rather than my:
                   6132: see bar
                   6133: : bar
                   6134:   + - ;
                   6135: see foo
                   6136: : foo
                   6137:   107645672 stats + - ;
                   6138: 
                   6139: \ use ' stats . to show that 107645672 is the xt for stats
                   6140: @end example
                   6141: 
                   6142: You can use techniques like this to make new defining words in terms of
                   6143: @i{any} existing defining word.
1.1       anton    6144: 
                   6145: 
1.29      crook    6146: @cindex defining defining words
1.26      crook    6147: @cindex @code{CREATE} ... @code{DOES>}
                   6148: If you want the words defined with your defining words to behave
                   6149: differently from words defined with standard defining words, you can
                   6150: write your defining word like this:
1.1       anton    6151: 
                   6152: @example
1.26      crook    6153: : def-word ( "name" -- )
1.29      crook    6154:     CREATE @i{code1}
1.26      crook    6155: DOES> ( ... -- ... )
1.29      crook    6156:     @i{code2} ;
1.26      crook    6157: 
                   6158: def-word name
1.1       anton    6159: @end example
                   6160: 
1.29      crook    6161: @cindex child words
                   6162: This fragment defines a @dfn{defining word} @code{def-word} and then
                   6163: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
                   6164: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
                   6165: is not executed at this time. The word @code{name} is sometimes called a
                   6166: @dfn{child} of @code{def-word}.
                   6167: 
                   6168: When you execute @code{name}, the address of the body of @code{name} is
                   6169: put on the data stack and @i{code2} is executed (the address of the body
                   6170: of @code{name} is the address @code{HERE} returns immediately after the
                   6171: @code{CREATE}).
                   6172: 
                   6173: @cindex atavism in child words
1.33      anton    6174: You can use @code{def-word} to define a set of child words that behave
1.29      crook    6175: differently, though atavistically; they all have a common run-time
                   6176: behaviour determined by @i{code2}. Typically, the @i{code1} sequence
                   6177: builds a data area in the body of the child word. The structure of the
                   6178: data is common to all children of @code{def-word}, but the data values
                   6179: are specific -- and private -- to each child word. When a child word is
                   6180: executed, the address of its private data area is passed as a parameter
                   6181: on TOS to be used and manipulated@footnote{It is legitimate both to read
                   6182: and write to this data area.} by @i{code2}.
                   6183: 
                   6184: The two fragments of code that make up the defining words act (are
                   6185: executed) at two completely separate times:
1.1       anton    6186: 
1.29      crook    6187: @itemize @bullet
                   6188: @item
                   6189: At @i{define time}, the defining word executes @i{code1} to generate a
                   6190: child word
                   6191: @item
                   6192: At @i{child execution time}, when a child word is invoked, @i{code2}
                   6193: is executed, using parameters (data) that are private and specific to
                   6194: the child word.
                   6195: @end itemize
                   6196: 
1.44      crook    6197: Another way of understanding the behaviour of @code{def-word} and
                   6198: @code{name} is to say that, if you make the following definitions:
1.33      anton    6199: @example
                   6200: : def-word1 ( "name" -- )
                   6201:     CREATE @i{code1} ;
                   6202: 
                   6203: : action1 ( ... -- ... )
                   6204:     @i{code2} ;
                   6205: 
                   6206: def-word1 name1
                   6207: @end example
                   6208: 
1.44      crook    6209: @noindent
                   6210: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1       anton    6211: 
1.29      crook    6212: The classic example is that you can define @code{CONSTANT} in this way:
1.26      crook    6213: 
1.1       anton    6214: @example
1.29      crook    6215: : CONSTANT ( w "name" -- )
                   6216:     CREATE ,
1.26      crook    6217: DOES> ( -- w )
                   6218:     @@ ;
1.1       anton    6219: @end example
                   6220: 
1.29      crook    6221: @comment There is a beautiful description of how this works and what
                   6222: @comment it does in the Forthwrite 100th edition.. as well as an elegant
                   6223: @comment commentary on the Counting Fruits problem.
                   6224: 
                   6225: When you create a constant with @code{5 CONSTANT five}, a set of
                   6226: define-time actions take place; first a new word @code{five} is created,
                   6227: then the value 5 is laid down in the body of @code{five} with
1.44      crook    6228: @code{,}. When @code{five} is executed, the address of the body is put on
1.29      crook    6229: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
                   6230: no code of its own; it simply contains a data field and a pointer to the
                   6231: code that follows @code{DOES>} in its defining word. That makes words
                   6232: created in this way very compact.
                   6233: 
                   6234: The final example in this section is intended to remind you that space
                   6235: reserved in @code{CREATE}d words is @i{data} space and therefore can be
                   6236: both read and written by a Standard program@footnote{Exercise: use this
                   6237: example as a starting point for your own implementation of @code{Value}
                   6238: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
                   6239: @code{[']}.}:
                   6240: 
                   6241: @example
                   6242: : foo ( "name" -- )
                   6243:     CREATE -1 ,
                   6244: DOES> ( -- )
1.33      anton    6245:     @@ . ;
1.29      crook    6246: 
                   6247: foo first-word
                   6248: foo second-word
                   6249: 
                   6250: 123 ' first-word >BODY !
                   6251: @end example
                   6252: 
                   6253: If @code{first-word} had been a @code{CREATE}d word, we could simply
                   6254: have executed it to get the address of its data field. However, since it
                   6255: was defined to have @code{DOES>} actions, its execution semantics are to
                   6256: perform those @code{DOES>} actions. To get the address of its data field
                   6257: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
                   6258: translate the xt into the address of the data field.  When you execute
                   6259: @code{first-word}, it will display @code{123}. When you execute
                   6260: @code{second-word} it will display @code{-1}.
1.26      crook    6261: 
                   6262: @cindex stack effect of @code{DOES>}-parts
                   6263: @cindex @code{DOES>}-parts, stack effect
1.29      crook    6264: In the examples above the stack comment after the @code{DOES>} specifies
1.26      crook    6265: the stack effect of the defined words, not the stack effect of the
                   6266: following code (the following code expects the address of the body on
                   6267: the top of stack, which is not reflected in the stack comment). This is
                   6268: the convention that I use and recommend (it clashes a bit with using
                   6269: locals declarations for stack effect specification, though).
1.1       anton    6270: 
1.53    ! anton    6271: @menu
        !          6272: * CREATE..DOES> applications::  
        !          6273: * CREATE..DOES> details::       
        !          6274: * Advanced does> usage::        
        !          6275: @end menu
        !          6276: 
        !          6277: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26      crook    6278: @subsubsection Applications of @code{CREATE..DOES>}
                   6279: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1       anton    6280: 
1.26      crook    6281: You may wonder how to use this feature. Here are some usage patterns:
1.1       anton    6282: 
1.26      crook    6283: @cindex factoring similar colon definitions
                   6284: When you see a sequence of code occurring several times, and you can
                   6285: identify a meaning, you will factor it out as a colon definition. When
                   6286: you see similar colon definitions, you can factor them using
                   6287: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
                   6288: that look very similar:
1.1       anton    6289: @example
1.26      crook    6290: : ori, ( reg-target reg-source n -- )
                   6291:     0 asm-reg-reg-imm ;
                   6292: : andi, ( reg-target reg-source n -- )
                   6293:     1 asm-reg-reg-imm ;
1.1       anton    6294: @end example
                   6295: 
1.26      crook    6296: @noindent
                   6297: This could be factored with:
                   6298: @example
                   6299: : reg-reg-imm ( op-code -- )
                   6300:     CREATE ,
                   6301: DOES> ( reg-target reg-source n -- )
                   6302:     @@ asm-reg-reg-imm ;
                   6303: 
                   6304: 0 reg-reg-imm ori,
                   6305: 1 reg-reg-imm andi,
                   6306: @end example
1.1       anton    6307: 
1.26      crook    6308: @cindex currying
                   6309: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
                   6310: supply a part of the parameters for a word (known as @dfn{currying} in
                   6311: the functional language community). E.g., @code{+} needs two
                   6312: parameters. Creating versions of @code{+} with one parameter fixed can
                   6313: be done like this:
1.1       anton    6314: @example
1.26      crook    6315: : curry+ ( n1 -- )
                   6316:     CREATE ,
                   6317: DOES> ( n2 -- n1+n2 )
                   6318:     @@ + ;
                   6319: 
                   6320:  3 curry+ 3+
                   6321: -2 curry+ 2-
1.1       anton    6322: @end example
                   6323: 
1.53    ! anton    6324: @node CREATE..DOES> details, Advanced does> usage, CREATE..DOES> applications, User-defined Defining Words
1.26      crook    6325: @subsubsection The gory details of @code{CREATE..DOES>}
                   6326: @cindex @code{CREATE} ... @code{DOES>}, details
1.1       anton    6327: 
1.26      crook    6328: doc-does>
1.1       anton    6329: 
1.26      crook    6330: @cindex @code{DOES>} in a separate definition
                   6331: This means that you need not use @code{CREATE} and @code{DOES>} in the
                   6332: same definition; you can put the @code{DOES>}-part in a separate
1.29      crook    6333: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26      crook    6334: @example
                   6335: : does1 
                   6336: DOES> ( ... -- ... )
1.44      crook    6337:     ... ;
                   6338: 
                   6339: : does2
                   6340: DOES> ( ... -- ... )
                   6341:     ... ;
                   6342: 
                   6343: : def-word ( ... -- ... )
                   6344:     create ...
                   6345:     IF
                   6346:        does1
                   6347:     ELSE
                   6348:        does2
                   6349:     ENDIF ;
                   6350: @end example
                   6351: 
                   6352: In this example, the selection of whether to use @code{does1} or
                   6353: @code{does2} is made at compile-time; at the time that the child word is
                   6354: @code{CREATE}d.
                   6355: 
                   6356: @cindex @code{DOES>} in interpretation state
                   6357: In a standard program you can apply a @code{DOES>}-part only if the last
                   6358: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
                   6359: will override the behaviour of the last word defined in any case. In a
                   6360: standard program, you can use @code{DOES>} only in a colon
                   6361: definition. In Gforth, you can also use it in interpretation state, in a
                   6362: kind of one-shot mode; for example:
                   6363: @example
                   6364: CREATE name ( ... -- ... )
                   6365:   @i{initialization}
                   6366: DOES>
                   6367:   @i{code} ;
                   6368: @end example
                   6369: 
                   6370: @noindent
                   6371: is equivalent to the standard:
                   6372: @example
                   6373: :noname
                   6374: DOES>
                   6375:     @i{code} ;
                   6376: CREATE name EXECUTE ( ... -- ... )
                   6377:     @i{initialization}
                   6378: @end example
                   6379: 
1.53    ! anton    6380: doc->body
        !          6381: 
        !          6382: @node Advanced does> usage,  , CREATE..DOES> details, User-defined Defining Words
        !          6383: @subsubsection Advanced does> usage
1.44      crook    6384: 
                   6385: 
                   6386: 
                   6387: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
                   6388: @subsection Deferred words
                   6389: @cindex deferred words
                   6390: 
                   6391: The defining word @code{Defer} allows you to define a word by name
                   6392: without defining its behaviour; the definition of its behaviour is
                   6393: deferred. Here are two situation where this can be useful:
                   6394: 
                   6395: @itemize @bullet
                   6396: @item
                   6397: Where you want to allow the behaviour of a word to be altered later, and
                   6398: for all precompiled references to the word to change when its behaviour
                   6399: is changed.
                   6400: @item
                   6401: For mutual recursion; @xref{Calls and returns}.
                   6402: @end itemize
                   6403: 
                   6404: In the following example, @code{foo} always invokes the version of
                   6405: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
                   6406: always invokes the version that prints ``@code{Hello}''. There is no way
                   6407: of getting @code{foo} to use the later version without re-ordering the
                   6408: source code and recompiling it.
                   6409: 
                   6410: @example
                   6411: : greet ." Good morning" ;
                   6412: : foo ... greet ... ;
                   6413: : greet ." Hello" ;
                   6414: : bar ... greet ... ;
                   6415: @end example
                   6416: 
                   6417: This problem can be solved by defining @code{greet} as a @code{Defer}red
                   6418: word. The behaviour of a @code{Defer}red word can be defined and
                   6419: redefined at any time by using @code{IS} to associate the xt of a
                   6420: previously-defined word with it. The previous example becomes:
                   6421: 
                   6422: @example
                   6423: Defer greet
                   6424: : foo ... greet ... ;
                   6425: : bar ... greet ... ;
                   6426: : greet1 ." Good morning" ;
                   6427: : greet2 ." Hello" ;
                   6428: ' greet2 <IS> greet  \ make greet behave like greet2
                   6429: @end example
                   6430: 
                   6431: A deferred word can be used to improve the statistics-gathering example
                   6432: from @ref{User-defined Defining Words}; rather than edit the
                   6433: application's source code to change every @code{:} to a @code{my:}, do
                   6434: this:
                   6435: 
                   6436: @example
                   6437: : real: : ;     \ retain access to the original
                   6438: defer :         \ redefine as a deferred word
                   6439: ' my: IS :      \ use special version of :
                   6440: \
                   6441: \ load application here
                   6442: \
                   6443: ' real: IS :    \ go back to the original
                   6444: @end example
                   6445: 
                   6446: 
                   6447: One thing to note is that @code{<IS>} consumes its name when it is
                   6448: executed.  If you want to specify the name at compile time, use
                   6449: @code{[IS]}:
                   6450: 
                   6451: @example
                   6452: : set-greet ( xt -- )
                   6453:   [IS] greet ;
                   6454: 
                   6455: ' greet1 set-greet
                   6456: @end example
                   6457: 
                   6458: A deferred word can only inherit default semantics from the xt (because
1.49      anton    6459: that is all that an xt can represent -- for more discussion of this
                   6460: @pxref{Tokens for Words}). However, the semantics of the deferred word
1.44      crook    6461: itself can be modified at the time that it is defined. For example:
                   6462: 
                   6463: @example
                   6464: : bar .... ; compile-only
                   6465: Defer fred immediate
                   6466: Defer jim
                   6467: 
                   6468: ' bar <IS> jim  \ jim has default semantics
                   6469: ' bar <IS> fred \ fred is immediate
                   6470: @end example
                   6471: 
                   6472: doc-defer
                   6473: doc-<is>
                   6474: doc-[is]
                   6475: doc-is
                   6476: @comment TODO document these: what's defers [is]
                   6477: doc-what's
                   6478: doc-defers
                   6479: 
                   6480: @c Use @code{words-deferred} to see a list of deferred words.
                   6481: 
                   6482: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
                   6483: are provided in @file{compat/defer.fs}.
                   6484: 
                   6485: 
                   6486: @node Aliases, Supplying names, Deferred words, Defining Words
                   6487: @subsection Aliases
                   6488: @cindex aliases
1.1       anton    6489: 
1.44      crook    6490: The defining word @code{Alias} allows you to define a word by name that
                   6491: has the same behaviour as some other word. Here are two situation where
                   6492: this can be useful:
1.1       anton    6493: 
1.44      crook    6494: @itemize @bullet
                   6495: @item
                   6496: When you want access to a word's definition from a different word list
                   6497: (for an example of this, see the definition of the @code{Root} word list
                   6498: in the Gforth source).
                   6499: @item
                   6500: When you want to create a synonym; a definition that can be known by
                   6501: either of two names (for example, @code{THEN} and @code{ENDIF} are
                   6502: aliases).
                   6503: @end itemize
1.1       anton    6504: 
1.44      crook    6505: The word whose behaviour the alias is to inherit is represented by an
                   6506: xt. Therefore, the alias only inherits default semantics from its
                   6507: ancestor. The semantics of the alias itself can be modified at the time
                   6508: that it is defined. For example:
1.1       anton    6509: 
                   6510: @example
1.44      crook    6511: : foo ... ; immediate
                   6512: 
                   6513: ' foo Alias bar \ bar is not an immediate word
                   6514: ' foo Alias fooby immediate \ fooby is an immediate word
1.1       anton    6515: @end example
                   6516: 
1.44      crook    6517: Words that are aliases have the same xt, different headers in the
                   6518: dictionary, and consequently different name tokens (@pxref{Tokens for
                   6519: Words}) and possibly different immediate flags.  An alias can only have
                   6520: default or immediate compilation semantics; you can define aliases for
                   6521: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1       anton    6522: 
1.44      crook    6523: doc-alias
1.26      crook    6524: 
1.1       anton    6525: 
1.52      anton    6526: @node Supplying names,  , Aliases, Defining Words
1.29      crook    6527: @subsection Supplying the name of a defined word
1.26      crook    6528: @cindex names for defined words
1.44      crook    6529: @cindex defining words, name given in a string
1.1       anton    6530: 
1.29      crook    6531: By default, a defining word takes the name for the defined word from the
1.26      crook    6532: input stream. Sometimes you want to supply the name from a string. You
                   6533: can do this with:
1.1       anton    6534: 
1.26      crook    6535: doc-nextname
1.1       anton    6536: 
1.26      crook    6537: For example:
1.1       anton    6538: 
1.26      crook    6539: @example
                   6540: s" foo" nextname create
                   6541: @end example
1.44      crook    6542: 
1.26      crook    6543: @noindent
                   6544: is equivalent to:
1.44      crook    6545: 
1.26      crook    6546: @example
                   6547: create foo
                   6548: @end example
1.1       anton    6549: 
1.29      crook    6550: @noindent
1.44      crook    6551: @code{nextname} works with any defining word, not just @code{:}.
1.1       anton    6552: 
                   6553: 
1.47      crook    6554: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
                   6555: @section Interpretation and Compilation Semantics
1.26      crook    6556: @cindex semantics, interpretation and compilation
1.1       anton    6557: 
1.26      crook    6558: @cindex interpretation semantics
                   6559: The @dfn{interpretation semantics} of a word are what the text
                   6560: interpreter does when it encounters the word in interpret state. It also
                   6561: appears in some other contexts, e.g., the execution token returned by
1.29      crook    6562: @code{' @i{word}} identifies the interpretation semantics of
                   6563: @i{word} (in other words, @code{' @i{word} execute} is equivalent to
                   6564: interpret-state text interpretation of @code{@i{word}}).
1.1       anton    6565: 
1.26      crook    6566: @cindex compilation semantics
                   6567: The @dfn{compilation semantics} of a word are what the text interpreter
                   6568: does when it encounters the word in compile state. It also appears in
1.29      crook    6569: other contexts, e.g, @code{POSTPONE @i{word}} compiles@footnote{In
1.26      crook    6570: standard terminology, ``appends to the current definition''.} the
1.29      crook    6571: compilation semantics of @i{word}.
1.1       anton    6572: 
1.26      crook    6573: @cindex execution semantics
                   6574: The standard also talks about @dfn{execution semantics}. They are used
                   6575: only for defining the interpretation and compilation semantics of many
                   6576: words. By default, the interpretation semantics of a word are to
                   6577: @code{execute} its execution semantics, and the compilation semantics of
                   6578: a word are to @code{compile,} its execution semantics.@footnote{In
                   6579: standard terminology: The default interpretation semantics are its
                   6580: execution semantics; the default compilation semantics are to append its
                   6581: execution semantics to the execution semantics of the current
                   6582: definition.}
                   6583: 
                   6584: @comment TODO expand, make it co-operate with new sections on text interpreter.
                   6585: 
                   6586: @cindex immediate words
                   6587: @cindex compile-only words
                   6588: You can change the semantics of the most-recently defined word:
                   6589: 
1.44      crook    6590: 
1.26      crook    6591: doc-immediate
                   6592: doc-compile-only
                   6593: doc-restrict
                   6594: 
1.44      crook    6595: 
1.26      crook    6596: Note that ticking (@code{'}) a compile-only word gives an error
                   6597: (``Interpreting a compile-only word'').
1.1       anton    6598: 
1.47      crook    6599: @menu
                   6600: * Combined words::
                   6601: @end menu
1.44      crook    6602: 
1.48      anton    6603: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44      crook    6604: @subsection Combined Words
                   6605: @cindex combined words
                   6606: 
                   6607: Gforth allows you to define @dfn{combined words} -- words that have an
                   6608: arbitrary combination of interpretation and compilation semantics.
                   6609: 
1.1       anton    6610: 
1.26      crook    6611: doc-interpret/compile:
1.1       anton    6612: 
1.44      crook    6613: 
1.26      crook    6614: This feature was introduced for implementing @code{TO} and @code{S"}. I
                   6615: recommend that you do not define such words, as cute as they may be:
                   6616: they make it hard to get at both parts of the word in some contexts.
                   6617: E.g., assume you want to get an execution token for the compilation
                   6618: part. Instead, define two words, one that embodies the interpretation
                   6619: part, and one that embodies the compilation part.  Once you have done
                   6620: that, you can define a combined word with @code{interpret/compile:} for
                   6621: the convenience of your users.
1.1       anton    6622: 
1.26      crook    6623: You might try to use this feature to provide an optimizing
                   6624: implementation of the default compilation semantics of a word. For
                   6625: example, by defining:
1.1       anton    6626: @example
1.26      crook    6627: :noname
                   6628:    foo bar ;
                   6629: :noname
                   6630:    POSTPONE foo POSTPONE bar ;
1.29      crook    6631: interpret/compile: opti-foobar
1.1       anton    6632: @end example
1.26      crook    6633: 
1.23      crook    6634: @noindent
1.26      crook    6635: as an optimizing version of:
                   6636: 
1.1       anton    6637: @example
1.26      crook    6638: : foobar
                   6639:     foo bar ;
1.1       anton    6640: @end example
                   6641: 
1.26      crook    6642: Unfortunately, this does not work correctly with @code{[compile]},
                   6643: because @code{[compile]} assumes that the compilation semantics of all
                   6644: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29      crook    6645: opti-foobar} would compile compilation semantics, whereas
                   6646: @code{[compile] foobar} would compile interpretation semantics.
1.1       anton    6647: 
1.26      crook    6648: @cindex state-smart words (are a bad idea)
1.29      crook    6649: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26      crook    6650: by @code{interpret/compile:} (words are state-smart if they check
                   6651: @code{STATE} during execution). E.g., they would try to code
                   6652: @code{foobar} like this:
1.1       anton    6653: 
1.26      crook    6654: @example
                   6655: : foobar
                   6656:   STATE @@
                   6657:   IF ( compilation state )
                   6658:     POSTPONE foo POSTPONE bar
                   6659:   ELSE
                   6660:     foo bar
                   6661:   ENDIF ; immediate
                   6662: @end example
1.1       anton    6663: 
1.26      crook    6664: Although this works if @code{foobar} is only processed by the text
                   6665: interpreter, it does not work in other contexts (like @code{'} or
                   6666: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
                   6667: for a state-smart word, not for the interpretation semantics of the
                   6668: original @code{foobar}; when you execute this execution token (directly
                   6669: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
                   6670: state, the result will not be what you expected (i.e., it will not
                   6671: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
                   6672: write them@footnote{For a more detailed discussion of this topic, see
                   6673: @cite{@code{State}-smartness -- Why it is Evil and How to Exorcise it} by Anton
                   6674: Ertl; presented at EuroForth '98 and available from
1.47      crook    6675: @*@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz}}!
1.1       anton    6676: 
1.26      crook    6677: @cindex defining words with arbitrary semantics combinations
                   6678: It is also possible to write defining words that define words with
                   6679: arbitrary combinations of interpretation and compilation semantics. In
                   6680: general, they look like this:
1.1       anton    6681: 
1.26      crook    6682: @example
                   6683: : def-word
                   6684:     create-interpret/compile
1.29      crook    6685:     @i{code1}
1.26      crook    6686: interpretation>
1.29      crook    6687:     @i{code2}
1.26      crook    6688: <interpretation
                   6689: compilation>
1.29      crook    6690:     @i{code3}
1.26      crook    6691: <compilation ;
                   6692: @end example
1.1       anton    6693: 
1.29      crook    6694: For a @i{word} defined with @code{def-word}, the interpretation
                   6695: semantics are to push the address of the body of @i{word} and perform
                   6696: @i{code2}, and the compilation semantics are to push the address of
                   6697: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26      crook    6698: can also be defined like this (except that the defined constants don't
                   6699: behave correctly when @code{[compile]}d):
1.1       anton    6700: 
1.26      crook    6701: @example
                   6702: : constant ( n "name" -- )
                   6703:     create-interpret/compile
                   6704:     ,
                   6705: interpretation> ( -- n )
                   6706:     @@
                   6707: <interpretation
                   6708: compilation> ( compilation. -- ; run-time. -- n )
                   6709:     @@ postpone literal
                   6710: <compilation ;
                   6711: @end example
1.1       anton    6712: 
1.44      crook    6713: 
1.26      crook    6714: doc-create-interpret/compile
                   6715: doc-interpretation>
                   6716: doc-<interpretation
                   6717: doc-compilation>
                   6718: doc-<compilation
1.1       anton    6719: 
1.44      crook    6720: 
1.29      crook    6721: Words defined with @code{interpret/compile:} and
1.26      crook    6722: @code{create-interpret/compile} have an extended header structure that
                   6723: differs from other words; however, unless you try to access them with
                   6724: plain address arithmetic, you should not notice this. Words for
                   6725: accessing the header structure usually know how to deal with this; e.g.,
1.29      crook    6726: @code{'} @i{word} @code{>body} also gives you the body of a word created
                   6727: with @code{create-interpret/compile}.
1.1       anton    6728: 
1.44      crook    6729: 
1.27      crook    6730: doc-postpone
1.44      crook    6731: 
1.29      crook    6732: @comment TODO -- expand glossary text for POSTPONE
1.27      crook    6733: 
1.47      crook    6734: 
                   6735: @c -------------------------------------------------------------
                   6736: @node Tokens for Words, The Text Interpreter, Interpretation and Compilation Semantics, Words
                   6737: @section Tokens for Words
                   6738: @cindex tokens for words
                   6739: 
                   6740: This section describes the creation and use of tokens that represent
                   6741: words.
                   6742: 
                   6743: Named words have information stored in their header space entries to
                   6744: indicate any non-default semantics (@pxref{Interpretation and
                   6745: Compilation Semantics}). The semantics can be modified, using
                   6746: @code{immediate} and/or @code{compile-only}, at the time that the words
                   6747: are defined. Unnamed words have (by definition) no header space
                   6748: entry, and therefore must have default semantics.
                   6749: 
                   6750: Named words have interpretation and compilation semantics. Unnamed words
                   6751: just have execution semantics.
                   6752: 
                   6753: @cindex xt
                   6754: @cindex execution token
                   6755: The execution semantics of an unnamed word are represented by an
                   6756: @dfn{execution token} (@i{xt}). As explained in @ref{Supplying names},
                   6757: the execution token of the last word defined can be produced with
                   6758: @code{lastxt}.
                   6759: 
                   6760: The interpretation semantics of a named word are also represented by an
                   6761: execution token. You can produce the execution token using @code{'} or
                   6762: @code{[']}. A simple example shows the difference between the two:
                   6763: 
                   6764: @example
                   6765: : greet ( -- )   ." Hello" ;
                   6766: : foo ( -- xt )  ['] greet execute ; \ ['] parses greet at compile-time
                   6767: : bar ( -- )     ' execute ; \  '  parses at run-time
                   6768: 
                   6769: \ the next four lines all do the same thing
                   6770: foo
                   6771: bar greet
                   6772: greet
                   6773: ' greet EXECUTE
                   6774: @end example
                   6775: 
                   6776: An execution token occupies one cell.
                   6777: @cindex code field address
                   6778: @cindex CFA
                   6779: In Gforth, the abstract data type @i{execution token} is implemented
                   6780: as a code field address (CFA).
                   6781: @comment TODO note that the standard does not say what it represents..
                   6782: @comment and you cannot necessarily compile it in all Forths (eg native
                   6783: @comment compilers?).
                   6784: 
                   6785: For literals, use @code{'} in interpreted code and @code{[']} in
                   6786: compiled code. Gforth's @code{'} and @code{[']} behave somewhat
                   6787: unusually by complaining about compile-only words. To get the execution
                   6788: token for a compile-only word @i{name}, use @code{COMP' @i{name} DROP}
                   6789: or @code{[COMP'] @i{name} DROP}.
                   6790: 
                   6791: @cindex compilation token
                   6792: The compilation semantics of a named word are represented by a
                   6793: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
                   6794: @i{xt} is an execution token. The compilation semantics represented by
                   6795: the compilation token can be performed with @code{execute}, which
                   6796: consumes the whole compilation token, with an additional stack effect
                   6797: determined by the represented compilation semantics.
                   6798: 
                   6799: At present, the @i{w} part of a compilation token is an execution token,
                   6800: and the @i{xt} part represents either @code{execute} or
                   6801: @code{compile,}@footnote{Depending upon the compilation semantics of the
                   6802: word. If the word has default compilation semantics, the @i{xt} will
                   6803: represent @code{compile,}. Otherwise (e.g., for immediate words), the
                   6804: @i{xt} will represent @code{execute}.}. However, don't rely on that
                   6805: knowledge, unless necessary; future versions of Gforth may introduce
                   6806: unusual compilation tokens (e.g., a compilation token that represents
                   6807: the compilation semantics of a literal).
                   6808: 
                   6809: You can compile the compilation semantics with @code{postpone,}. I.e.,
                   6810: @code{COMP' @i{word} postpone,} is equivalent to @code{postpone
                   6811: @i{word}}.
                   6812: 
                   6813: @cindex name token
                   6814: @cindex name field address
                   6815: @cindex NFA
                   6816: Named words are also represented by the @dfn{name token}, (@i{nt}). In
                   6817: Gforth, the abstract data type @emph{name token} is implemented as a
                   6818: name field address (NFA).
                   6819: 
                   6820: 
                   6821: doc-execute
                   6822: doc-perform
                   6823: doc-compile,
                   6824: doc-[']
                   6825: doc-'
                   6826: doc-[comp']
                   6827: doc-comp'
                   6828: doc-postpone,
                   6829: 
                   6830: doc-find-name
                   6831: doc-name>int
                   6832: doc-name?int
                   6833: doc-name>comp
                   6834: doc-name>string
                   6835: 
                   6836: 
1.26      crook    6837: @c ----------------------------------------------------------
1.47      crook    6838: @node The Text Interpreter, Word Lists, Tokens for Words, Words
1.26      crook    6839: @section  The Text Interpreter
                   6840: @cindex interpreter - outer
                   6841: @cindex text interpreter
                   6842: @cindex outer interpreter
1.1       anton    6843: 
1.34      anton    6844: @c Should we really describe all these ugly details?  IMO the text
                   6845: @c interpreter should be much cleaner, but that may not be possible within
                   6846: @c ANS Forth. - anton
1.44      crook    6847: @c nac-> I wanted to explain how it works to show how you can exploit
                   6848: @c it in your own programs. When I was writing a cross-compiler, figuring out
                   6849: @c some of these gory details was very helpful to me. None of the textbooks
                   6850: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
                   6851: @c seems to positively avoid going into too much detail for some of
                   6852: @c the internals.
1.34      anton    6853: 
1.29      crook    6854: The text interpreter@footnote{This is an expanded version of the
                   6855: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34      anton    6856: that processes input from the current input device. It is also called
                   6857: the outer interpreter, in contrast to the inner interpreter
                   6858: (@pxref{Engine}) which executes the compiled Forth code on interpretive
                   6859: implementations.
1.27      crook    6860: 
1.29      crook    6861: @cindex interpret state
                   6862: @cindex compile state
                   6863: The text interpreter operates in one of two states: @dfn{interpret
                   6864: state} and @dfn{compile state}. The current state is defined by the
                   6865: aptly-named variable, @code{state}.
                   6866: 
                   6867: This section starts by describing how the text interpreter behaves when
                   6868: it is in interpret state, processing input from the user input device --
                   6869: the keyboard. This is the mode that a Forth system is in after it starts
                   6870: up.
                   6871: 
                   6872: @cindex input buffer
                   6873: @cindex terminal input buffer
                   6874: The text interpreter works from an area of memory called the @dfn{input
                   6875: buffer}@footnote{When the text interpreter is processing input from the
                   6876: keyboard, this area of memory is called the @dfn{terminal input buffer}
                   6877: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
                   6878: @code{#TIB}.}, which stores your keyboard input when you press the
1.30      anton    6879: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29      crook    6880: leading spaces (called @dfn{delimiters}) then parses a string (a
                   6881: sequence of non-space characters) until it reaches either a space
                   6882: character or the end of the buffer. Having parsed a string, it makes two
                   6883: attempts to process it:
1.27      crook    6884: 
1.29      crook    6885: @cindex dictionary
1.27      crook    6886: @itemize @bullet
                   6887: @item
1.29      crook    6888: It looks for the string in a @dfn{dictionary} of definitions. If the
                   6889: string is found, the string names a @dfn{definition} (also known as a
                   6890: @dfn{word}) and the dictionary search returns information that allows
                   6891: the text interpreter to perform the word's @dfn{interpretation
                   6892: semantics}. In most cases, this simply means that the word will be
                   6893: executed.
1.27      crook    6894: @item
                   6895: If the string is not found in the dictionary, the text interpreter
1.29      crook    6896: attempts to treat it as a number, using the rules described in
                   6897: @ref{Number Conversion}. If the string represents a legal number in the
                   6898: current radix, the number is pushed onto a parameter stack (the data
                   6899: stack for integers, the floating-point stack for floating-point
                   6900: numbers).
                   6901: @end itemize
                   6902: 
                   6903: If both attempts fail, or if the word is found in the dictionary but has
                   6904: no interpretation semantics@footnote{This happens if the word was
                   6905: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
                   6906: remainder of the input buffer, issues an error message and waits for
                   6907: more input. If one of the attempts succeeds, the text interpreter
                   6908: repeats the parsing process until the whole of the input buffer has been
                   6909: processed, at which point it prints the status message ``@code{ ok}''
                   6910: and waits for more input.
                   6911: 
                   6912: @cindex parse area
                   6913: The text interpreter keeps track of its position in the input buffer by
                   6914: updating a variable called @code{>IN} (pronounced ``to-in''). The value
                   6915: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
                   6916: of the input buffer. The region from offset @code{>IN @@} to the end of
                   6917: the input buffer is called the @dfn{parse area}@footnote{In other words,
                   6918: the text interpreter processes the contents of the input buffer by
                   6919: parsing strings from the parse area until the parse area is empty.}.
                   6920: This example shows how @code{>IN} changes as the text interpreter parses
                   6921: the input buffer:
                   6922: 
                   6923: @example
                   6924: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
                   6925:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
                   6926: 
                   6927: 1 2 3 remaining + remaining . 
                   6928: 
                   6929: : foo 1 2 3 remaining SWAP remaining ;
                   6930: @end example
                   6931: 
                   6932: @noindent
                   6933: The result is:
                   6934: 
                   6935: @example
                   6936: ->+ remaining .<-
                   6937: ->.<-5  ok
                   6938: 
                   6939: ->SWAP remaining ;-<
                   6940: ->;<-  ok
                   6941: @end example
                   6942: 
                   6943: @cindex parsing words
                   6944: The value of @code{>IN} can also be modified by a word in the input
                   6945: buffer that is executed by the text interpreter.  This means that a word
                   6946: can ``trick'' the text interpreter into either skipping a section of the
                   6947: input buffer@footnote{This is how parsing words work.} or into parsing a
                   6948: section twice. For example:
1.27      crook    6949: 
1.29      crook    6950: @example
                   6951: : lat ." <<lat>>" ;
                   6952: : flat ." <<flat>>" >IN DUP @@ 3 - SWAP ! ;
                   6953: @end example
                   6954: 
                   6955: @noindent
                   6956: When @code{flat} is executed, this output is produced@footnote{Exercise
                   6957: for the reader: what would happen if the @code{3} were replaced with
                   6958: @code{4}?}:
                   6959: 
                   6960: @example
                   6961: <<flat>><<lat>>
                   6962: @end example
                   6963: 
                   6964: @noindent
                   6965: Two important notes about the behaviour of the text interpreter:
1.27      crook    6966: 
                   6967: @itemize @bullet
                   6968: @item
                   6969: It processes each input string to completion before parsing additional
1.29      crook    6970: characters from the input buffer.
                   6971: @item
                   6972: It treats the input buffer as a read-only region (and so must your code).
                   6973: @end itemize
                   6974: 
                   6975: @noindent
                   6976: When the text interpreter is in compile state, its behaviour changes in
                   6977: these ways:
                   6978: 
                   6979: @itemize @bullet
                   6980: @item
                   6981: If a parsed string is found in the dictionary, the text interpreter will
                   6982: perform the word's @dfn{compilation semantics}. In most cases, this
                   6983: simply means that the execution semantics of the word will be appended
                   6984: to the current definition.
1.27      crook    6985: @item
1.29      crook    6986: When a number is encountered, it is compiled into the current definition
                   6987: (as a literal) rather than being pushed onto a parameter stack.
                   6988: @item
                   6989: If an error occurs, @code{state} is modified to put the text interpreter
                   6990: back into interpret state.
                   6991: @item
                   6992: Each time a line is entered from the keyboard, Gforth prints
                   6993: ``@code{ compiled}'' rather than `` @code{ok}''.
                   6994: @end itemize
                   6995: 
                   6996: @cindex text interpreter - input sources
                   6997: When the text interpreter is using an input device other than the
                   6998: keyboard, its behaviour changes in these ways:
                   6999: 
                   7000: @itemize @bullet
                   7001: @item
                   7002: When the parse area is empty, the text interpreter attempts to refill
                   7003: the input buffer from the input source. When the input source is
                   7004: exhausted, the input source is set back to the user input device.
                   7005: @item
                   7006: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
                   7007: time the parse area is emptied.
                   7008: @item
                   7009: If an error occurs, the input source is set back to the user input
                   7010: device.
1.27      crook    7011: @end itemize
1.21      crook    7012: 
1.49      anton    7013: You can read about this in more detail in @ref{Input Sources}.
1.44      crook    7014: 
1.26      crook    7015: doc->in
1.27      crook    7016: doc-source
                   7017: 
1.26      crook    7018: doc-tib
                   7019: doc-#tib
1.1       anton    7020: 
1.44      crook    7021: 
1.26      crook    7022: @menu
1.29      crook    7023: * Input Sources::
1.26      crook    7024: * Number Conversion::
                   7025: * Interpret/Compile states::
                   7026: * Literals::
                   7027: * Interpreter Directives::
                   7028: @end menu
1.1       anton    7029: 
1.29      crook    7030: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
                   7031: @subsection Input Sources
                   7032: @cindex input sources
                   7033: @cindex text interpreter - input sources
                   7034: 
1.44      crook    7035: By default, the text interpreter processes input from the user input
1.29      crook    7036: device (the keyboard) when Forth starts up. The text interpreter can
                   7037: process input from any of these sources:
                   7038: 
                   7039: @itemize @bullet
                   7040: @item
                   7041: The user input device -- the keyboard.
                   7042: @item
                   7043: A file, using the words described in @ref{Forth source files}.
                   7044: @item
                   7045: A block, using the words described in @ref{Blocks}.
                   7046: @item
                   7047: A text string, using @code{evaluate}.
                   7048: @end itemize
                   7049: 
                   7050: A program can identify the current input device from the values of
                   7051: @code{source-id} and @code{blk}.
                   7052: 
1.44      crook    7053: 
1.29      crook    7054: doc-source-id
                   7055: doc-blk
                   7056: 
                   7057: doc-save-input
                   7058: doc-restore-input
                   7059: 
                   7060: doc-evaluate
1.1       anton    7061: 
1.29      crook    7062: 
1.44      crook    7063: 
1.29      crook    7064: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26      crook    7065: @subsection Number Conversion
                   7066: @cindex number conversion
                   7067: @cindex double-cell numbers, input format
                   7068: @cindex input format for double-cell numbers
                   7069: @cindex single-cell numbers, input format
                   7070: @cindex input format for single-cell numbers
                   7071: @cindex floating-point numbers, input format
                   7072: @cindex input format for floating-point numbers
1.1       anton    7073: 
1.29      crook    7074: This section describes the rules that the text interpreter uses when it
                   7075: tries to convert a string into a number.
1.1       anton    7076: 
1.26      crook    7077: Let <digit> represent any character that is a legal digit in the current
1.29      crook    7078: number base@footnote{For example, 0-9 when the number base is decimal or
                   7079: 0-9, A-F when the number base is hexadecimal.}.
1.1       anton    7080: 
1.26      crook    7081: Let <decimal digit> represent any character in the range 0-9.
1.1       anton    7082: 
1.29      crook    7083: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
                   7084: in the braces (@i{a} or @i{b} or neither).
1.1       anton    7085: 
1.26      crook    7086: Let * represent any number of instances of the previous character
                   7087: (including none).
1.1       anton    7088: 
1.26      crook    7089: Let any other character represent itself.
1.1       anton    7090: 
1.29      crook    7091: @noindent
1.26      crook    7092: Now, the conversion rules are:
1.21      crook    7093: 
1.26      crook    7094: @itemize @bullet
                   7095: @item
                   7096: A string of the form <digit><digit>* is treated as a single-precision
1.29      crook    7097: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26      crook    7098: @item
                   7099: A string of the form -<digit><digit>* is treated as a single-precision
1.29      crook    7100: (cell-sized) negative integer, and is represented using 2's-complement
1.26      crook    7101: arithmetic. Examples are -45 -5681 -0
                   7102: @item
                   7103: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29      crook    7104: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
                   7105: (all three of these represent the same number).
1.26      crook    7106: @item
                   7107: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29      crook    7108: double-precision (double-cell-sized) negative integer, and is
1.26      crook    7109: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29      crook    7110: -34.65 (all three of these represent the same number).
1.26      crook    7111: @item
1.29      crook    7112: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
                   7113: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35      anton    7114: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29      crook    7115: number) +12.E-4
1.26      crook    7116: @end itemize
1.1       anton    7117: 
1.26      crook    7118: By default, the number base used for integer number conversion is given
1.35      anton    7119: by the contents of the variable @code{base}.  Note that a lot of
                   7120: confusion can result from unexpected values of @code{base}.  If you
                   7121: change @code{base} anywhere, make sure to save the old value and restore
                   7122: it afterwards.  In general I recommend keeping @code{base} decimal, and
                   7123: using the prefixes described below for the popular non-decimal bases.
1.1       anton    7124: 
1.29      crook    7125: doc-dpl
1.26      crook    7126: doc-base
                   7127: doc-hex
                   7128: doc-decimal
1.1       anton    7129: 
1.44      crook    7130: 
1.26      crook    7131: @cindex '-prefix for character strings
                   7132: @cindex &-prefix for decimal numbers
                   7133: @cindex %-prefix for binary numbers
                   7134: @cindex $-prefix for hexadecimal numbers
1.35      anton    7135: Gforth allows you to override the value of @code{base} by using a
1.29      crook    7136: prefix@footnote{Some Forth implementations provide a similar scheme by
                   7137: implementing @code{$} etc. as parsing words that process the subsequent
                   7138: number in the input stream and push it onto the stack. For example, see
                   7139: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
                   7140: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
                   7141: is required between the prefix and the number.} before the first digit
                   7142: of an (integer) number. Four prefixes are supported:
1.1       anton    7143: 
1.26      crook    7144: @itemize @bullet
                   7145: @item
1.35      anton    7146: @code{&} -- decimal
1.26      crook    7147: @item
1.35      anton    7148: @code{%} -- binary
1.26      crook    7149: @item
1.35      anton    7150: @code{$} -- hexadecimal
1.26      crook    7151: @item
1.35      anton    7152: @code{'} -- base @code{max-char+1}
1.26      crook    7153: @end itemize
1.1       anton    7154: 
1.26      crook    7155: Here are some examples, with the equivalent decimal number shown after
                   7156: in braces:
1.1       anton    7157: 
1.26      crook    7158: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
                   7159: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
                   7160: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
                   7161: &905 (905), $abc (2478), $ABC (2478).
1.1       anton    7162: 
1.26      crook    7163: @cindex number conversion - traps for the unwary
1.29      crook    7164: @noindent
1.26      crook    7165: Number conversion has a number of traps for the unwary:
1.1       anton    7166: 
1.26      crook    7167: @itemize @bullet
                   7168: @item
                   7169: You cannot determine the current number base using the code sequence
1.35      anton    7170: @code{base @@ .} -- the number base is always 10 in the current number
                   7171: base. Instead, use something like @code{base @@ dec.}
1.26      crook    7172: @item
                   7173: If the number base is set to a value greater than 14 (for example,
                   7174: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
                   7175: it to be intepreted as either a single-precision integer or a
                   7176: floating-point number (Gforth treats it as an integer). The ambiguity
                   7177: can be resolved by explicitly stating the sign of the mantissa and/or
                   7178: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
                   7179: ambiguity arises; either representation will be treated as a
                   7180: floating-point number.
                   7181: @item
1.29      crook    7182: There is a word @code{bin} but it does @i{not} set the number base!
1.26      crook    7183: It is used to specify file types.
                   7184: @item
                   7185: ANS Forth requires the @code{.} of a double-precision number to
                   7186: be the final character in the string. Allowing the @code{.} to be
                   7187: anywhere after the first digit is a Gforth extension.
                   7188: @item
                   7189: The number conversion process does not check for overflow.
                   7190: @item
                   7191: In Gforth, number conversion to floating-point numbers always use base
1.35      anton    7192: 10, irrespective of the value of @code{base}. In ANS Forth,
1.26      crook    7193: conversion to floating-point numbers whilst the value of
1.35      anton    7194: @code{base} is not 10 is an ambiguous condition.
1.26      crook    7195: @end itemize
1.1       anton    7196: 
1.49      anton    7197: You can read numbers into your programs with the words described in
                   7198: @ref{Input}.
1.1       anton    7199: 
1.26      crook    7200: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
                   7201: @subsection Interpret/Compile states
                   7202: @cindex Interpret/Compile states
1.1       anton    7203: 
1.29      crook    7204: A standard program is not permitted to change @code{state}
                   7205: explicitly. However, it can change @code{state} implicitly, using the
                   7206: words @code{[} and @code{]}. When @code{[} is executed it switches
                   7207: @code{state} to interpret state, and therefore the text interpreter
                   7208: starts interpreting. When @code{]} is executed it switches @code{state}
                   7209: to compile state and therefore the text interpreter starts
1.44      crook    7210: compiling. The most common usage for these words is for switching into
                   7211: interpret state and back from within a colon definition; this technique
1.49      anton    7212: can be used to compile a literal (for an example, @pxref{Literals}) or
                   7213: for conditional compilation (for an example, @pxref{Interpreter
                   7214: Directives}).
1.44      crook    7215: 
1.35      anton    7216: 
                   7217: @c This is a bad example: It's non-standard, and it's not necessary.
                   7218: @c However, I can't think of a good example for switching into compile
                   7219: @c state when there is no current word (@code{state}-smart words are not a
                   7220: @c good reason).  So maybe we should use an example for switching into
                   7221: @c interpret @code{state} in a colon def. - anton
1.44      crook    7222: @c nac-> I agree. I started out by putting in the example, then realised
                   7223: @c that it was non-ANS, so wrote more words around it. I hope this
                   7224: @c re-written version is acceptable to you. I do want to keep the example
                   7225: @c as it is helpful for showing what is and what is not portable, particularly
                   7226: @c where it outlaws a style in common use.
                   7227: 
1.35      anton    7228: 
1.44      crook    7229: @code{[} and @code{]} also give you the ability to switch into compile
                   7230: state and back, but we cannot think of any useful Standard application
                   7231: for this ability. Pre-ANS Forth textbooks have examples like this:
1.29      crook    7232: 
                   7233: @example
                   7234: : AA ." this is A" ;
                   7235: : BB ." this is B" ;
                   7236: : CC ." this is C" ;
                   7237: 
1.44      crook    7238: create table ] aa bb cc [
                   7239: 
1.29      crook    7240: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
                   7241:   cells table + @ execute ;
                   7242: @end example
                   7243: 
1.44      crook    7244: This example builds a jump table; @code{0 go} will display ``@code{this
                   7245: is A}''. Using @code{[} and @code{]} in this example is equivalent to
                   7246: defining @code{table} like this:
1.29      crook    7247: 
                   7248: @example
1.44      crook    7249: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
1.29      crook    7250: @end example
                   7251: 
1.44      crook    7252: The problem with this code is that the definition of @code{table} is not
                   7253: portable -- it @i{compile}s execution tokens into code space. Whilst it
                   7254: @i{may} work on systems where code space and data space co-incide, the
1.29      crook    7255: Standard only allows data space to be assigned for a @code{CREATE}d
                   7256: word. In addition, the Standard only allows @code{@@} to access data
                   7257: space, whilst this example is using it to access code space. The only
                   7258: portable, Standard way to build this table is to build it in data space,
                   7259: like this:
                   7260: 
                   7261: @example
                   7262: create table ' aa , ' bb , ' cc ,
                   7263: @end example
                   7264: 
1.26      crook    7265: doc-state
                   7266: doc-[
                   7267: doc-]
1.1       anton    7268: 
1.44      crook    7269: 
1.26      crook    7270: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
                   7271: @subsection Literals
                   7272: @cindex Literals
1.21      crook    7273: 
1.29      crook    7274: Often, you want to use a number within a colon definition. When you do
                   7275: this, the text interpreter automatically compiles the number as a
                   7276: @i{literal}. A literal is a number whose run-time effect is to be pushed
                   7277: onto the stack.  If you had to do some maths to generate the number, you
                   7278: might write it like this:
                   7279: 
                   7280: @example
                   7281: : HOUR-TO-SEC ( n1 -- n2 )
                   7282:   60 *      \ to minutes
                   7283:   60 * ;    \ to seconds
                   7284: @end example
                   7285: 
                   7286: It is very clear what this definition is doing, but it's inefficient
                   7287: since it is performing 2 multiples at run-time. An alternative would be
                   7288: to write:
                   7289: 
                   7290: @example
                   7291: : HOUR-TO-SEC ( n1 -- n2 )
                   7292:   3600 * ;  \ to seconds
                   7293: @end example
                   7294: 
                   7295: Which does the same thing, and has the advantage of using a single
                   7296: multiply. Ideally, we'd like the efficiency of the second with the
                   7297: readability of the first.
                   7298: 
                   7299: @code{Literal} allows us to achieve that. It takes a number from the
                   7300: stack and lays it down in the current definition just as though the
                   7301: number had been typed directly into the definition. Our first attempt
                   7302: might look like this:
                   7303: 
                   7304: @example
                   7305: 60          \ mins per hour
                   7306: 60 *        \ seconds per minute
                   7307: : HOUR-TO-SEC ( n1 -- n2 )
                   7308:   Literal * ;  \ to seconds
                   7309: @end example
                   7310: 
                   7311: But this produces the error message @code{unstructured}. What happened?
                   7312: The stack notation for @code{:} is (@i{ -- colon-sys}) and the size of
                   7313: @i{colon-sys} is implementation-defined. In other words, once we start a
                   7314: colon definition we can't portably access anything that was on the stack
                   7315: before the definition began@footnote{@cite{Two Problems in ANS Forth},
                   7316: by Thomas Worthington; Forth Dimensions 20(2) pages 32--34 describes
                   7317: some situations where you might want to access stack items above
                   7318: colon-sys, and provides a solution to the problem.}. The correct way of
                   7319: solving this problem in this instance is to use @code{[ ]} like this:
                   7320: 
                   7321: @example
                   7322: : HOUR-TO-SEC ( n1 -- n2 )
                   7323:   [ 60          \ minutes per hour
                   7324:     60 * ]      \ seconds per minute
                   7325:   LITERAL * ;   \ to seconds
                   7326: @end example
1.23      crook    7327: 
1.44      crook    7328: 
1.26      crook    7329: doc-literal
                   7330: doc-]L
                   7331: doc-2literal
                   7332: doc-fliteral
1.1       anton    7333: 
1.44      crook    7334: 
1.48      anton    7335: @node Interpreter Directives,  , Literals, The Text Interpreter
1.26      crook    7336: @subsection Interpreter Directives
                   7337: @cindex interpreter directives
1.1       anton    7338: 
1.29      crook    7339: These words are usually used in interpret state; typically to control
                   7340: which parts of a source file are processed by the text
1.26      crook    7341: interpreter. There are only a few ANS Forth Standard words, but Gforth
                   7342: supplements these with a rich set of immediate control structure words
                   7343: to compensate for the fact that the non-immediate versions can only be
1.29      crook    7344: used in compile state (@pxref{Control Structures}). Typical usages:
                   7345: 
                   7346: @example
                   7347: FALSE Constant ASSEMBLER
                   7348: .
                   7349: .
                   7350: ASSEMBLER [IF]
                   7351: : ASSEMBLER-FEATURE
                   7352:   ...
                   7353: ;
                   7354: [ENDIF]
                   7355: .
                   7356: .
                   7357: : SEE
                   7358:   ... \ general-purpose SEE code
                   7359:   [ ASSEMBLER [IF] ]
                   7360:   ... \ assembler-specific SEE code
                   7361:   [ [ENDIF] ]
                   7362: ;
                   7363: @end example
1.1       anton    7364: 
1.44      crook    7365: 
1.26      crook    7366: doc-[IF]
                   7367: doc-[ELSE]
                   7368: doc-[THEN]
                   7369: doc-[ENDIF]
1.1       anton    7370: 
1.26      crook    7371: doc-[IFDEF]
                   7372: doc-[IFUNDEF]
1.1       anton    7373: 
1.26      crook    7374: doc-[?DO]
                   7375: doc-[DO]
                   7376: doc-[FOR]
                   7377: doc-[LOOP]
                   7378: doc-[+LOOP]
                   7379: doc-[NEXT]
1.1       anton    7380: 
1.26      crook    7381: doc-[BEGIN]
                   7382: doc-[UNTIL]
                   7383: doc-[AGAIN]
                   7384: doc-[WHILE]
                   7385: doc-[REPEAT]
1.1       anton    7386: 
1.27      crook    7387: 
1.26      crook    7388: @c -------------------------------------------------------------
1.47      crook    7389: @node Word Lists, Environmental Queries, The Text Interpreter, Words
1.26      crook    7390: @section Word Lists
                   7391: @cindex word lists
1.32      anton    7392: @cindex header space
1.1       anton    7393: 
1.36      anton    7394: A wordlist is a list of named words; you can add new words and look up
                   7395: words by name (and you can remove words in a restricted way with
                   7396: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
                   7397: 
                   7398: @cindex search order stack
                   7399: The text interpreter searches the wordlists present in the search order
                   7400: (a stack of wordlists), from the top to the bottom.  Within each
                   7401: wordlist, the search starts conceptually at the newest word; i.e., if
                   7402: two words in a wordlist have the same name, the newer word is found.
1.1       anton    7403: 
1.26      crook    7404: @cindex compilation word list
1.36      anton    7405: New words are added to the @dfn{compilation wordlist} (aka current
                   7406: wordlist).
1.1       anton    7407: 
1.36      anton    7408: @cindex wid
                   7409: A word list is identified by a cell-sized word list identifier (@i{wid})
                   7410: in much the same way as a file is identified by a file handle. The
                   7411: numerical value of the wid has no (portable) meaning, and might change
                   7412: from session to session.
1.1       anton    7413: 
1.29      crook    7414: The ANS Forth ``Search order'' word set is intended to provide a set of
                   7415: low-level tools that allow various different schemes to be
1.26      crook    7416: implemented. Gforth provides @code{vocabulary}, a traditional Forth
                   7417: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
1.45      crook    7418: Forth.
1.1       anton    7419: 
1.27      crook    7420: @comment TODO: locals section refers to here, saying that every word list (aka
                   7421: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.1       anton    7422: 
1.45      crook    7423: @comment TODO: document markers, reveal, tables, mappedwordlist
                   7424: 
                   7425: @comment the gforthman- prefix is used to pick out the true definition of a
1.27      crook    7426: @comment word from the source files, rather than some alias.
1.44      crook    7427: 
1.26      crook    7428: doc-forth-wordlist
                   7429: doc-definitions
                   7430: doc-get-current
                   7431: doc-set-current
                   7432: doc-get-order
1.45      crook    7433: doc---gforthman-set-order
1.26      crook    7434: doc-wordlist
1.30      anton    7435: doc-table
1.36      anton    7436: doc-push-order
                   7437: doc-previous
1.26      crook    7438: doc-also
1.45      crook    7439: doc---gforthman-forth
1.26      crook    7440: doc-only
1.45      crook    7441: doc---gforthman-order
1.15      anton    7442: 
1.26      crook    7443: doc-find
                   7444: doc-search-wordlist
1.15      anton    7445: 
1.26      crook    7446: doc-words
                   7447: doc-vlist
1.44      crook    7448: @c doc-words-deferred
1.1       anton    7449: 
1.26      crook    7450: doc-mappedwordlist
                   7451: doc-root
                   7452: doc-vocabulary
                   7453: doc-seal
                   7454: doc-vocs
                   7455: doc-current
                   7456: doc-context
1.1       anton    7457: 
1.44      crook    7458: 
1.26      crook    7459: @menu
                   7460: * Why use word lists?::
                   7461: * Word list examples::
                   7462: @end menu
                   7463: 
                   7464: @node Why use word lists?, Word list examples, Word Lists, Word Lists
                   7465: @subsection Why use word lists?
                   7466: @cindex word lists - why use them?
                   7467: 
1.29      crook    7468: Here are some reasons for using multiple word lists:
1.26      crook    7469: 
                   7470: @itemize @bullet
                   7471: @item
1.32      anton    7472: To improve compilation speed by reducing the number of header space
1.26      crook    7473: entries that must be searched. This is achieved by creating a new
                   7474: word list that contains all of the definitions that are used in the
                   7475: definition of a Forth system but which would not usually be used by
                   7476: programs running on that system. That word list would be on the search
                   7477: list when the Forth system was compiled but would be removed from the
                   7478: search list for normal operation. This can be a useful technique for
                   7479: low-performance systems (for example, 8-bit processors in embedded
                   7480: systems) but is unlikely to be necessary in high-performance desktop
                   7481: systems.
                   7482: @item
                   7483: To prevent a set of words from being used outside the context in which
                   7484: they are valid. Two classic examples of this are an integrated editor
                   7485: (all of the edit commands are defined in a separate word list; the
                   7486: search order is set to the editor word list when the editor is invoked;
                   7487: the old search order is restored when the editor is terminated) and an
                   7488: integrated assembler (the op-codes for the machine are defined in a
                   7489: separate word list which is used when a @code{CODE} word is defined).
                   7490: @item
                   7491: To prevent a name-space clash between multiple definitions with the same
                   7492: name. For example, when building a cross-compiler you might have a word
                   7493: @code{IF} that generates conditional code for your target system. By
                   7494: placing this definition in a different word list you can control whether
                   7495: the host system's @code{IF} or the target system's @code{IF} get used in
                   7496: any particular context by controlling the order of the word lists on the
                   7497: search order stack.
                   7498: @end itemize
1.1       anton    7499: 
1.48      anton    7500: @node Word list examples,  , Why use word lists?, Word Lists
1.26      crook    7501: @subsection Word list examples
                   7502: @cindex word lists - examples
1.1       anton    7503: 
1.26      crook    7504: Here is an example of creating and using a new wordlist using ANS
                   7505: Forth Standard words:
1.1       anton    7506: 
                   7507: @example
1.26      crook    7508: wordlist constant my-new-words-wordlist
                   7509: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
1.21      crook    7510: 
1.26      crook    7511: \ add it to the search order
                   7512: also my-new-words
1.21      crook    7513: 
1.26      crook    7514: \ alternatively, add it to the search order and make it
                   7515: \ the compilation word list
                   7516: also my-new-words definitions
                   7517: \ type "order" to see the problem
1.21      crook    7518: @end example
                   7519: 
1.26      crook    7520: The problem with this example is that @code{order} has no way to
                   7521: associate the name @code{my-new-words} with the wid of the word list (in
                   7522: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
                   7523: that has no associated name). There is no Standard way of associating a
                   7524: name with a wid.
                   7525: 
                   7526: In Gforth, this example can be re-coded using @code{vocabulary}, which
                   7527: associates a name with a wid:
1.21      crook    7528: 
1.26      crook    7529: @example
                   7530: vocabulary my-new-words
1.21      crook    7531: 
1.26      crook    7532: \ add it to the search order
1.45      crook    7533: also my-new-words
1.21      crook    7534: 
1.26      crook    7535: \ alternatively, add it to the search order and make it
                   7536: \ the compilation word list
                   7537: my-new-words definitions
                   7538: \ type "order" to see that the problem is solved
                   7539: @end example
1.23      crook    7540: 
1.26      crook    7541: @c -------------------------------------------------------------
                   7542: @node Environmental Queries, Files, Word Lists, Words
                   7543: @section Environmental Queries
                   7544: @cindex environmental queries
1.21      crook    7545: 
1.26      crook    7546: ANS Forth introduced the idea of ``environmental queries'' as a way
                   7547: for a program running on a system to determine certain characteristics of the system.
                   7548: The Standard specifies a number of strings that might be recognised by a system.
1.21      crook    7549: 
1.32      anton    7550: The Standard requires that the header space used for environmental queries
                   7551: be distinct from the header space used for definitions.
1.21      crook    7552: 
1.26      crook    7553: Typically, environmental queries are supported by creating a set of
1.29      crook    7554: definitions in a word list that is @i{only} used during environmental
1.26      crook    7555: queries; that is what Gforth does. There is no Standard way of adding
                   7556: definitions to the set of recognised environmental queries, but any
                   7557: implementation that supports the loading of optional word sets must have
                   7558: some mechanism for doing this (after loading the word set, the
                   7559: associated environmental query string must return @code{true}). In
                   7560: Gforth, the word list used to honour environmental queries can be
                   7561: manipulated just like any other word list.
1.21      crook    7562: 
1.44      crook    7563: 
1.26      crook    7564: doc-environment?
                   7565: doc-environment-wordlist
1.21      crook    7566: 
1.26      crook    7567: doc-gforth
                   7568: doc-os-class
1.21      crook    7569: 
1.44      crook    7570: 
1.26      crook    7571: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
                   7572: returning two items on the stack, querying it using @code{environment?}
                   7573: will return an additional item; the @code{true} flag that shows that the
                   7574: string was recognised.
1.21      crook    7575: 
1.26      crook    7576: @comment TODO Document the standard strings or note where they are documented herein
1.21      crook    7577: 
1.26      crook    7578: Here are some examples of using environmental queries:
1.21      crook    7579: 
1.26      crook    7580: @example
                   7581: s" address-unit-bits" environment? 0=
                   7582: [IF]
                   7583:      cr .( environmental attribute address-units-bits unknown... ) cr
                   7584: [THEN]
1.21      crook    7585: 
1.26      crook    7586: s" block" environment? [IF] DROP include block.fs [THEN]
1.21      crook    7587: 
1.26      crook    7588: s" gforth" environment? [IF] 2DROP include compat/vocabulary.fs [THEN]
1.21      crook    7589: 
1.26      crook    7590: s" gforth" environment? [IF] .( Gforth version ) TYPE
                   7591:                         [ELSE] .( Not Gforth..) [THEN]
                   7592: @end example
1.21      crook    7593: 
                   7594: 
1.26      crook    7595: Here is an example of adding a definition to the environment word list:
1.21      crook    7596: 
1.26      crook    7597: @example
                   7598: get-current environment-wordlist set-current
                   7599: true constant block
                   7600: true constant block-ext
                   7601: set-current
                   7602: @end example
1.21      crook    7603: 
1.26      crook    7604: You can see what definitions are in the environment word list like this:
1.21      crook    7605: 
1.26      crook    7606: @example
                   7607: get-order 1+ environment-wordlist swap set-order words previous
                   7608: @end example
1.21      crook    7609: 
                   7610: 
1.26      crook    7611: @c -------------------------------------------------------------
                   7612: @node Files, Blocks, Environmental Queries, Words
                   7613: @section Files
1.28      crook    7614: @cindex files
                   7615: @cindex I/O - file-handling
1.21      crook    7616: 
1.26      crook    7617: Gforth provides facilities for accessing files that are stored in the
                   7618: host operating system's file-system. Files that are processed by Gforth
                   7619: can be divided into two categories:
1.21      crook    7620: 
1.23      crook    7621: @itemize @bullet
                   7622: @item
1.29      crook    7623: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23      crook    7624: @item
1.29      crook    7625: Files that are processed by some other program (@dfn{general files}).
1.26      crook    7626: @end itemize
                   7627: 
1.45      crook    7628: doc-loadfilename
                   7629: doc-sourcefilename
                   7630: doc-sourceline#
                   7631: 
1.26      crook    7632: @menu
1.48      anton    7633: * Forth source files::          
                   7634: * General files::               
                   7635: * Search Paths::                
1.26      crook    7636: @end menu
                   7637: 
1.21      crook    7638: 
1.26      crook    7639: @c -------------------------------------------------------------
                   7640: @node Forth source files, General files, Files, Files
                   7641: @subsection Forth source files
                   7642: @cindex including files
                   7643: @cindex Forth source files
1.21      crook    7644: 
1.26      crook    7645: The simplest way to interpret the contents of a file is to use one of
                   7646: these two formats:
1.21      crook    7647: 
1.26      crook    7648: @example
                   7649: include mysource.fs
                   7650: s" mysource.fs" included
                   7651: @end example
1.21      crook    7652: 
1.26      crook    7653: Sometimes you want to include a file only if it is not included already
                   7654: (by, say, another source file). In that case, you can use one of these
1.45      crook    7655: three formats:
1.21      crook    7656: 
1.26      crook    7657: @example
                   7658: require mysource.fs
                   7659: needs mysource.fs
                   7660: s" mysource.fs" required
                   7661: @end example
1.21      crook    7662: 
1.26      crook    7663: @cindex stack effect of included files
                   7664: @cindex including files, stack effect
1.45      crook    7665: It is good practice to write your source files such that interpreting them
                   7666: does not change the stack. Source files designed in this way can be used with
1.26      crook    7667: @code{required} and friends without complications. For example:
1.21      crook    7668: 
1.26      crook    7669: @example
                   7670: 1 require foo.fs drop
                   7671: @end example
1.21      crook    7672: 
1.44      crook    7673: 
1.26      crook    7674: doc-include-file
                   7675: doc-included
1.28      crook    7676: doc-included?
1.26      crook    7677: doc-include
                   7678: doc-required
                   7679: doc-require
                   7680: doc-needs
1.28      crook    7681: doc-init-included-files
1.21      crook    7682: 
1.44      crook    7683: 
1.26      crook    7684: A definition in ANS Forth for @code{required} is provided in
                   7685: @file{compat/required.fs}.
1.21      crook    7686: 
1.26      crook    7687: @c -------------------------------------------------------------
                   7688: @node General files, Search Paths, Forth source files, Files
                   7689: @subsection General files
                   7690: @cindex general files
                   7691: @cindex file-handling
1.21      crook    7692: 
1.26      crook    7693: Files are opened/created by name and type. The following types are
                   7694: recognised:
1.1       anton    7695: 
1.44      crook    7696: 
1.26      crook    7697: doc-r/o
                   7698: doc-r/w
                   7699: doc-w/o
                   7700: doc-bin
1.1       anton    7701: 
1.44      crook    7702: 
1.26      crook    7703: When a file is opened/created, it returns a file identifier,
1.29      crook    7704: @i{wfileid} that is used for all other file commands. All file
                   7705: commands also return a status value, @i{wior}, that is 0 for a
1.26      crook    7706: successful operation and an implementation-defined non-zero value in the
                   7707: case of an error.
1.21      crook    7708: 
1.44      crook    7709: 
1.26      crook    7710: doc-open-file
                   7711: doc-create-file
1.21      crook    7712: 
1.26      crook    7713: doc-close-file
                   7714: doc-delete-file
                   7715: doc-rename-file
                   7716: doc-read-file
                   7717: doc-read-line
                   7718: doc-write-file
                   7719: doc-write-line
                   7720: doc-emit-file
                   7721: doc-flush-file
1.21      crook    7722: 
1.26      crook    7723: doc-file-status
                   7724: doc-file-position
                   7725: doc-reposition-file
                   7726: doc-file-size
                   7727: doc-resize-file
1.21      crook    7728: 
1.44      crook    7729: 
1.26      crook    7730: @c ---------------------------------------------------------
1.48      anton    7731: @node Search Paths,  , General files, Files
1.26      crook    7732: @subsection Search Paths
                   7733: @cindex path for @code{included}
                   7734: @cindex file search path
                   7735: @cindex @code{include} search path
                   7736: @cindex search path for files
1.21      crook    7737: 
1.26      crook    7738: If you specify an absolute filename (i.e., a filename starting with
                   7739: @file{/} or @file{~}, or with @file{:} in the second position (as in
                   7740: @samp{C:...})) for @code{included} and friends, that file is included
                   7741: just as you would expect.
1.21      crook    7742: 
1.26      crook    7743: For relative filenames, Gforth uses a search path similar to Forth's
                   7744: search order (@pxref{Word Lists}). It tries to find the given filename
                   7745: in the directories present in the path, and includes the first one it
                   7746: finds. There are separate search paths for Forth source files and
                   7747: general files.
1.21      crook    7748: 
1.26      crook    7749: If the search path contains the directory @file{.} (as it should), this
                   7750: refers to the directory that the present file was @code{included}
                   7751: from. This allows files to include other files relative to their own
                   7752: position (irrespective of the current working directory or the absolute
                   7753: position).  This feature is essential for libraries consisting of
                   7754: several files, where a file may include other files from the library.
                   7755: It corresponds to @code{#include "..."} in C. If the current input
                   7756: source is not a file, @file{.} refers to the directory of the innermost
                   7757: file being included, or, if there is no file being included, to the
                   7758: current working directory.
1.21      crook    7759: 
1.26      crook    7760: Use @file{~+} to refer to the current working directory (as in the
                   7761: @code{bash}).
1.1       anton    7762: 
1.26      crook    7763: If the filename starts with @file{./}, the search path is not searched
                   7764: (just as with absolute filenames), and the @file{.} has the same meaning
                   7765: as described above.
1.1       anton    7766: 
1.48      anton    7767: @menu
                   7768: * Forth Search Paths::          
                   7769: * General Search Paths::        
                   7770: @end menu
                   7771: 
1.26      crook    7772: @c ---------------------------------------------------------
1.48      anton    7773: @node Forth Search Paths, General Search Paths, Search Paths, Search Paths
1.26      crook    7774: @subsubsection Forth Search Paths
1.28      crook    7775: @cindex search path control - Forth
1.5       anton    7776: 
1.26      crook    7777: The search path is initialized when you start Gforth (@pxref{Invoking
                   7778: Gforth}). You can display it and change it using these words:
1.5       anton    7779: 
1.44      crook    7780: 
1.26      crook    7781: doc-.fpath
                   7782: doc-fpath+
                   7783: doc-fpath=
                   7784: doc-open-fpath-file
1.5       anton    7785: 
1.44      crook    7786: 
                   7787: @noindent
1.26      crook    7788: Here is an example of using @code{fpath} and @code{require}:
1.5       anton    7789: 
1.26      crook    7790: @example
                   7791: fpath= /usr/lib/forth/|./
                   7792: require timer.fs
                   7793: @end example
1.5       anton    7794: 
1.26      crook    7795: @c ---------------------------------------------------------
1.48      anton    7796: @node General Search Paths,  , Forth Search Paths, Search Paths
1.26      crook    7797: @subsubsection General Search Paths
                   7798: @cindex search path control - for user applications
1.5       anton    7799: 
1.26      crook    7800: Your application may need to search files in several directories, like
                   7801: @code{included} does. To facilitate this, Gforth allows you to define
                   7802: and use your own search paths, by providing generic equivalents of the
                   7803: Forth search path words:
1.5       anton    7804: 
1.44      crook    7805: 
1.26      crook    7806: doc-.path
                   7807: doc-path+
                   7808: doc-path=
                   7809: doc-open-path-file
1.5       anton    7810: 
1.44      crook    7811: 
1.26      crook    7812: Here's an example of creating a search path:
1.5       anton    7813: 
1.26      crook    7814: @example
                   7815: \ Make a buffer for the path:
                   7816: create mypath   100 chars ,     \ maximum length (is checked)
                   7817:                 0 ,             \ real len
                   7818:                 100 chars allot \ space for path
                   7819: @end example
1.5       anton    7820: 
1.26      crook    7821: @c -------------------------------------------------------------
                   7822: @node Blocks, Other I/O, Files, Words
                   7823: @section Blocks
1.28      crook    7824: @cindex I/O - blocks
                   7825: @cindex blocks
                   7826: 
                   7827: When you run Gforth on a modern desk-top computer, it runs under the
                   7828: control of an operating system which provides certain services.  One of
                   7829: these services is @var{file services}, which allows Forth source code
                   7830: and data to be stored in files and read into Gforth (@pxref{Files}).
                   7831: 
                   7832: Traditionally, Forth has been an important programming language on
                   7833: systems where it has interfaced directly to the underlying hardware with
                   7834: no intervening operating system. Forth provides a mechanism, called
1.29      crook    7835: @dfn{blocks}, for accessing mass storage on such systems.
1.28      crook    7836: 
                   7837: A block is a 1024-byte data area, which can be used to hold data or
                   7838: Forth source code. No structure is imposed on the contents of the
                   7839: block. A block is identified by its number; blocks are numbered
                   7840: contiguously from 1 to an implementation-defined maximum.
                   7841: 
                   7842: A typical system that used blocks but no operating system might use a
                   7843: single floppy-disk drive for mass storage, with the disks formatted to
                   7844: provide 256-byte sectors. Blocks would be implemented by assigning the
                   7845: first four sectors of the disk to block 1, the second four sectors to
                   7846: block 2 and so on, up to the limit of the capacity of the disk. The disk
                   7847: would not contain any file system information, just the set of blocks.
                   7848: 
1.29      crook    7849: @cindex blocks file
1.28      crook    7850: On systems that do provide file services, blocks are typically
1.29      crook    7851: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28      crook    7852: file}.  The size of the blocks file will be an exact multiple of 1024
                   7853: bytes, corresponding to the number of blocks it contains. This is the
                   7854: mechanism that Gforth uses.
                   7855: 
1.29      crook    7856: @cindex @file{blocks.fb}
1.28      crook    7857: Only 1 blocks file can be open at a time. If you use block words without
                   7858: having specified a blocks file, Gforth defaults to the blocks file
                   7859: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
                   7860: locate a blocks file (@pxref{Forth Search Paths}).
                   7861: 
1.29      crook    7862: @cindex block buffers
1.28      crook    7863: When you read and write blocks under program control, Gforth uses a
1.29      crook    7864: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28      crook    7865: not used when you use @code{load} to interpret the contents of a block.
                   7866: 
                   7867: The behaviour of the block buffers is directly analagous to that of a
                   7868: cache. Each block buffer has three states:
                   7869: 
                   7870: @itemize @bullet
                   7871: @item
                   7872: Unassigned
                   7873: @item
                   7874: Assigned-clean
                   7875: @item
                   7876: Assigned-dirty
                   7877: @end itemize
                   7878: 
1.29      crook    7879: Initially, all block buffers are @i{unassigned}. In order to access a
1.28      crook    7880: block, the block (specified by its block number) must be assigned to a
                   7881: block buffer.
                   7882: 
                   7883: The assignment of a block to a block buffer is performed by @code{block}
                   7884: or @code{buffer}. Use @code{block} when you wish to modify the existing
                   7885: contents of a block. Use @code{buffer} when you don't care about the
                   7886: existing contents of the block@footnote{The ANS Forth definition of
1.35      anton    7887: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28      crook    7888: with the particular block is already stored in a block buffer due to an
                   7889: earlier @code{block} command, @code{buffer} will return that block
                   7890: buffer and the existing contents of the block will be
                   7891: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29      crook    7892: block buffer for the block.}.
1.28      crook    7893: 
1.47      crook    7894: Once a block has been assigned to a block buffer using @code{block} or
                   7895: @code{buffer}, that block buffer becomes the @i{current block buffer}
                   7896: and its state changes to @i{assigned-clean}. Data may only be
                   7897: manipulated (read or written) within the current block buffer.
                   7898: 
                   7899: When the contents of the current block buffer has been modified it is
1.48      anton    7900: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
                   7901: either abandon the changes (by doing nothing) or commit the changes,
                   7902: using @code{update}. Using @code{update} does not change the blocks
                   7903: file; it simply changes a block buffer's state to @i{assigned-dirty}.
1.28      crook    7904: 
1.29      crook    7905: The word @code{flush} causes all @i{assigned-dirty} blocks to be
1.28      crook    7906: written back to the blocks file on disk. Leaving Gforth using @code{bye}
                   7907: also causes a @code{flush} to be performed.
                   7908: 
1.29      crook    7909: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28      crook    7910: algorithm to assign a block buffer to a block. That means that any
                   7911: particular block can only be assigned to one specific block buffer,
1.29      crook    7912: called (for the particular operation) the @i{victim buffer}. If the
1.47      crook    7913: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
                   7914: the new block immediately. If it is @i{assigned-dirty} its current
                   7915: contents are written back to the blocks file on disk before it is
1.28      crook    7916: allocated to the new block.
                   7917: 
                   7918: Although no structure is imposed on the contents of a block, it is
                   7919: traditional to display the contents as 16 lines each of 64 characters.  A
                   7920: block provides a single, continuous stream of input (for example, it
                   7921: acts as a single parse area) -- there are no end-of-line characters
                   7922: within a block, and no end-of-file character at the end of a
                   7923: block. There are two consequences of this:
1.26      crook    7924: 
1.28      crook    7925: @itemize @bullet
                   7926: @item
                   7927: The last character of one line wraps straight into the first character
                   7928: of the following line
                   7929: @item
                   7930: The word @code{\} -- comment to end of line -- requires special
                   7931: treatment; in the context of a block it causes all characters until the
                   7932: end of the current 64-character ``line'' to be ignored.
                   7933: @end itemize
                   7934: 
                   7935: In Gforth, when you use @code{block} with a non-existent block number,
1.45      crook    7936: the current blocks file will be extended to the appropriate size and the
1.28      crook    7937: block buffer will be initialised with spaces.
                   7938: 
1.47      crook    7939: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
                   7940: for details) but doesn't encourage the use of blocks; the mechanism is
                   7941: only provided for backward compatibility -- ANS Forth requires blocks to
                   7942: be available when files are.
1.28      crook    7943: 
                   7944: Common techniques that are used when working with blocks include:
                   7945: 
                   7946: @itemize @bullet
                   7947: @item
                   7948: A screen editor that allows you to edit blocks without leaving the Forth
                   7949: environment.
                   7950: @item
                   7951: Shadow screens; where every code block has an associated block
                   7952: containing comments (for example: code in odd block numbers, comments in
                   7953: even block numbers). Typically, the block editor provides a convenient
                   7954: mechanism to toggle between code and comments.
                   7955: @item
                   7956: Load blocks; a single block (typically block 1) contains a number of
                   7957: @code{thru} commands which @code{load} the whole of the application.
                   7958: @end itemize
1.26      crook    7959: 
1.29      crook    7960: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
                   7961: integrated into a Forth programming environment.
1.26      crook    7962: 
                   7963: @comment TODO what about errors on open-blocks?
1.44      crook    7964: 
1.26      crook    7965: doc-open-blocks
                   7966: doc-use
                   7967: doc-get-block-fid
                   7968: doc-block-position
1.28      crook    7969: 
                   7970: doc-scr
                   7971: doc-list
                   7972: 
1.45      crook    7973: doc---gforthman-block
1.28      crook    7974: doc-buffer
                   7975: 
1.26      crook    7976: doc-update
1.28      crook    7977: doc-updated?
1.26      crook    7978: doc-save-buffers
                   7979: doc-empty-buffers
                   7980: doc-empty-buffer
                   7981: doc-flush
1.28      crook    7982: 
1.26      crook    7983: doc-load
                   7984: doc-thru
                   7985: doc-+load
                   7986: doc-+thru
1.45      crook    7987: doc---gforthman--->
1.26      crook    7988: doc-block-included
                   7989: 
1.44      crook    7990: 
1.26      crook    7991: @c -------------------------------------------------------------
                   7992: @node Other I/O, Programming Tools, Blocks, Words
                   7993: @section Other I/O
1.28      crook    7994: @cindex I/O - keyboard and display
1.26      crook    7995: 
                   7996: @menu
                   7997: * Simple numeric output::       Predefined formats
                   7998: * Formatted numeric output::    Formatted (pictured) output
                   7999: * String Formats::              How Forth stores strings in memory
                   8000: * Displaying characters and strings:: Other stuff
                   8001: * Input::                       Input
                   8002: @end menu
                   8003: 
                   8004: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
                   8005: @subsection Simple numeric output
1.28      crook    8006: @cindex numeric output - simple/free-format
1.5       anton    8007: 
1.26      crook    8008: The simplest output functions are those that display numbers from the
                   8009: data or floating-point stacks. Floating-point output is always displayed
                   8010: using base 10. Numbers displayed from the data stack use the value stored
                   8011: in @code{base}.
1.5       anton    8012: 
1.44      crook    8013: 
1.26      crook    8014: doc-.
                   8015: doc-dec.
                   8016: doc-hex.
                   8017: doc-u.
                   8018: doc-.r
                   8019: doc-u.r
                   8020: doc-d.
                   8021: doc-ud.
                   8022: doc-d.r
                   8023: doc-ud.r
                   8024: doc-f.
                   8025: doc-fe.
                   8026: doc-fs.
1.5       anton    8027: 
1.44      crook    8028: 
1.26      crook    8029: Examples of printing the number 1234.5678E23 in the different floating-point output
                   8030: formats are shown below:
1.5       anton    8031: 
                   8032: @example
1.26      crook    8033: f. 123456779999999000000000000.
                   8034: fe. 123.456779999999E24
                   8035: fs. 1.23456779999999E26
1.5       anton    8036: @end example
                   8037: 
                   8038: 
1.26      crook    8039: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
                   8040: @subsection Formatted numeric output
1.28      crook    8041: @cindex formatted numeric output
1.26      crook    8042: @cindex pictured numeric output
1.28      crook    8043: @cindex numeric output - formatted
1.26      crook    8044: 
1.29      crook    8045: Forth traditionally uses a technique called @dfn{pictured numeric
1.26      crook    8046: output} for formatted printing of integers.  In this technique, digits
                   8047: are extracted from the number (using the current output radix defined by
                   8048: @code{base}), converted to ASCII codes and appended to a string that is
                   8049: built in a scratch-pad area of memory (@pxref{core-idef,
                   8050: Implementation-defined options, Implementation-defined
                   8051: options}). Arbitrary characters can be appended to the string during the
                   8052: extraction process. The completed string is specified by an address
                   8053: and length and can be manipulated (@code{TYPE}ed, copied, modified)
                   8054: under program control.
1.5       anton    8055: 
1.26      crook    8056: All of the words described in the previous section for simple numeric
                   8057: output are implemented in Gforth using pictured numeric output.
1.5       anton    8058: 
1.47      crook    8059: Three important things to remember about pictured numeric output:
1.5       anton    8060: 
1.26      crook    8061: @itemize @bullet
                   8062: @item
1.28      crook    8063: It always operates on double-precision numbers; to display a
1.49      anton    8064: single-precision number, convert it first (for ways of doing this
                   8065: @pxref{Double precision}).
1.26      crook    8066: @item
1.28      crook    8067: It always treats the double-precision number as though it were
                   8068: unsigned. The examples below show ways of printing signed numbers.
1.26      crook    8069: @item
                   8070: The string is built up from right to left; least significant digit first.
                   8071: @end itemize
1.5       anton    8072: 
1.44      crook    8073: 
1.26      crook    8074: doc-<#
1.47      crook    8075: doc-<<#
1.26      crook    8076: doc-#
                   8077: doc-#s
                   8078: doc-hold
                   8079: doc-sign
                   8080: doc-#>
1.47      crook    8081: doc-#>>
1.5       anton    8082: 
1.26      crook    8083: doc-represent
1.5       anton    8084: 
1.44      crook    8085: 
                   8086: @noindent
1.26      crook    8087: Here are some examples of using pictured numeric output:
1.5       anton    8088: 
                   8089: @example
1.26      crook    8090: : my-u. ( u -- )
                   8091:   \ Simplest use of pns.. behaves like Standard u. 
                   8092:   0              \ convert to unsigned double
                   8093:   <#             \ start conversion
                   8094:   #s             \ convert all digits
                   8095:   #>             \ complete conversion
                   8096:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    8097: 
1.26      crook    8098: : cents-only ( u -- )
                   8099:   0              \ convert to unsigned double
                   8100:   <#             \ start conversion
                   8101:   # #            \ convert two least-significant digits
                   8102:   #>             \ complete conversion, discard other digits
                   8103:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    8104: 
1.26      crook    8105: : dollars-and-cents ( u -- )
                   8106:   0              \ convert to unsigned double
                   8107:   <#             \ start conversion
                   8108:   # #            \ convert two least-significant digits
                   8109:   [char] . hold  \ insert decimal point
                   8110:   #s             \ convert remaining digits
                   8111:   [char] $ hold  \ append currency symbol
                   8112:   #>             \ complete conversion
                   8113:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    8114: 
1.26      crook    8115: : my-. ( n -- )
                   8116:   \ handling negatives.. behaves like Standard .
                   8117:   s>d            \ convert to signed double
                   8118:   swap over dabs \ leave sign byte followed by unsigned double
                   8119:   <#             \ start conversion
                   8120:   #s             \ convert all digits
                   8121:   rot sign       \ get at sign byte, append "-" if needed
                   8122:   #>             \ complete conversion
                   8123:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    8124: 
1.26      crook    8125: : account. ( n -- )
                   8126:   \ accountants don't like minus signs, they use braces
                   8127:   \ for negative numbers
                   8128:   s>d            \ convert to signed double
                   8129:   swap over dabs \ leave sign byte followed by unsigned double
                   8130:   <#             \ start conversion
                   8131:   2 pick         \ get copy of sign byte
                   8132:   0< IF [char] ) hold THEN \ right-most character of output
                   8133:   #s             \ convert all digits
                   8134:   rot            \ get at sign byte
                   8135:   0< IF [char] ( hold THEN
                   8136:   #>             \ complete conversion
                   8137:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    8138: @end example
                   8139: 
1.26      crook    8140: Here are some examples of using these words:
1.5       anton    8141: 
                   8142: @example
1.26      crook    8143: 1 my-u. 1
                   8144: hex -1 my-u. decimal FFFFFFFF
                   8145: 1 cents-only 01
                   8146: 1234 cents-only 34
                   8147: 2 dollars-and-cents $0.02
                   8148: 1234 dollars-and-cents $12.34
                   8149: 123 my-. 123
                   8150: -123 my. -123
                   8151: 123 account. 123
                   8152: -456 account. (456)
1.5       anton    8153: @end example
                   8154: 
                   8155: 
1.26      crook    8156: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
                   8157: @subsection String Formats
1.27      crook    8158: @cindex strings - see character strings
                   8159: @cindex character strings - formats
1.28      crook    8160: @cindex I/O - see character strings
1.26      crook    8161: 
1.27      crook    8162: Forth commonly uses two different methods for representing character
                   8163: strings:
1.26      crook    8164: 
                   8165: @itemize @bullet
                   8166: @item
                   8167: @cindex address of counted string
1.45      crook    8168: @cindex counted string
1.29      crook    8169: As a @dfn{counted string}, represented by a @i{c-addr}. The char
                   8170: addressed by @i{c-addr} contains a character-count, @i{n}, of the
                   8171: string and the string occupies the subsequent @i{n} char addresses in
1.26      crook    8172: memory.
                   8173: @item
1.29      crook    8174: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
                   8175: of the string in characters, and @i{c-addr} is the address of the
1.26      crook    8176: first byte of the string.
                   8177: @end itemize
                   8178: 
                   8179: ANS Forth encourages the use of the second format when representing
                   8180: strings on the stack, whilst conceeding that the counted string format
                   8181: remains useful as a way of storing strings in memory.
                   8182: 
1.44      crook    8183: 
1.26      crook    8184: doc-count
                   8185: 
1.44      crook    8186: 
1.49      anton    8187: For words that move, copy and search for strings see @ref{Memory
                   8188: Blocks}. For words that display characters and strings see
                   8189: @ref{Displaying characters and strings}.
1.26      crook    8190: 
                   8191: @node Displaying characters and strings, Input, String Formats, Other I/O
                   8192: @subsection Displaying characters and strings
1.27      crook    8193: @cindex characters - compiling and displaying
                   8194: @cindex character strings - compiling and displaying
1.26      crook    8195: 
                   8196: This section starts with a glossary of Forth words and ends with a set
                   8197: of examples.
                   8198: 
1.44      crook    8199: 
1.26      crook    8200: doc-bl
                   8201: doc-space
                   8202: doc-spaces
                   8203: doc-emit
                   8204: doc-toupper
                   8205: doc-."
                   8206: doc-.(
                   8207: doc-type
1.44      crook    8208: doc-typewhite
1.26      crook    8209: doc-cr
1.27      crook    8210: @cindex cursor control
1.26      crook    8211: doc-at-xy
                   8212: doc-page
                   8213: doc-s"
                   8214: doc-c"
                   8215: doc-char
                   8216: doc-[char]
                   8217: doc-sliteral
                   8218: 
1.44      crook    8219: 
                   8220: @noindent
1.26      crook    8221: As an example, consider the following text, stored in a file @file{test.fs}:
1.5       anton    8222: 
                   8223: @example
1.26      crook    8224: .( text-1)
                   8225: : my-word
                   8226:   ." text-2" cr
                   8227:   .( text-3)
                   8228: ;
                   8229: 
                   8230: ." text-4"
                   8231: 
                   8232: : my-char
                   8233:   [char] ALPHABET emit
                   8234:   char emit
                   8235: ;
1.5       anton    8236: @end example
                   8237: 
1.26      crook    8238: When you load this code into Gforth, the following output is generated:
1.5       anton    8239: 
1.26      crook    8240: @example
1.30      anton    8241: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26      crook    8242: @end example
1.5       anton    8243: 
1.26      crook    8244: @itemize @bullet
                   8245: @item
                   8246: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
                   8247: is an immediate word; it behaves in the same way whether it is used inside
                   8248: or outside a colon definition.
                   8249: @item
                   8250: Message @code{text-4} is displayed because of Gforth's added interpretation
                   8251: semantics for @code{."}.
                   8252: @item
1.29      crook    8253: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26      crook    8254: performs the compilation semantics for @code{."} within the definition of
                   8255: @code{my-word}.
                   8256: @end itemize
1.5       anton    8257: 
1.26      crook    8258: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5       anton    8259: 
1.26      crook    8260: @example
1.30      anton    8261: @kbd{my-word @key{RET}} text-2
1.26      crook    8262:  ok
1.30      anton    8263: @kbd{my-char fred @key{RET}} Af ok
                   8264: @kbd{my-char jim @key{RET}} Aj ok
1.26      crook    8265: @end example
1.5       anton    8266: 
                   8267: @itemize @bullet
                   8268: @item
1.26      crook    8269: Message @code{text-2} is displayed because of the run-time behaviour of
                   8270: @code{."}.
                   8271: @item
                   8272: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
                   8273: on the stack at run-time. @code{emit} always displays the character
                   8274: when @code{my-char} is executed.
                   8275: @item
                   8276: @code{char} parses a string at run-time and the second @code{emit} displays
                   8277: the first character of the string.
1.5       anton    8278: @item
1.26      crook    8279: If you type @code{see my-char} you can see that @code{[char]} discarded
                   8280: the text ``LPHABET'' and only compiled the display code for ``A'' into the
                   8281: definition of @code{my-char}.
1.5       anton    8282: @end itemize
                   8283: 
                   8284: 
                   8285: 
1.48      anton    8286: @node Input,  , Displaying characters and strings, Other I/O
1.26      crook    8287: @subsection Input
                   8288: @cindex input
1.28      crook    8289: @cindex I/O - see input
                   8290: @cindex parsing a string
1.5       anton    8291: 
1.49      anton    8292: For ways of storing character strings in memory see @ref{String Formats}.
1.5       anton    8293: 
1.27      crook    8294: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29      crook    8295: @comment then index them
1.27      crook    8296: 
1.44      crook    8297: 
1.27      crook    8298: doc-key
                   8299: doc-key?
1.45      crook    8300: doc-ekey
                   8301: doc-ekey?
                   8302: doc-ekey>char
1.26      crook    8303: doc->number
                   8304: doc->float
                   8305: doc-accept
1.27      crook    8306: doc-pad
                   8307: doc-parse
                   8308: doc-word
                   8309: doc-sword
1.44      crook    8310: doc-(name)
1.27      crook    8311: doc-refill
                   8312: @comment obsolescent words..
                   8313: doc-convert
1.26      crook    8314: doc-query
                   8315: doc-expect
1.27      crook    8316: doc-span
1.5       anton    8317: 
                   8318: 
1.44      crook    8319: 
1.5       anton    8320: @c -------------------------------------------------------------
1.26      crook    8321: @node Programming Tools, Assembler and Code Words, Other I/O, Words
                   8322: @section Programming Tools
                   8323: @cindex programming tools
1.12      anton    8324: 
                   8325: @menu
1.26      crook    8326: * Debugging::                   Simple and quick.
                   8327: * Assertions::                  Making your programs self-checking.
1.46      pazsan   8328: * Singlestep Debugger::         Executing your program word by word.
1.5       anton    8329: @end menu
                   8330: 
1.26      crook    8331: @node Debugging, Assertions, Programming Tools, Programming Tools
                   8332: @subsection Debugging
                   8333: @cindex debugging
1.5       anton    8334: 
1.26      crook    8335: Languages with a slow edit/compile/link/test development loop tend to
                   8336: require sophisticated tracing/stepping debuggers to facilate
                   8337: productive debugging.
1.5       anton    8338: 
1.26      crook    8339: A much better (faster) way in fast-compiling languages is to add
                   8340: printing code at well-selected places, let the program run, look at
                   8341: the output, see where things went wrong, add more printing code, etc.,
                   8342: until the bug is found.
1.5       anton    8343: 
1.26      crook    8344: The simple debugging aids provided in @file{debugs.fs}
                   8345: are meant to support this style of debugging. In addition, there are
                   8346: words for non-destructively inspecting the stack and memory:
1.5       anton    8347: 
1.44      crook    8348: 
1.26      crook    8349: doc-.s
                   8350: doc-f.s
1.5       anton    8351: 
1.44      crook    8352: 
1.29      crook    8353: There is a word @code{.r} but it does @i{not} display the return
1.26      crook    8354: stack! It is used for formatted numeric output.
1.5       anton    8355: 
1.44      crook    8356: 
1.26      crook    8357: doc-depth
                   8358: doc-fdepth
                   8359: doc-clearstack
                   8360: doc-?
                   8361: doc-dump
1.5       anton    8362: 
1.44      crook    8363: 
1.26      crook    8364: The word @code{~~} prints debugging information (by default the source
                   8365: location and the stack contents). It is easy to insert. If you use Emacs
                   8366: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
                   8367: query-replace them with nothing). The deferred words
                   8368: @code{printdebugdata} and @code{printdebugline} control the output of
                   8369: @code{~~}. The default source location output format works well with
                   8370: Emacs' compilation mode, so you can step through the program at the
                   8371: source level using @kbd{C-x `} (the advantage over a stepping debugger
                   8372: is that you can step in any direction and you know where the crash has
                   8373: happened or where the strange data has occurred).
1.5       anton    8374: 
1.26      crook    8375: The default actions of @code{~~} clobber the contents of the pictured
                   8376: numeric output string, so you should not use @code{~~}, e.g., between
                   8377: @code{<#} and @code{#>}.
1.5       anton    8378: 
1.44      crook    8379: 
1.26      crook    8380: doc-~~
                   8381: doc-printdebugdata
                   8382: doc-printdebugline
1.5       anton    8383: 
1.26      crook    8384: doc-see
                   8385: doc-marker
1.5       anton    8386: 
1.44      crook    8387: 
1.26      crook    8388: Here's an example of using @code{marker} at the start of a source file
                   8389: that you are debugging; it ensures that you only ever have one copy of
                   8390: the file's definitions compiled at any time:
1.5       anton    8391: 
1.26      crook    8392: @example
                   8393: [IFDEF] my-code
                   8394:     my-code
                   8395: [ENDIF]
1.5       anton    8396: 
1.26      crook    8397: marker my-code
1.28      crook    8398: init-included-files
1.5       anton    8399: 
1.26      crook    8400: \ .. definitions start here
                   8401: \ .
                   8402: \ .
                   8403: \ end
                   8404: @end example
1.5       anton    8405: 
                   8406: 
                   8407: 
1.26      crook    8408: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
                   8409: @subsection Assertions
                   8410: @cindex assertions
1.5       anton    8411: 
1.26      crook    8412: It is a good idea to make your programs self-checking, especially if you
                   8413: make an assumption that may become invalid during maintenance (for
                   8414: example, that a certain field of a data structure is never zero). Gforth
1.29      crook    8415: supports @dfn{assertions} for this purpose. They are used like this:
1.23      crook    8416: 
1.26      crook    8417: @example
1.29      crook    8418: assert( @i{flag} )
1.26      crook    8419: @end example
1.23      crook    8420: 
1.26      crook    8421: The code between @code{assert(} and @code{)} should compute a flag, that
                   8422: should be true if everything is alright and false otherwise. It should
                   8423: not change anything else on the stack. The overall stack effect of the
                   8424: assertion is @code{( -- )}. E.g.
1.23      crook    8425: 
1.26      crook    8426: @example
                   8427: assert( 1 1 + 2 = ) \ what we learn in school
                   8428: assert( dup 0<> ) \ assert that the top of stack is not zero
                   8429: assert( false ) \ this code should not be reached
                   8430: @end example
1.23      crook    8431: 
1.26      crook    8432: The need for assertions is different at different times. During
                   8433: debugging, we want more checking, in production we sometimes care more
                   8434: for speed. Therefore, assertions can be turned off, i.e., the assertion
                   8435: becomes a comment. Depending on the importance of an assertion and the
                   8436: time it takes to check it, you may want to turn off some assertions and
                   8437: keep others turned on. Gforth provides several levels of assertions for
                   8438: this purpose:
1.23      crook    8439: 
1.44      crook    8440: 
1.26      crook    8441: doc-assert0(
                   8442: doc-assert1(
                   8443: doc-assert2(
                   8444: doc-assert3(
                   8445: doc-assert(
                   8446: doc-)
1.23      crook    8447: 
1.44      crook    8448: 
1.26      crook    8449: The variable @code{assert-level} specifies the highest assertions that
                   8450: are turned on. I.e., at the default @code{assert-level} of one,
                   8451: @code{assert0(} and @code{assert1(} assertions perform checking, while
                   8452: @code{assert2(} and @code{assert3(} assertions are treated as comments.
                   8453: 
                   8454: The value of @code{assert-level} is evaluated at compile-time, not at
                   8455: run-time. Therefore you cannot turn assertions on or off at run-time;
                   8456: you have to set the @code{assert-level} appropriately before compiling a
                   8457: piece of code. You can compile different pieces of code at different
                   8458: @code{assert-level}s (e.g., a trusted library at level 1 and
                   8459: newly-written code at level 3).
1.23      crook    8460: 
1.44      crook    8461: 
1.26      crook    8462: doc-assert-level
1.23      crook    8463: 
1.44      crook    8464: 
1.26      crook    8465: If an assertion fails, a message compatible with Emacs' compilation mode
                   8466: is produced and the execution is aborted (currently with @code{ABORT"}.
                   8467: If there is interest, we will introduce a special throw code. But if you
                   8468: intend to @code{catch} a specific condition, using @code{throw} is
                   8469: probably more appropriate than an assertion).
1.23      crook    8470: 
1.26      crook    8471: Definitions in ANS Forth for these assertion words are provided
                   8472: in @file{compat/assert.fs}.
1.23      crook    8473: 
                   8474: 
1.48      anton    8475: @node Singlestep Debugger,  , Assertions, Programming Tools
1.26      crook    8476: @subsection Singlestep Debugger
                   8477: @cindex singlestep Debugger
                   8478: @cindex debugging Singlestep
1.23      crook    8479: 
1.26      crook    8480: When you create a new word there's often the need to check whether it
                   8481: behaves correctly or not. You can do this by typing @code{dbg
                   8482: badword}. A debug session might look like this:
1.23      crook    8483: 
1.26      crook    8484: @example
                   8485: : badword 0 DO i . LOOP ;  ok
                   8486: 2 dbg badword 
                   8487: : badword  
                   8488: Scanning code...
1.23      crook    8489: 
1.26      crook    8490: Nesting debugger ready!
1.23      crook    8491: 
1.26      crook    8492: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
                   8493: 400D4740  8049F68 DO             -> [ 0 ] 
                   8494: 400D4744  804A0C8 i              -> [ 1 ] 00000 
                   8495: 400D4748 400C5E60 .              -> 0 [ 0 ] 
                   8496: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   8497: 400D4744  804A0C8 i              -> [ 1 ] 00001 
                   8498: 400D4748 400C5E60 .              -> 1 [ 0 ] 
                   8499: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   8500: 400D4758  804B384 ;              ->  ok
                   8501: @end example
1.23      crook    8502: 
1.26      crook    8503: Each line displayed is one step. You always have to hit return to
                   8504: execute the next word that is displayed. If you don't want to execute
                   8505: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
                   8506: an overview what keys are available:
1.23      crook    8507: 
1.26      crook    8508: @table @i
1.23      crook    8509: 
1.30      anton    8510: @item @key{RET}
1.26      crook    8511: Next; Execute the next word.
1.23      crook    8512: 
1.26      crook    8513: @item n
                   8514: Nest; Single step through next word.
1.5       anton    8515: 
1.26      crook    8516: @item u
                   8517: Unnest; Stop debugging and execute rest of word. If we got to this word
                   8518: with nest, continue debugging with the calling word.
1.5       anton    8519: 
1.26      crook    8520: @item d
                   8521: Done; Stop debugging and execute rest.
1.5       anton    8522: 
1.26      crook    8523: @item s
                   8524: Stop; Abort immediately.
1.5       anton    8525: 
1.26      crook    8526: @end table
1.5       anton    8527: 
1.26      crook    8528: Debugging large application with this mechanism is very difficult, because
                   8529: you have to nest very deeply into the program before the interesting part
                   8530: begins. This takes a lot of time. 
1.5       anton    8531: 
1.26      crook    8532: To do it more directly put a @code{BREAK:} command into your source code.
                   8533: When program execution reaches @code{BREAK:} the single step debugger is
                   8534: invoked and you have all the features described above.
1.23      crook    8535: 
1.26      crook    8536: If you have more than one part to debug it is useful to know where the
                   8537: program has stopped at the moment. You can do this by the 
                   8538: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
                   8539: string is typed out when the ``breakpoint'' is reached.
                   8540: 
1.44      crook    8541: 
1.26      crook    8542: doc-dbg
1.45      crook    8543: doc-break:
                   8544: doc-break"
1.26      crook    8545: 
                   8546: 
1.44      crook    8547: 
1.26      crook    8548: @c -------------------------------------------------------------
                   8549: @node Assembler and Code Words, Threading Words, Programming Tools, Words
                   8550: @section Assembler and Code Words
                   8551: @cindex assembler
                   8552: @cindex code words
1.5       anton    8553: 
1.52      anton    8554: @menu
1.53    ! anton    8555: * Code and ;code::              
        !          8556: * Common Assembler::            Assembler Syntax
1.52      anton    8557: * Common Disassembler::         
                   8558: * 386 Assembler::               Deviations and special cases
                   8559: * Alpha Assembler::             Deviations and special cases
                   8560: * MIPS assembler::              Deviations and special cases
1.53    ! anton    8561: * Other assemblers::            How to write them
1.52      anton    8562: @end menu
                   8563: 
1.53    ! anton    8564: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
        !          8565: @subsection @code{Code} and @code{;code}
1.52      anton    8566: 
1.26      crook    8567: Gforth provides some words for defining primitives (words written in
1.29      crook    8568: machine code), and for defining the machine-code equivalent of
1.26      crook    8569: @code{DOES>}-based defining words. However, the machine-independent
                   8570: nature of Gforth poses a few problems: First of all, Gforth runs on
                   8571: several architectures, so it can provide no standard assembler. What's
                   8572: worse is that the register allocation not only depends on the processor,
                   8573: but also on the @code{gcc} version and options used.
1.5       anton    8574: 
1.29      crook    8575: The words that Gforth offers encapsulate some system dependences (e.g.,
                   8576: the header structure), so a system-independent assembler may be used in
1.26      crook    8577: Gforth. If you do not have an assembler, you can compile machine code
1.29      crook    8578: directly with @code{,} and @code{c,}@footnote{This isn't portable,
                   8579: because these words emit stuff in @i{data} space; it works because
                   8580: Gforth has unified code/data spaces. Assembler isn't likely to be
                   8581: portable anyway.}.
1.5       anton    8582: 
1.44      crook    8583: 
1.26      crook    8584: doc-assembler
1.45      crook    8585: doc-init-asm
1.26      crook    8586: doc-code
                   8587: doc-end-code
                   8588: doc-;code
                   8589: doc-flush-icache
1.5       anton    8590: 
1.44      crook    8591: 
1.26      crook    8592: If @code{flush-icache} does not work correctly, @code{code} words
                   8593: etc. will not work (reliably), either.
1.5       anton    8594: 
1.29      crook    8595: The typical usage of these @code{code} words can be shown most easily by
                   8596: analogy to the equivalent high-level defining words:
                   8597: 
                   8598: @example
1.53    ! anton    8599: : foo                              code foo
        !          8600:    <high-level Forth words>              <assembler>
        !          8601: ;                                  end-code
        !          8602:                                 
        !          8603: : bar                              : bar
        !          8604:    <high-level Forth words>           <high-level Forth words>
        !          8605:    CREATE                             CREATE
        !          8606:       <high-level Forth words>           <high-level Forth words>
        !          8607:    DOES>                              ;code
        !          8608:       <high-level Forth words>           <assembler>
        !          8609: ;                                  end-code
1.29      crook    8610: @end example
                   8611: 
1.26      crook    8612: @code{flush-icache} is always present. The other words are rarely used
                   8613: and reside in @code{code.fs}, which is usually not loaded. You can load
                   8614: it with @code{require code.fs}.
1.5       anton    8615: 
1.26      crook    8616: @cindex registers of the inner interpreter
                   8617: In the assembly code you will want to refer to the inner interpreter's
                   8618: registers (e.g., the data stack pointer) and you may want to use other
                   8619: registers for temporary storage. Unfortunately, the register allocation
                   8620: is installation-dependent.
1.5       anton    8621: 
1.26      crook    8622: The easiest solution is to use explicit register declarations
                   8623: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
                   8624: GNU C Manual}) for all of the inner interpreter's registers: You have to
                   8625: compile Gforth with @code{-DFORCE_REG} (configure option
                   8626: @code{--enable-force-reg}) and the appropriate declarations must be
                   8627: present in the @code{machine.h} file (see @code{mips.h} for an example;
                   8628: you can find a full list of all declarable register symbols with
                   8629: @code{grep register engine.c}). If you give explicit registers to all
                   8630: variables that are declared at the beginning of @code{engine()}, you
                   8631: should be able to use the other caller-saved registers for temporary
                   8632: storage. Alternatively, you can use the @code{gcc} option
                   8633: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
                   8634: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
                   8635: (however, this restriction on register allocation may slow Gforth
                   8636: significantly).
1.5       anton    8637: 
1.26      crook    8638: If this solution is not viable (e.g., because @code{gcc} does not allow
                   8639: you to explicitly declare all the registers you need), you have to find
                   8640: out by looking at the code where the inner interpreter's registers
                   8641: reside and which registers can be used for temporary storage. You can
                   8642: get an assembly listing of the engine's code with @code{make engine.s}.
1.5       anton    8643: 
1.26      crook    8644: In any case, it is good practice to abstract your assembly code from the
                   8645: actual register allocation. E.g., if the data stack pointer resides in
                   8646: register @code{$17}, create an alias for this register called @code{sp},
                   8647: and use that in your assembly code.
1.5       anton    8648: 
1.26      crook    8649: @cindex code words, portable
                   8650: Another option for implementing normal and defining words efficiently
                   8651: is to add the desired functionality to the source of Gforth. For normal
                   8652: words you just have to edit @file{primitives} (@pxref{Automatic
                   8653: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
                   8654: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
                   8655: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.5       anton    8656: 
1.53    ! anton    8657: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
        !          8658: @subsection Common Assembler
        !          8659: 
        !          8660: The assemblers in Gforth generally use a postfix syntax, i.e., the
        !          8661: instruction name follows the operands.
        !          8662: 
        !          8663: The operands are passed in the usual order (the same that is used in the
        !          8664: manual of the architecture).  Since they all are Forth words, they have
        !          8665: to be separated by spaces; you can also use Forth words to compute the
        !          8666: operands.
        !          8667: 
        !          8668: The instruction names usually end with a @code{,}.  This makes it easier
        !          8669: to visually separate instructions if you put several of them on one
        !          8670: line; it also avoids shadowing other Forth words (e.g., @code{and}).
        !          8671: 
        !          8672: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
        !          8673: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
        !          8674: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
        !          8675: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
        !          8676: conditions are specified in a way specific to each assembler.
        !          8677: 
1.52      anton    8678: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
                   8679: @subsection Common Disassembler
                   8680: 
                   8681: You can disassemble a @code{code} word with @code{see}
                   8682: (@pxref{Debugging}).  You can disassemble a section of memory with
                   8683: 
                   8684: doc-disasm
                   8685: 
                   8686: The disassembler generally produces output that can be fed into the
                   8687: assembler (i.e., same syntax, etc.).  It also includes additional
1.53    ! anton    8688: information in comments.  In particular, the address of the instruction
        !          8689: is given in a comment before the instruction.
        !          8690: 
        !          8691: @code{See} may display more or less than the actual code of the word,
        !          8692: because the recognition of the end of the code is unreliable.  You can
        !          8693: use @code{disasm} if it did not display enough.  It may display more, if
        !          8694: the code word is not immediately followed by a named word.  If you have
        !          8695: something else there, you can follow the word with @code{align last @ ,}
        !          8696: to ensure that the end is recognized.
1.52      anton    8697: 
                   8698: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
                   8699: @subsection 386 Assembler
                   8700: 
                   8701: The 386 assembler and disassembler included in Gforth was written by
                   8702: Andrew McKewan; it is in the public domain.
                   8703: 
                   8704: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
                   8705: @subsection Alpha Assembler
                   8706: 
1.53    ! anton    8707: The Alpha assembler and disassembler was written by Bernd Thallner.
1.52      anton    8708: 
1.53    ! anton    8709: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
1.52      anton    8710: @subsection MIPS assembler
                   8711: 
                   8712: The MIPS assembler was originally written by Christian Pirker.
                   8713: 
                   8714: Currently the assembler and disassembler only cover the MIPS-I
                   8715: architecture (R3000), and don't support FP instructions.
                   8716: 
                   8717: Registers are specified by numbers, e.g., @code{1} (without preceding
                   8718: @code{$}).  You can also specify them by name, e.g. @code{$at}; however,
                   8719: @code{$a0}--@code{$a3} are not available, to avoid shadowing hex
                   8720: numbers.
                   8721: 
                   8722: Because there is no way to distinguish registers from immediate values,
                   8723: you have to explicitly use the immediate forms of instructions, i.e.,
                   8724: @code{addiu,}, not just @code{addu,} (@command{as} does this
                   8725: implicitly).
                   8726: 
                   8727: If the architecture manual specifies several formats for the instruction
                   8728: (e.g., for @code{jalr,}), you usually have to use the one with more
                   8729: arguments (i.e., two for @code{jalr,}).  When in doubt, see
                   8730: @code{arch/mips/testasm.fs} for an example of correct use.
                   8731: 
1.53    ! anton    8732: Branches and jumps in the MIPS architecture have a delay slot.  You have
        !          8733: to fill it yourself (the simplest way is to use @code{nop,}), the
        !          8734: assembler does not do it for you (unlike @command{as}).  Even
        !          8735: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
        !          8736: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
        !          8737: and @code{then,} just specify branch targets, they are not affected.
        !          8738: 
        !          8739: Note that you must not put branches, jumps, or @code{li,} into the delay
        !          8740: slot: @code{li,} may expand to several instructions, and control flow
        !          8741: instructions may not be put into the branch delay slot in any case.
1.52      anton    8742: 
                   8743: For branches the argument specifying the target is a relative address;
                   8744: You have to add the address of the delay slot to get the absolute
                   8745: address.
1.53    ! anton    8746: 
        !          8747: The MIPS architecture also has load delay slots and restrictions on
        !          8748: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
        !          8749: yourself to satisfy these restrictions, the assembler does not do it for
        !          8750: you.
        !          8751: 
        !          8752: You can specify the conditions for @code{if,} etc. by taking a
        !          8753: conditional branch and leaving away the @code{b} at the start and the
        !          8754: @code{,} at the end.  E.g.,
        !          8755: 
        !          8756: @example
        !          8757: 4 5 eq if,
        !          8758:   ... \ do something if $4 equals $5
        !          8759: then,
        !          8760: @end example
        !          8761: 
        !          8762: @node Other assemblers,  , MIPS assembler, Assembler and Code Words
        !          8763: @subsection Other assemblers
        !          8764: 
        !          8765: If you want to contribute another assembler/disassembler, please contact
        !          8766: us (@email{bug-gforth@@gnu.org}) to check if we have such an assembler
        !          8767: already.  If you are writing them from scratch, please use a similar
        !          8768: syntax style as the one we use (i.e., postfix, commas at the end of the
        !          8769: instruction names, @pxref{Common Assembler}); make the output of the
        !          8770: disassembler be valid input for the assembler, and keep the style
        !          8771: similar to the style we used.
        !          8772: 
        !          8773: Hints on implementation: The most important part is to have a good test
        !          8774: suite that contains all instructions.  Once you have that, the rest is
        !          8775: easy.  For actual coding you can take a look at
        !          8776: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
        !          8777: the assembler and disassembler, avoiding redundancy and some potential
        !          8778: bugs.  You can also look at that file (and @pxref{Advanced does> usage})
        !          8779: to get ideas how to factor a disassembler.
1.5       anton    8780: 
1.26      crook    8781: @c -------------------------------------------------------------
                   8782: @node Threading Words, Locals, Assembler and Code Words, Words
                   8783: @section Threading Words
                   8784: @cindex threading words
1.5       anton    8785: 
1.26      crook    8786: @cindex code address
                   8787: These words provide access to code addresses and other threading stuff
                   8788: in Gforth (and, possibly, other interpretive Forths). It more or less
                   8789: abstracts away the differences between direct and indirect threading
                   8790: (and, for direct threading, the machine dependences). However, at
                   8791: present this wordset is still incomplete. It is also pretty low-level;
                   8792: some day it will hopefully be made unnecessary by an internals wordset
                   8793: that abstracts implementation details away completely.
1.5       anton    8794: 
1.44      crook    8795: 
1.26      crook    8796: doc-threading-method
                   8797: doc->code-address
                   8798: doc->does-code
                   8799: doc-code-address!
                   8800: doc-does-code!
                   8801: doc-does-handler!
                   8802: doc-/does-handler
1.5       anton    8803: 
1.44      crook    8804: 
1.26      crook    8805: The code addresses produced by various defining words are produced by
                   8806: the following words:
1.5       anton    8807: 
1.44      crook    8808: 
1.26      crook    8809: doc-docol:
                   8810: doc-docon:
                   8811: doc-dovar:
                   8812: doc-douser:
                   8813: doc-dodefer:
                   8814: doc-dofield:
1.5       anton    8815: 
1.44      crook    8816: 
1.26      crook    8817: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
                   8818: with @code{>does-code}. If the word was defined in that way, the value
                   8819: returned is non-zero and identifies the @code{DOES>} used by the
                   8820: defining word.
                   8821: @comment TODO should that be ``identifies the xt of the DOES> ??''
1.5       anton    8822: 
1.26      crook    8823: @c -------------------------------------------------------------
                   8824: @node Locals, Structures, Threading Words, Words
                   8825: @section Locals
                   8826: @cindex locals
1.5       anton    8827: 
1.26      crook    8828: Local variables can make Forth programming more enjoyable and Forth
                   8829: programs easier to read. Unfortunately, the locals of ANS Forth are
                   8830: laden with restrictions. Therefore, we provide not only the ANS Forth
                   8831: locals wordset, but also our own, more powerful locals wordset (we
                   8832: implemented the ANS Forth locals wordset through our locals wordset).
1.5       anton    8833: 
1.26      crook    8834: The ideas in this section have also been published in the paper
                   8835: @cite{Automatic Scoping of Local Variables} by M. Anton Ertl, presented
                   8836: at EuroForth '94; it is available at
1.47      crook    8837: @*@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz}.
1.5       anton    8838: 
1.26      crook    8839: @menu
                   8840: * Gforth locals::               
                   8841: * ANS Forth locals::            
                   8842: @end menu
1.5       anton    8843: 
1.26      crook    8844: @node Gforth locals, ANS Forth locals, Locals, Locals
                   8845: @subsection Gforth locals
                   8846: @cindex Gforth locals
                   8847: @cindex locals, Gforth style
1.5       anton    8848: 
1.26      crook    8849: Locals can be defined with
1.5       anton    8850: 
                   8851: @example
1.26      crook    8852: @{ local1 local2 ... -- comment @}
                   8853: @end example
                   8854: or
                   8855: @example
                   8856: @{ local1 local2 ... @}
1.5       anton    8857: @end example
                   8858: 
1.26      crook    8859: E.g.,
1.5       anton    8860: @example
1.26      crook    8861: : max @{ n1 n2 -- n3 @}
                   8862:  n1 n2 > if
                   8863:    n1
                   8864:  else
                   8865:    n2
                   8866:  endif ;
1.5       anton    8867: @end example
                   8868: 
1.26      crook    8869: The similarity of locals definitions with stack comments is intended. A
                   8870: locals definition often replaces the stack comment of a word. The order
                   8871: of the locals corresponds to the order in a stack comment and everything
                   8872: after the @code{--} is really a comment.
1.5       anton    8873: 
1.26      crook    8874: This similarity has one disadvantage: It is too easy to confuse locals
                   8875: declarations with stack comments, causing bugs and making them hard to
                   8876: find. However, this problem can be avoided by appropriate coding
                   8877: conventions: Do not use both notations in the same program. If you do,
                   8878: they should be distinguished using additional means, e.g. by position.
                   8879: 
                   8880: @cindex types of locals
                   8881: @cindex locals types
                   8882: The name of the local may be preceded by a type specifier, e.g.,
                   8883: @code{F:} for a floating point value:
                   8884: 
                   8885: @example
                   8886: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
                   8887: \ complex multiplication
                   8888:  Ar Br f* Ai Bi f* f-
                   8889:  Ar Bi f* Ai Br f* f+ ;
                   8890: @end example
                   8891: 
                   8892: @cindex flavours of locals
                   8893: @cindex locals flavours
                   8894: @cindex value-flavoured locals
                   8895: @cindex variable-flavoured locals
                   8896: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
                   8897: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
                   8898: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
                   8899: with @code{W:}, @code{D:} etc.) produces its value and can be changed
                   8900: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
                   8901: produces its address (which becomes invalid when the variable's scope is
                   8902: left). E.g., the standard word @code{emit} can be defined in terms of
                   8903: @code{type} like this:
1.5       anton    8904: 
                   8905: @example
1.26      crook    8906: : emit @{ C^ char* -- @}
                   8907:     char* 1 type ;
1.5       anton    8908: @end example
                   8909: 
1.26      crook    8910: @cindex default type of locals
                   8911: @cindex locals, default type
                   8912: A local without type specifier is a @code{W:} local. Both flavours of
                   8913: locals are initialized with values from the data or FP stack.
1.5       anton    8914: 
1.26      crook    8915: Currently there is no way to define locals with user-defined data
                   8916: structures, but we are working on it.
1.5       anton    8917: 
1.26      crook    8918: Gforth allows defining locals everywhere in a colon definition. This
                   8919: poses the following questions:
1.5       anton    8920: 
1.26      crook    8921: @menu
                   8922: * Where are locals visible by name?::  
                   8923: * How long do locals live?::    
                   8924: * Programming Style::           
                   8925: * Implementation::              
                   8926: @end menu
1.5       anton    8927: 
1.26      crook    8928: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
                   8929: @subsubsection Where are locals visible by name?
                   8930: @cindex locals visibility
                   8931: @cindex visibility of locals
                   8932: @cindex scope of locals
1.5       anton    8933: 
1.26      crook    8934: Basically, the answer is that locals are visible where you would expect
                   8935: it in block-structured languages, and sometimes a little longer. If you
                   8936: want to restrict the scope of a local, enclose its definition in
                   8937: @code{SCOPE}...@code{ENDSCOPE}.
1.5       anton    8938: 
1.44      crook    8939: 
1.26      crook    8940: doc-scope
                   8941: doc-endscope
1.5       anton    8942: 
1.44      crook    8943: 
1.26      crook    8944: These words behave like control structure words, so you can use them
                   8945: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
                   8946: arbitrary ways.
1.5       anton    8947: 
1.26      crook    8948: If you want a more exact answer to the visibility question, here's the
                   8949: basic principle: A local is visible in all places that can only be
                   8950: reached through the definition of the local@footnote{In compiler
                   8951: construction terminology, all places dominated by the definition of the
                   8952: local.}. In other words, it is not visible in places that can be reached
                   8953: without going through the definition of the local. E.g., locals defined
                   8954: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
                   8955: defined in @code{BEGIN}...@code{UNTIL} are visible after the
                   8956: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.5       anton    8957: 
1.26      crook    8958: The reasoning behind this solution is: We want to have the locals
                   8959: visible as long as it is meaningful. The user can always make the
                   8960: visibility shorter by using explicit scoping. In a place that can
                   8961: only be reached through the definition of a local, the meaning of a
                   8962: local name is clear. In other places it is not: How is the local
                   8963: initialized at the control flow path that does not contain the
                   8964: definition? Which local is meant, if the same name is defined twice in
                   8965: two independent control flow paths?
1.5       anton    8966: 
1.26      crook    8967: This should be enough detail for nearly all users, so you can skip the
                   8968: rest of this section. If you really must know all the gory details and
                   8969: options, read on.
1.5       anton    8970: 
1.26      crook    8971: In order to implement this rule, the compiler has to know which places
                   8972: are unreachable. It knows this automatically after @code{AHEAD},
                   8973: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
                   8974: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
                   8975: compiler that the control flow never reaches that place. If
                   8976: @code{UNREACHABLE} is not used where it could, the only consequence is
                   8977: that the visibility of some locals is more limited than the rule above
                   8978: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
                   8979: lie to the compiler), buggy code will be produced.
1.5       anton    8980: 
1.44      crook    8981: 
1.26      crook    8982: doc-unreachable
1.5       anton    8983: 
1.44      crook    8984: 
1.26      crook    8985: Another problem with this rule is that at @code{BEGIN}, the compiler
                   8986: does not know which locals will be visible on the incoming
                   8987: back-edge. All problems discussed in the following are due to this
                   8988: ignorance of the compiler (we discuss the problems using @code{BEGIN}
                   8989: loops as examples; the discussion also applies to @code{?DO} and other
                   8990: loops). Perhaps the most insidious example is:
1.5       anton    8991: @example
1.26      crook    8992: AHEAD
                   8993: BEGIN
                   8994:   x
                   8995: [ 1 CS-ROLL ] THEN
                   8996:   @{ x @}
                   8997:   ...
                   8998: UNTIL
                   8999: @end example
1.5       anton    9000: 
1.26      crook    9001: This should be legal according to the visibility rule. The use of
                   9002: @code{x} can only be reached through the definition; but that appears
                   9003: textually below the use.
1.5       anton    9004: 
1.26      crook    9005: From this example it is clear that the visibility rules cannot be fully
                   9006: implemented without major headaches. Our implementation treats common
                   9007: cases as advertised and the exceptions are treated in a safe way: The
                   9008: compiler makes a reasonable guess about the locals visible after a
                   9009: @code{BEGIN}; if it is too pessimistic, the
                   9010: user will get a spurious error about the local not being defined; if the
                   9011: compiler is too optimistic, it will notice this later and issue a
                   9012: warning. In the case above the compiler would complain about @code{x}
                   9013: being undefined at its use. You can see from the obscure examples in
                   9014: this section that it takes quite unusual control structures to get the
                   9015: compiler into trouble, and even then it will often do fine.
1.5       anton    9016: 
1.26      crook    9017: If the @code{BEGIN} is reachable from above, the most optimistic guess
                   9018: is that all locals visible before the @code{BEGIN} will also be
                   9019: visible after the @code{BEGIN}. This guess is valid for all loops that
                   9020: are entered only through the @code{BEGIN}, in particular, for normal
                   9021: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
                   9022: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
                   9023: compiler. When the branch to the @code{BEGIN} is finally generated by
                   9024: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
                   9025: warns the user if it was too optimistic:
                   9026: @example
                   9027: IF
                   9028:   @{ x @}
                   9029: BEGIN
                   9030:   \ x ? 
                   9031: [ 1 cs-roll ] THEN
                   9032:   ...
                   9033: UNTIL
1.5       anton    9034: @end example
                   9035: 
1.26      crook    9036: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
                   9037: optimistically assumes that it lives until the @code{THEN}. It notices
                   9038: this difference when it compiles the @code{UNTIL} and issues a
                   9039: warning. The user can avoid the warning, and make sure that @code{x}
                   9040: is not used in the wrong area by using explicit scoping:
                   9041: @example
                   9042: IF
                   9043:   SCOPE
                   9044:   @{ x @}
                   9045:   ENDSCOPE
                   9046: BEGIN
                   9047: [ 1 cs-roll ] THEN
                   9048:   ...
                   9049: UNTIL
                   9050: @end example
1.5       anton    9051: 
1.26      crook    9052: Since the guess is optimistic, there will be no spurious error messages
                   9053: about undefined locals.
1.5       anton    9054: 
1.26      crook    9055: If the @code{BEGIN} is not reachable from above (e.g., after
                   9056: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
                   9057: optimistic guess, as the locals visible after the @code{BEGIN} may be
                   9058: defined later. Therefore, the compiler assumes that no locals are
                   9059: visible after the @code{BEGIN}. However, the user can use
                   9060: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
                   9061: visible at the BEGIN as at the point where the top control-flow stack
                   9062: item was created.
1.5       anton    9063: 
1.44      crook    9064: 
1.26      crook    9065: doc-assume-live
1.5       anton    9066: 
1.44      crook    9067: 
                   9068: @noindent
1.26      crook    9069: E.g.,
1.5       anton    9070: @example
1.26      crook    9071: @{ x @}
                   9072: AHEAD
                   9073: ASSUME-LIVE
                   9074: BEGIN
                   9075:   x
                   9076: [ 1 CS-ROLL ] THEN
                   9077:   ...
                   9078: UNTIL
1.5       anton    9079: @end example
                   9080: 
1.26      crook    9081: Other cases where the locals are defined before the @code{BEGIN} can be
                   9082: handled by inserting an appropriate @code{CS-ROLL} before the
                   9083: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
                   9084: behind the @code{ASSUME-LIVE}).
1.5       anton    9085: 
1.26      crook    9086: Cases where locals are defined after the @code{BEGIN} (but should be
                   9087: visible immediately after the @code{BEGIN}) can only be handled by
                   9088: rearranging the loop. E.g., the ``most insidious'' example above can be
                   9089: arranged into:
1.5       anton    9090: @example
1.26      crook    9091: BEGIN
                   9092:   @{ x @}
                   9093:   ... 0=
                   9094: WHILE
                   9095:   x
                   9096: REPEAT
1.5       anton    9097: @end example
                   9098: 
1.26      crook    9099: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
                   9100: @subsubsection How long do locals live?
                   9101: @cindex locals lifetime
                   9102: @cindex lifetime of locals
1.5       anton    9103: 
1.26      crook    9104: The right answer for the lifetime question would be: A local lives at
                   9105: least as long as it can be accessed. For a value-flavoured local this
                   9106: means: until the end of its visibility. However, a variable-flavoured
                   9107: local could be accessed through its address far beyond its visibility
                   9108: scope. Ultimately, this would mean that such locals would have to be
                   9109: garbage collected. Since this entails un-Forth-like implementation
                   9110: complexities, I adopted the same cowardly solution as some other
                   9111: languages (e.g., C): The local lives only as long as it is visible;
                   9112: afterwards its address is invalid (and programs that access it
                   9113: afterwards are erroneous).
1.5       anton    9114: 
1.26      crook    9115: @node Programming Style, Implementation, How long do locals live?, Gforth locals
                   9116: @subsubsection Programming Style
                   9117: @cindex locals programming style
                   9118: @cindex programming style, locals
1.5       anton    9119: 
1.26      crook    9120: The freedom to define locals anywhere has the potential to change
                   9121: programming styles dramatically. In particular, the need to use the
                   9122: return stack for intermediate storage vanishes. Moreover, all stack
                   9123: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
                   9124: determined arguments) can be eliminated: If the stack items are in the
                   9125: wrong order, just write a locals definition for all of them; then
                   9126: write the items in the order you want.
1.5       anton    9127: 
1.26      crook    9128: This seems a little far-fetched and eliminating stack manipulations is
                   9129: unlikely to become a conscious programming objective. Still, the number
                   9130: of stack manipulations will be reduced dramatically if local variables
1.49      anton    9131: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
1.26      crook    9132: a traditional implementation of @code{max}).
1.5       anton    9133: 
1.26      crook    9134: This shows one potential benefit of locals: making Forth programs more
                   9135: readable. Of course, this benefit will only be realized if the
                   9136: programmers continue to honour the principle of factoring instead of
                   9137: using the added latitude to make the words longer.
1.5       anton    9138: 
1.26      crook    9139: @cindex single-assignment style for locals
                   9140: Using @code{TO} can and should be avoided.  Without @code{TO},
                   9141: every value-flavoured local has only a single assignment and many
                   9142: advantages of functional languages apply to Forth. I.e., programs are
                   9143: easier to analyse, to optimize and to read: It is clear from the
                   9144: definition what the local stands for, it does not turn into something
                   9145: different later.
1.5       anton    9146: 
1.26      crook    9147: E.g., a definition using @code{TO} might look like this:
1.5       anton    9148: @example
1.26      crook    9149: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9150:  u1 u2 min 0
                   9151:  ?do
                   9152:    addr1 c@@ addr2 c@@ -
                   9153:    ?dup-if
                   9154:      unloop exit
                   9155:    then
                   9156:    addr1 char+ TO addr1
                   9157:    addr2 char+ TO addr2
                   9158:  loop
                   9159:  u1 u2 - ;
1.5       anton    9160: @end example
1.26      crook    9161: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
                   9162: every loop iteration. @code{strcmp} is a typical example of the
                   9163: readability problems of using @code{TO}. When you start reading
                   9164: @code{strcmp}, you think that @code{addr1} refers to the start of the
                   9165: string. Only near the end of the loop you realize that it is something
                   9166: else.
1.5       anton    9167: 
1.26      crook    9168: This can be avoided by defining two locals at the start of the loop that
                   9169: are initialized with the right value for the current iteration.
1.5       anton    9170: @example
1.26      crook    9171: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9172:  addr1 addr2
                   9173:  u1 u2 min 0 
                   9174:  ?do @{ s1 s2 @}
                   9175:    s1 c@@ s2 c@@ -
                   9176:    ?dup-if
                   9177:      unloop exit
                   9178:    then
                   9179:    s1 char+ s2 char+
                   9180:  loop
                   9181:  2drop
                   9182:  u1 u2 - ;
1.5       anton    9183: @end example
1.26      crook    9184: Here it is clear from the start that @code{s1} has a different value
                   9185: in every loop iteration.
1.5       anton    9186: 
1.26      crook    9187: @node Implementation,  , Programming Style, Gforth locals
                   9188: @subsubsection Implementation
                   9189: @cindex locals implementation
                   9190: @cindex implementation of locals
1.5       anton    9191: 
1.26      crook    9192: @cindex locals stack
                   9193: Gforth uses an extra locals stack. The most compelling reason for
                   9194: this is that the return stack is not float-aligned; using an extra stack
                   9195: also eliminates the problems and restrictions of using the return stack
                   9196: as locals stack. Like the other stacks, the locals stack grows toward
                   9197: lower addresses. A few primitives allow an efficient implementation:
1.5       anton    9198: 
1.44      crook    9199: 
1.26      crook    9200: doc-@local#
                   9201: doc-f@local#
                   9202: doc-laddr#
                   9203: doc-lp+!#
                   9204: doc-lp!
                   9205: doc->l
                   9206: doc-f>l
1.5       anton    9207: 
1.44      crook    9208: 
1.26      crook    9209: In addition to these primitives, some specializations of these
                   9210: primitives for commonly occurring inline arguments are provided for
                   9211: efficiency reasons, e.g., @code{@@local0} as specialization of
                   9212: @code{@@local#} for the inline argument 0. The following compiling words
                   9213: compile the right specialized version, or the general version, as
                   9214: appropriate:
1.6       pazsan   9215: 
1.44      crook    9216: 
1.26      crook    9217: doc-compile-@local
                   9218: doc-compile-f@local
                   9219: doc-compile-lp+!
1.12      anton    9220: 
1.44      crook    9221: 
1.26      crook    9222: Combinations of conditional branches and @code{lp+!#} like
                   9223: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
                   9224: is taken) are provided for efficiency and correctness in loops.
1.6       pazsan   9225: 
1.26      crook    9226: A special area in the dictionary space is reserved for keeping the
                   9227: local variable names. @code{@{} switches the dictionary pointer to this
                   9228: area and @code{@}} switches it back and generates the locals
                   9229: initializing code. @code{W:} etc.@ are normal defining words. This
                   9230: special area is cleared at the start of every colon definition.
1.6       pazsan   9231: 
1.26      crook    9232: @cindex word list for defining locals
                   9233: A special feature of Gforth's dictionary is used to implement the
                   9234: definition of locals without type specifiers: every word list (aka
                   9235: vocabulary) has its own methods for searching
                   9236: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
                   9237: with a special search method: When it is searched for a word, it
                   9238: actually creates that word using @code{W:}. @code{@{} changes the search
                   9239: order to first search the word list containing @code{@}}, @code{W:} etc.,
                   9240: and then the word list for defining locals without type specifiers.
1.12      anton    9241: 
1.26      crook    9242: The lifetime rules support a stack discipline within a colon
                   9243: definition: The lifetime of a local is either nested with other locals
                   9244: lifetimes or it does not overlap them.
1.6       pazsan   9245: 
1.26      crook    9246: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
                   9247: pointer manipulation is generated. Between control structure words
                   9248: locals definitions can push locals onto the locals stack. @code{AGAIN}
                   9249: is the simplest of the other three control flow words. It has to
                   9250: restore the locals stack depth of the corresponding @code{BEGIN}
                   9251: before branching. The code looks like this:
                   9252: @format
                   9253: @code{lp+!#} current-locals-size @minus{} dest-locals-size
                   9254: @code{branch} <begin>
                   9255: @end format
1.6       pazsan   9256: 
1.26      crook    9257: @code{UNTIL} is a little more complicated: If it branches back, it
                   9258: must adjust the stack just like @code{AGAIN}. But if it falls through,
                   9259: the locals stack must not be changed. The compiler generates the
                   9260: following code:
                   9261: @format
                   9262: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
                   9263: @end format
                   9264: The locals stack pointer is only adjusted if the branch is taken.
1.6       pazsan   9265: 
1.26      crook    9266: @code{THEN} can produce somewhat inefficient code:
                   9267: @format
                   9268: @code{lp+!#} current-locals-size @minus{} orig-locals-size
                   9269: <orig target>:
                   9270: @code{lp+!#} orig-locals-size @minus{} new-locals-size
                   9271: @end format
                   9272: The second @code{lp+!#} adjusts the locals stack pointer from the
1.29      crook    9273: level at the @i{orig} point to the level after the @code{THEN}. The
1.26      crook    9274: first @code{lp+!#} adjusts the locals stack pointer from the current
                   9275: level to the level at the orig point, so the complete effect is an
                   9276: adjustment from the current level to the right level after the
                   9277: @code{THEN}.
1.6       pazsan   9278: 
1.26      crook    9279: @cindex locals information on the control-flow stack
                   9280: @cindex control-flow stack items, locals information
                   9281: In a conventional Forth implementation a dest control-flow stack entry
                   9282: is just the target address and an orig entry is just the address to be
                   9283: patched. Our locals implementation adds a word list to every orig or dest
                   9284: item. It is the list of locals visible (or assumed visible) at the point
                   9285: described by the entry. Our implementation also adds a tag to identify
                   9286: the kind of entry, in particular to differentiate between live and dead
                   9287: (reachable and unreachable) orig entries.
1.6       pazsan   9288: 
1.26      crook    9289: A few unusual operations have to be performed on locals word lists:
1.6       pazsan   9290: 
1.44      crook    9291: 
1.26      crook    9292: doc-common-list
                   9293: doc-sub-list?
                   9294: doc-list-size
1.6       pazsan   9295: 
1.44      crook    9296: 
1.26      crook    9297: Several features of our locals word list implementation make these
                   9298: operations easy to implement: The locals word lists are organised as
                   9299: linked lists; the tails of these lists are shared, if the lists
                   9300: contain some of the same locals; and the address of a name is greater
                   9301: than the address of the names behind it in the list.
1.6       pazsan   9302: 
1.26      crook    9303: Another important implementation detail is the variable
                   9304: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
                   9305: determine if they can be reached directly or only through the branch
                   9306: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
                   9307: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
                   9308: definition, by @code{BEGIN} and usually by @code{THEN}.
1.6       pazsan   9309: 
1.26      crook    9310: Counted loops are similar to other loops in most respects, but
                   9311: @code{LEAVE} requires special attention: It performs basically the same
                   9312: service as @code{AHEAD}, but it does not create a control-flow stack
                   9313: entry. Therefore the information has to be stored elsewhere;
                   9314: traditionally, the information was stored in the target fields of the
                   9315: branches created by the @code{LEAVE}s, by organizing these fields into a
                   9316: linked list. Unfortunately, this clever trick does not provide enough
                   9317: space for storing our extended control flow information. Therefore, we
                   9318: introduce another stack, the leave stack. It contains the control-flow
                   9319: stack entries for all unresolved @code{LEAVE}s.
1.6       pazsan   9320: 
1.26      crook    9321: Local names are kept until the end of the colon definition, even if
                   9322: they are no longer visible in any control-flow path. In a few cases
                   9323: this may lead to increased space needs for the locals name area, but
                   9324: usually less than reclaiming this space would cost in code size.
1.6       pazsan   9325: 
                   9326: 
1.26      crook    9327: @node ANS Forth locals,  , Gforth locals, Locals
                   9328: @subsection ANS Forth locals
                   9329: @cindex locals, ANS Forth style
1.6       pazsan   9330: 
1.26      crook    9331: The ANS Forth locals wordset does not define a syntax for locals, but
                   9332: words that make it possible to define various syntaxes. One of the
                   9333: possible syntaxes is a subset of the syntax we used in the Gforth locals
                   9334: wordset, i.e.:
1.6       pazsan   9335: 
                   9336: @example
1.26      crook    9337: @{ local1 local2 ... -- comment @}
1.6       pazsan   9338: @end example
1.23      crook    9339: @noindent
1.26      crook    9340: or
1.6       pazsan   9341: @example
1.26      crook    9342: @{ local1 local2 ... @}
1.6       pazsan   9343: @end example
                   9344: 
1.26      crook    9345: The order of the locals corresponds to the order in a stack comment. The
                   9346: restrictions are:
1.6       pazsan   9347: 
                   9348: @itemize @bullet
                   9349: @item
1.26      crook    9350: Locals can only be cell-sized values (no type specifiers are allowed).
1.6       pazsan   9351: @item
1.26      crook    9352: Locals can be defined only outside control structures.
1.6       pazsan   9353: @item
1.26      crook    9354: Locals can interfere with explicit usage of the return stack. For the
                   9355: exact (and long) rules, see the standard. If you don't use return stack
                   9356: accessing words in a definition using locals, you will be all right. The
                   9357: purpose of this rule is to make locals implementation on the return
                   9358: stack easier.
1.6       pazsan   9359: @item
1.26      crook    9360: The whole definition must be in one line.
                   9361: @end itemize
1.6       pazsan   9362: 
1.44      crook    9363: Locals defined in this way behave like @code{VALUE}s
1.49      anton    9364: (@pxref{Values}). I.e., they are initialized from the stack. Using their
1.26      crook    9365: name produces their value. Their value can be changed using @code{TO}.
1.6       pazsan   9366: 
1.26      crook    9367: Since this syntax is supported by Gforth directly, you need not do
                   9368: anything to use it. If you want to port a program using this syntax to
                   9369: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
                   9370: syntax on the other system.
1.6       pazsan   9371: 
1.26      crook    9372: Note that a syntax shown in the standard, section A.13 looks
                   9373: similar, but is quite different in having the order of locals
                   9374: reversed. Beware!
1.6       pazsan   9375: 
1.26      crook    9376: The ANS Forth locals wordset itself consists of a word:
1.6       pazsan   9377: 
1.44      crook    9378: 
1.26      crook    9379: doc-(local)
1.6       pazsan   9380: 
1.44      crook    9381: 
1.26      crook    9382: The ANS Forth locals extension wordset defines a syntax using @code{locals|}, but it is so
                   9383: awful that we strongly recommend not to use it. We have implemented this
                   9384: syntax to make porting to Gforth easy, but do not document it here. The
                   9385: problem with this syntax is that the locals are defined in an order
                   9386: reversed with respect to the standard stack comment notation, making
                   9387: programs harder to read, and easier to misread and miswrite. The only
                   9388: merit of this syntax is that it is easy to implement using the ANS Forth
                   9389: locals wordset.
1.7       pazsan   9390: 
                   9391: 
1.26      crook    9392: @c ----------------------------------------------------------
                   9393: @node Structures, Object-oriented Forth, Locals, Words
                   9394: @section  Structures
                   9395: @cindex structures
                   9396: @cindex records
1.7       pazsan   9397: 
1.26      crook    9398: This section presents the structure package that comes with Gforth. A
                   9399: version of the package implemented in ANS Forth is available in
                   9400: @file{compat/struct.fs}. This package was inspired by a posting on
                   9401: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
                   9402: possibly John Hayes). A version of this section has been published in
                   9403: ???. Marcel Hendrix provided helpful comments.
1.7       pazsan   9404: 
1.26      crook    9405: @menu
                   9406: * Why explicit structure support?::  
                   9407: * Structure Usage::             
                   9408: * Structure Naming Convention::  
                   9409: * Structure Implementation::    
                   9410: * Structure Glossary::          
                   9411: @end menu
1.7       pazsan   9412: 
1.26      crook    9413: @node Why explicit structure support?, Structure Usage, Structures, Structures
                   9414: @subsection Why explicit structure support?
1.7       pazsan   9415: 
1.26      crook    9416: @cindex address arithmetic for structures
                   9417: @cindex structures using address arithmetic
                   9418: If we want to use a structure containing several fields, we could simply
                   9419: reserve memory for it, and access the fields using address arithmetic
1.32      anton    9420: (@pxref{Address arithmetic}). As an example, consider a structure with
1.26      crook    9421: the following fields
1.7       pazsan   9422: 
1.26      crook    9423: @table @code
                   9424: @item a
                   9425: is a float
                   9426: @item b
                   9427: is a cell
                   9428: @item c
                   9429: is a float
                   9430: @end table
1.7       pazsan   9431: 
1.26      crook    9432: Given the (float-aligned) base address of the structure we get the
                   9433: address of the field
1.13      pazsan   9434: 
1.26      crook    9435: @table @code
                   9436: @item a
                   9437: without doing anything further.
                   9438: @item b
                   9439: with @code{float+}
                   9440: @item c
                   9441: with @code{float+ cell+ faligned}
                   9442: @end table
1.13      pazsan   9443: 
1.26      crook    9444: It is easy to see that this can become quite tiring. 
1.13      pazsan   9445: 
1.26      crook    9446: Moreover, it is not very readable, because seeing a
                   9447: @code{cell+} tells us neither which kind of structure is
                   9448: accessed nor what field is accessed; we have to somehow infer the kind
                   9449: of structure, and then look up in the documentation, which field of
                   9450: that structure corresponds to that offset.
1.13      pazsan   9451: 
1.26      crook    9452: Finally, this kind of address arithmetic also causes maintenance
                   9453: troubles: If you add or delete a field somewhere in the middle of the
                   9454: structure, you have to find and change all computations for the fields
                   9455: afterwards.
1.13      pazsan   9456: 
1.26      crook    9457: So, instead of using @code{cell+} and friends directly, how
                   9458: about storing the offsets in constants:
1.13      pazsan   9459: 
                   9460: @example
1.26      crook    9461: 0 constant a-offset
                   9462: 0 float+ constant b-offset
                   9463: 0 float+ cell+ faligned c-offset
1.13      pazsan   9464: @end example
                   9465: 
1.26      crook    9466: Now we can get the address of field @code{x} with @code{x-offset
                   9467: +}. This is much better in all respects. Of course, you still
                   9468: have to change all later offset definitions if you add a field. You can
                   9469: fix this by declaring the offsets in the following way:
1.13      pazsan   9470: 
                   9471: @example
1.26      crook    9472: 0 constant a-offset
                   9473: a-offset float+ constant b-offset
                   9474: b-offset cell+ faligned constant c-offset
1.13      pazsan   9475: @end example
                   9476: 
1.26      crook    9477: Since we always use the offsets with @code{+}, we could use a defining
                   9478: word @code{cfield} that includes the @code{+} in the action of the
                   9479: defined word:
1.8       pazsan   9480: 
                   9481: @example
1.26      crook    9482: : cfield ( n "name" -- )
                   9483:     create ,
                   9484: does> ( name execution: addr1 -- addr2 )
                   9485:     @@ + ;
1.13      pazsan   9486: 
1.26      crook    9487: 0 cfield a
                   9488: 0 a float+ cfield b
                   9489: 0 b cell+ faligned cfield c
1.13      pazsan   9490: @end example
                   9491: 
1.26      crook    9492: Instead of @code{x-offset +}, we now simply write @code{x}.
                   9493: 
                   9494: The structure field words now can be used quite nicely. However,
                   9495: their definition is still a bit cumbersome: We have to repeat the
                   9496: name, the information about size and alignment is distributed before
                   9497: and after the field definitions etc.  The structure package presented
                   9498: here addresses these problems.
                   9499: 
                   9500: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
                   9501: @subsection Structure Usage
                   9502: @cindex structure usage
1.13      pazsan   9503: 
1.26      crook    9504: @cindex @code{field} usage
                   9505: @cindex @code{struct} usage
                   9506: @cindex @code{end-struct} usage
                   9507: You can define a structure for a (data-less) linked list with:
1.13      pazsan   9508: @example
1.26      crook    9509: struct
                   9510:     cell% field list-next
                   9511: end-struct list%
1.13      pazsan   9512: @end example
                   9513: 
1.26      crook    9514: With the address of the list node on the stack, you can compute the
                   9515: address of the field that contains the address of the next node with
                   9516: @code{list-next}. E.g., you can determine the length of a list
                   9517: with:
1.13      pazsan   9518: 
                   9519: @example
1.26      crook    9520: : list-length ( list -- n )
                   9521: \ "list" is a pointer to the first element of a linked list
                   9522: \ "n" is the length of the list
                   9523:     0 BEGIN ( list1 n1 )
                   9524:         over
                   9525:     WHILE ( list1 n1 )
                   9526:         1+ swap list-next @@ swap
                   9527:     REPEAT
                   9528:     nip ;
1.13      pazsan   9529: @end example
                   9530: 
1.26      crook    9531: You can reserve memory for a list node in the dictionary with
                   9532: @code{list% %allot}, which leaves the address of the list node on the
                   9533: stack. For the equivalent allocation on the heap you can use @code{list%
                   9534: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
                   9535: use @code{list% %allocate}). You can get the the size of a list
                   9536: node with @code{list% %size} and its alignment with @code{list%
                   9537: %alignment}.
1.13      pazsan   9538: 
1.26      crook    9539: Note that in ANS Forth the body of a @code{create}d word is
                   9540: @code{aligned} but not necessarily @code{faligned};
                   9541: therefore, if you do a:
1.13      pazsan   9542: @example
1.26      crook    9543: create @emph{name} foo% %allot
1.8       pazsan   9544: @end example
                   9545: 
1.26      crook    9546: @noindent
                   9547: then the memory alloted for @code{foo%} is
                   9548: guaranteed to start at the body of @code{@emph{name}} only if
                   9549: @code{foo%} contains only character, cell and double fields.
1.20      pazsan   9550: 
1.45      crook    9551: @cindex structures containing structures
1.26      crook    9552: You can include a structure @code{foo%} as a field of
                   9553: another structure, like this:
1.20      pazsan   9554: @example
1.26      crook    9555: struct
                   9556: ...
                   9557:     foo% field ...
                   9558: ...
                   9559: end-struct ...
1.20      pazsan   9560: @end example
                   9561: 
1.26      crook    9562: @cindex structure extension
                   9563: @cindex extended records
                   9564: Instead of starting with an empty structure, you can extend an
                   9565: existing structure. E.g., a plain linked list without data, as defined
                   9566: above, is hardly useful; You can extend it to a linked list of integers,
                   9567: like this:@footnote{This feature is also known as @emph{extended
                   9568: records}. It is the main innovation in the Oberon language; in other
                   9569: words, adding this feature to Modula-2 led Wirth to create a new
                   9570: language, write a new compiler etc.  Adding this feature to Forth just
                   9571: required a few lines of code.}
1.20      pazsan   9572: 
                   9573: @example
1.26      crook    9574: list%
                   9575:     cell% field intlist-int
                   9576: end-struct intlist%
1.20      pazsan   9577: @end example
                   9578: 
1.26      crook    9579: @code{intlist%} is a structure with two fields:
                   9580: @code{list-next} and @code{intlist-int}.
1.20      pazsan   9581: 
1.26      crook    9582: @cindex structures containing arrays
                   9583: You can specify an array type containing @emph{n} elements of
                   9584: type @code{foo%} like this:
1.20      pazsan   9585: 
                   9586: @example
1.26      crook    9587: foo% @emph{n} *
1.20      pazsan   9588: @end example
                   9589: 
1.26      crook    9590: You can use this array type in any place where you can use a normal
                   9591: type, e.g., when defining a @code{field}, or with
                   9592: @code{%allot}.
1.20      pazsan   9593: 
1.26      crook    9594: @cindex first field optimization
                   9595: The first field is at the base address of a structure and the word
                   9596: for this field (e.g., @code{list-next}) actually does not change
                   9597: the address on the stack. You may be tempted to leave it away in the
                   9598: interest of run-time and space efficiency. This is not necessary,
                   9599: because the structure package optimizes this case and compiling such
                   9600: words does not generate any code. So, in the interest of readability
                   9601: and maintainability you should include the word for the field when
                   9602: accessing the field.
1.20      pazsan   9603: 
1.26      crook    9604: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
                   9605: @subsection Structure Naming Convention
                   9606: @cindex structure naming convention
1.20      pazsan   9607: 
1.26      crook    9608: The field names that come to (my) mind are often quite generic, and,
                   9609: if used, would cause frequent name clashes. E.g., many structures
                   9610: probably contain a @code{counter} field. The structure names
                   9611: that come to (my) mind are often also the logical choice for the names
                   9612: of words that create such a structure.
1.20      pazsan   9613: 
1.26      crook    9614: Therefore, I have adopted the following naming conventions: 
1.20      pazsan   9615: 
1.26      crook    9616: @itemize @bullet
                   9617: @cindex field naming convention
                   9618: @item
                   9619: The names of fields are of the form
                   9620: @code{@emph{struct}-@emph{field}}, where
                   9621: @code{@emph{struct}} is the basic name of the structure, and
                   9622: @code{@emph{field}} is the basic name of the field. You can
                   9623: think of field words as converting the (address of the)
                   9624: structure into the (address of the) field.
1.20      pazsan   9625: 
1.26      crook    9626: @cindex structure naming convention
                   9627: @item
                   9628: The names of structures are of the form
                   9629: @code{@emph{struct}%}, where
                   9630: @code{@emph{struct}} is the basic name of the structure.
                   9631: @end itemize
1.20      pazsan   9632: 
1.26      crook    9633: This naming convention does not work that well for fields of extended
                   9634: structures; e.g., the integer list structure has a field
                   9635: @code{intlist-int}, but has @code{list-next}, not
                   9636: @code{intlist-next}.
1.20      pazsan   9637: 
1.26      crook    9638: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
                   9639: @subsection Structure Implementation
                   9640: @cindex structure implementation
                   9641: @cindex implementation of structures
1.20      pazsan   9642: 
1.26      crook    9643: The central idea in the implementation is to pass the data about the
                   9644: structure being built on the stack, not in some global
                   9645: variable. Everything else falls into place naturally once this design
                   9646: decision is made.
1.20      pazsan   9647: 
1.26      crook    9648: The type description on the stack is of the form @emph{align
                   9649: size}. Keeping the size on the top-of-stack makes dealing with arrays
                   9650: very simple.
1.20      pazsan   9651: 
1.26      crook    9652: @code{field} is a defining word that uses @code{Create}
                   9653: and @code{DOES>}. The body of the field contains the offset
                   9654: of the field, and the normal @code{DOES>} action is simply:
1.20      pazsan   9655: 
                   9656: @example
1.48      anton    9657: @@ +
1.20      pazsan   9658: @end example
                   9659: 
1.23      crook    9660: @noindent
1.26      crook    9661: i.e., add the offset to the address, giving the stack effect
1.29      crook    9662: @i{addr1 -- addr2} for a field.
1.20      pazsan   9663: 
1.26      crook    9664: @cindex first field optimization, implementation
                   9665: This simple structure is slightly complicated by the optimization
                   9666: for fields with offset 0, which requires a different
                   9667: @code{DOES>}-part (because we cannot rely on there being
                   9668: something on the stack if such a field is invoked during
                   9669: compilation). Therefore, we put the different @code{DOES>}-parts
                   9670: in separate words, and decide which one to invoke based on the
                   9671: offset. For a zero offset, the field is basically a noop; it is
                   9672: immediate, and therefore no code is generated when it is compiled.
1.20      pazsan   9673: 
1.26      crook    9674: @node Structure Glossary,  , Structure Implementation, Structures
                   9675: @subsection Structure Glossary
                   9676: @cindex structure glossary
1.20      pazsan   9677: 
1.44      crook    9678: 
1.26      crook    9679: doc-%align
                   9680: doc-%alignment
                   9681: doc-%alloc
                   9682: doc-%allocate
                   9683: doc-%allot
                   9684: doc-cell%
                   9685: doc-char%
                   9686: doc-dfloat%
                   9687: doc-double%
                   9688: doc-end-struct
                   9689: doc-field
                   9690: doc-float%
                   9691: doc-naligned
                   9692: doc-sfloat%
                   9693: doc-%size
                   9694: doc-struct
1.23      crook    9695: 
1.44      crook    9696: 
1.26      crook    9697: @c -------------------------------------------------------------
                   9698: @node Object-oriented Forth, Passing Commands to the OS, Structures, Words
                   9699: @section Object-oriented Forth
1.20      pazsan   9700: 
1.26      crook    9701: Gforth comes with three packages for object-oriented programming:
                   9702: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
                   9703: is preloaded, so you have to @code{include} them before use. The most
                   9704: important differences between these packages (and others) are discussed
                   9705: in @ref{Comparison with other object models}. All packages are written
                   9706: in ANS Forth and can be used with any other ANS Forth.
1.20      pazsan   9707: 
1.26      crook    9708: @menu
1.48      anton    9709: * Why object-oriented programming?::  
                   9710: * Object-Oriented Terminology::  
                   9711: * Objects::                     
                   9712: * OOF::                         
                   9713: * Mini-OOF::                    
1.26      crook    9714: * Comparison with other object models::  
                   9715: @end menu
1.20      pazsan   9716: 
1.48      anton    9717: @c ----------------------------------------------------------------
                   9718: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
                   9719: @subsection Why object-oriented programming?
1.26      crook    9720: @cindex object-oriented programming motivation
                   9721: @cindex motivation for object-oriented programming
1.23      crook    9722: 
1.26      crook    9723: Often we have to deal with several data structures (@emph{objects}),
                   9724: that have to be treated similarly in some respects, but differently in
                   9725: others. Graphical objects are the textbook example: circles, triangles,
                   9726: dinosaurs, icons, and others, and we may want to add more during program
                   9727: development. We want to apply some operations to any graphical object,
                   9728: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
                   9729: has to do something different for every kind of object.
                   9730: @comment TODO add some other operations eg perimeter, area
                   9731: @comment and tie in to concrete examples later..
1.23      crook    9732: 
1.26      crook    9733: We could implement @code{draw} as a big @code{CASE}
                   9734: control structure that executes the appropriate code depending on the
                   9735: kind of object to be drawn. This would be not be very elegant, and,
                   9736: moreover, we would have to change @code{draw} every time we add
                   9737: a new kind of graphical object (say, a spaceship).
1.23      crook    9738: 
1.26      crook    9739: What we would rather do is: When defining spaceships, we would tell
                   9740: the system: ``Here's how you @code{draw} a spaceship; you figure
                   9741: out the rest''.
1.23      crook    9742: 
1.26      crook    9743: This is the problem that all systems solve that (rightfully) call
                   9744: themselves object-oriented; the object-oriented packages presented here
                   9745: solve this problem (and not much else).
                   9746: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.23      crook    9747: 
1.48      anton    9748: @c ------------------------------------------------------------------------
1.26      crook    9749: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
1.48      anton    9750: @subsection Object-Oriented Terminology
1.26      crook    9751: @cindex object-oriented terminology
                   9752: @cindex terminology for object-oriented programming
1.23      crook    9753: 
1.26      crook    9754: This section is mainly for reference, so you don't have to understand
                   9755: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
                   9756: short:
1.23      crook    9757: 
1.26      crook    9758: @table @emph
                   9759: @cindex class
                   9760: @item class
                   9761: a data structure definition with some extras.
1.23      crook    9762: 
1.26      crook    9763: @cindex object
                   9764: @item object
                   9765: an instance of the data structure described by the class definition.
1.23      crook    9766: 
1.26      crook    9767: @cindex instance variables
                   9768: @item instance variables
                   9769: fields of the data structure.
1.23      crook    9770: 
1.26      crook    9771: @cindex selector
                   9772: @cindex method selector
                   9773: @cindex virtual function
                   9774: @item selector
                   9775: (or @emph{method selector}) a word (e.g.,
                   9776: @code{draw}) that performs an operation on a variety of data
                   9777: structures (classes). A selector describes @emph{what} operation to
                   9778: perform. In C++ terminology: a (pure) virtual function.
1.23      crook    9779: 
1.26      crook    9780: @cindex method
                   9781: @item method
                   9782: the concrete definition that performs the operation
                   9783: described by the selector for a specific class. A method specifies
                   9784: @emph{how} the operation is performed for a specific class.
1.23      crook    9785: 
1.26      crook    9786: @cindex selector invocation
                   9787: @cindex message send
                   9788: @cindex invoking a selector
                   9789: @item selector invocation
                   9790: a call of a selector. One argument of the call (the TOS (top-of-stack))
                   9791: is used for determining which method is used. In Smalltalk terminology:
                   9792: a message (consisting of the selector and the other arguments) is sent
                   9793: to the object.
1.1       anton    9794: 
1.26      crook    9795: @cindex receiving object
                   9796: @item receiving object
                   9797: the object used for determining the method executed by a selector
                   9798: invocation. In the @file{objects.fs} model, it is the object that is on
                   9799: the TOS when the selector is invoked. (@emph{Receiving} comes from
                   9800: the Smalltalk @emph{message} terminology.)
1.1       anton    9801: 
1.26      crook    9802: @cindex child class
                   9803: @cindex parent class
                   9804: @cindex inheritance
                   9805: @item child class
                   9806: a class that has (@emph{inherits}) all properties (instance variables,
                   9807: selectors, methods) from a @emph{parent class}. In Smalltalk
                   9808: terminology: The subclass inherits from the superclass. In C++
                   9809: terminology: The derived class inherits from the base class.
1.1       anton    9810: 
1.26      crook    9811: @end table
1.21      crook    9812: 
1.26      crook    9813: @c If you wonder about the message sending terminology, it comes from
                   9814: @c a time when each object had it's own task and objects communicated via
                   9815: @c message passing; eventually the Smalltalk developers realized that
                   9816: @c they can do most things through simple (indirect) calls. They kept the
                   9817: @c terminology.
1.1       anton    9818: 
1.48      anton    9819: @c --------------------------------------------------------------
1.26      crook    9820: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
                   9821: @subsection The @file{objects.fs} model
                   9822: @cindex objects
                   9823: @cindex object-oriented programming
1.1       anton    9824: 
1.26      crook    9825: @cindex @file{objects.fs}
                   9826: @cindex @file{oof.fs}
1.1       anton    9827: 
1.37      anton    9828: This section describes the @file{objects.fs} package. This material also
                   9829: has been published in @cite{Yet Another Forth Objects Package} by Anton
                   9830: Ertl and appeared in Forth Dimensions 19(2), pages 37--43
1.47      crook    9831: (@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html}).
1.26      crook    9832: @c McKewan's and Zsoter's packages
1.1       anton    9833: 
1.26      crook    9834: This section assumes that you have read @ref{Structures}.
1.1       anton    9835: 
1.26      crook    9836: The techniques on which this model is based have been used to implement
                   9837: the parser generator, Gray, and have also been used in Gforth for
                   9838: implementing the various flavours of word lists (hashed or not,
                   9839: case-sensitive or not, special-purpose word lists for locals etc.).
1.1       anton    9840: 
                   9841: 
1.26      crook    9842: @menu
                   9843: * Properties of the Objects model::  
                   9844: * Basic Objects Usage::         
1.37      anton    9845: * The Objects base class::      
1.26      crook    9846: * Creating objects::            
                   9847: * Object-Oriented Programming Style::  
                   9848: * Class Binding::               
                   9849: * Method conveniences::         
                   9850: * Classes and Scoping::         
1.37      anton    9851: * Dividing classes::            
1.26      crook    9852: * Object Interfaces::           
                   9853: * Objects Implementation::      
                   9854: * Objects Glossary::            
                   9855: @end menu
1.1       anton    9856: 
1.26      crook    9857: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
                   9858: and Bernd Paysan helped me with the related works section.
1.1       anton    9859: 
1.26      crook    9860: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
                   9861: @subsubsection Properties of the @file{objects.fs} model
                   9862: @cindex @file{objects.fs} properties
1.1       anton    9863: 
1.26      crook    9864: @itemize @bullet
                   9865: @item
                   9866: It is straightforward to pass objects on the stack. Passing
                   9867: selectors on the stack is a little less convenient, but possible.
1.1       anton    9868: 
1.26      crook    9869: @item
                   9870: Objects are just data structures in memory, and are referenced by their
                   9871: address. You can create words for objects with normal defining words
                   9872: like @code{constant}. Likewise, there is no difference between instance
                   9873: variables that contain objects and those that contain other data.
1.1       anton    9874: 
1.26      crook    9875: @item
                   9876: Late binding is efficient and easy to use.
1.21      crook    9877: 
1.26      crook    9878: @item
                   9879: It avoids parsing, and thus avoids problems with state-smartness
                   9880: and reduced extensibility; for convenience there are a few parsing
                   9881: words, but they have non-parsing counterparts. There are also a few
                   9882: defining words that parse. This is hard to avoid, because all standard
                   9883: defining words parse (except @code{:noname}); however, such
                   9884: words are not as bad as many other parsing words, because they are not
                   9885: state-smart.
1.21      crook    9886: 
1.26      crook    9887: @item
                   9888: It does not try to incorporate everything. It does a few things and does
                   9889: them well (IMO). In particular, this model was not designed to support
                   9890: information hiding (although it has features that may help); you can use
                   9891: a separate package for achieving this.
1.21      crook    9892: 
1.26      crook    9893: @item
                   9894: It is layered; you don't have to learn and use all features to use this
1.49      anton    9895: model. Only a few features are necessary (@pxref{Basic Objects Usage},
                   9896: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
1.26      crook    9897: are optional and independent of each other.
1.21      crook    9898: 
1.26      crook    9899: @item
                   9900: An implementation in ANS Forth is available.
1.21      crook    9901: 
1.26      crook    9902: @end itemize
1.21      crook    9903: 
                   9904: 
1.26      crook    9905: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
                   9906: @subsubsection Basic @file{objects.fs} Usage
                   9907: @cindex basic objects usage
                   9908: @cindex objects, basic usage
1.21      crook    9909: 
1.26      crook    9910: You can define a class for graphical objects like this:
1.21      crook    9911: 
1.26      crook    9912: @cindex @code{class} usage
                   9913: @cindex @code{end-class} usage
                   9914: @cindex @code{selector} usage
                   9915: @example
                   9916: object class \ "object" is the parent class
                   9917:   selector draw ( x y graphical -- )
                   9918: end-class graphical
                   9919: @end example
1.21      crook    9920: 
1.26      crook    9921: This code defines a class @code{graphical} with an
                   9922: operation @code{draw}.  We can perform the operation
                   9923: @code{draw} on any @code{graphical} object, e.g.:
1.21      crook    9924: 
1.26      crook    9925: @example
                   9926: 100 100 t-rex draw
                   9927: @end example
1.21      crook    9928: 
1.26      crook    9929: @noindent
                   9930: where @code{t-rex} is a word (say, a constant) that produces a
                   9931: graphical object.
1.21      crook    9932: 
1.29      crook    9933: @comment TODO add a 2nd operation eg perimeter.. and use for
1.26      crook    9934: @comment a concrete example
1.21      crook    9935: 
1.26      crook    9936: @cindex abstract class
                   9937: How do we create a graphical object? With the present definitions,
                   9938: we cannot create a useful graphical object. The class
                   9939: @code{graphical} describes graphical objects in general, but not
                   9940: any concrete graphical object type (C++ users would call it an
                   9941: @emph{abstract class}); e.g., there is no method for the selector
                   9942: @code{draw} in the class @code{graphical}.
1.21      crook    9943: 
1.26      crook    9944: For concrete graphical objects, we define child classes of the
                   9945: class @code{graphical}, e.g.:
1.21      crook    9946: 
1.26      crook    9947: @cindex @code{overrides} usage
                   9948: @cindex @code{field} usage in class definition
                   9949: @example
                   9950: graphical class \ "graphical" is the parent class
                   9951:   cell% field circle-radius
1.21      crook    9952: 
1.26      crook    9953: :noname ( x y circle -- )
                   9954:   circle-radius @@ draw-circle ;
                   9955: overrides draw
1.21      crook    9956: 
1.26      crook    9957: :noname ( n-radius circle -- )
                   9958:   circle-radius ! ;
                   9959: overrides construct
1.21      crook    9960: 
1.26      crook    9961: end-class circle
1.21      crook    9962: @end example
                   9963: 
1.26      crook    9964: Here we define a class @code{circle} as a child of @code{graphical},
                   9965: with field @code{circle-radius} (which behaves just like a field
                   9966: (@pxref{Structures}); it defines (using @code{overrides}) new methods
                   9967: for the selectors @code{draw} and @code{construct} (@code{construct} is
                   9968: defined in @code{object}, the parent class of @code{graphical}).
1.21      crook    9969: 
1.26      crook    9970: Now we can create a circle on the heap (i.e.,
                   9971: @code{allocate}d memory) with:
1.21      crook    9972: 
1.26      crook    9973: @cindex @code{heap-new} usage
1.21      crook    9974: @example
1.26      crook    9975: 50 circle heap-new constant my-circle
                   9976: @end example
1.21      crook    9977: 
1.26      crook    9978: @noindent
                   9979: @code{heap-new} invokes @code{construct}, thus
                   9980: initializing the field @code{circle-radius} with 50. We can draw
                   9981: this new circle at (100,100) with:
1.21      crook    9982: 
1.26      crook    9983: @example
                   9984: 100 100 my-circle draw
1.21      crook    9985: @end example
                   9986: 
1.26      crook    9987: @cindex selector invocation, restrictions
                   9988: @cindex class definition, restrictions
                   9989: Note: You can only invoke a selector if the object on the TOS
                   9990: (the receiving object) belongs to the class where the selector was
                   9991: defined or one of its descendents; e.g., you can invoke
                   9992: @code{draw} only for objects belonging to @code{graphical}
                   9993: or its descendents (e.g., @code{circle}).  Immediately before
                   9994: @code{end-class}, the search order has to be the same as
                   9995: immediately after @code{class}.
1.21      crook    9996: 
1.26      crook    9997: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
                   9998: @subsubsection The @file{object.fs} base class
                   9999: @cindex @code{object} class
1.21      crook    10000: 
1.26      crook    10001: When you define a class, you have to specify a parent class.  So how do
                   10002: you start defining classes? There is one class available from the start:
                   10003: @code{object}. It is ancestor for all classes and so is the
                   10004: only class that has no parent. It has two selectors: @code{construct}
                   10005: and @code{print}.
1.21      crook    10006: 
1.26      crook    10007: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
                   10008: @subsubsection Creating objects
                   10009: @cindex creating objects
                   10010: @cindex object creation
                   10011: @cindex object allocation options
1.21      crook    10012: 
1.26      crook    10013: @cindex @code{heap-new} discussion
                   10014: @cindex @code{dict-new} discussion
                   10015: @cindex @code{construct} discussion
                   10016: You can create and initialize an object of a class on the heap with
                   10017: @code{heap-new} ( ... class -- object ) and in the dictionary
                   10018: (allocation with @code{allot}) with @code{dict-new} (
                   10019: ... class -- object ). Both words invoke @code{construct}, which
                   10020: consumes the stack items indicated by "..." above.
1.21      crook    10021: 
1.26      crook    10022: @cindex @code{init-object} discussion
                   10023: @cindex @code{class-inst-size} discussion
                   10024: If you want to allocate memory for an object yourself, you can get its
                   10025: alignment and size with @code{class-inst-size 2@@} ( class --
                   10026: align size ). Once you have memory for an object, you can initialize
                   10027: it with @code{init-object} ( ... class object -- );
                   10028: @code{construct} does only a part of the necessary work.
1.21      crook    10029: 
1.26      crook    10030: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
                   10031: @subsubsection Object-Oriented Programming Style
                   10032: @cindex object-oriented programming style
1.47      crook    10033: @cindex programming style, object-oriented
1.21      crook    10034: 
1.26      crook    10035: This section is not exhaustive.
1.1       anton    10036: 
1.26      crook    10037: @cindex stack effects of selectors
                   10038: @cindex selectors and stack effects
                   10039: In general, it is a good idea to ensure that all methods for the
                   10040: same selector have the same stack effect: when you invoke a selector,
                   10041: you often have no idea which method will be invoked, so, unless all
                   10042: methods have the same stack effect, you will not know the stack effect
                   10043: of the selector invocation.
1.21      crook    10044: 
1.26      crook    10045: One exception to this rule is methods for the selector
                   10046: @code{construct}. We know which method is invoked, because we
                   10047: specify the class to be constructed at the same place. Actually, I
                   10048: defined @code{construct} as a selector only to give the users a
                   10049: convenient way to specify initialization. The way it is used, a
                   10050: mechanism different from selector invocation would be more natural
                   10051: (but probably would take more code and more space to explain).
1.21      crook    10052: 
1.26      crook    10053: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
                   10054: @subsubsection Class Binding
                   10055: @cindex class binding
                   10056: @cindex early binding
1.21      crook    10057: 
1.26      crook    10058: @cindex late binding
                   10059: Normal selector invocations determine the method at run-time depending
                   10060: on the class of the receiving object. This run-time selection is called
1.29      crook    10061: @i{late binding}.
1.21      crook    10062: 
1.26      crook    10063: Sometimes it's preferable to invoke a different method. For example,
                   10064: you might want to use the simple method for @code{print}ing
                   10065: @code{object}s instead of the possibly long-winded @code{print} method
                   10066: of the receiver class. You can achieve this by replacing the invocation
                   10067: of @code{print} with:
1.21      crook    10068: 
1.26      crook    10069: @cindex @code{[bind]} usage
                   10070: @example
                   10071: [bind] object print
1.21      crook    10072: @end example
                   10073: 
1.26      crook    10074: @noindent
                   10075: in compiled code or:
1.21      crook    10076: 
1.26      crook    10077: @cindex @code{bind} usage
1.21      crook    10078: @example
1.26      crook    10079: bind object print
1.21      crook    10080: @end example
                   10081: 
1.26      crook    10082: @cindex class binding, alternative to
                   10083: @noindent
                   10084: in interpreted code. Alternatively, you can define the method with a
                   10085: name (e.g., @code{print-object}), and then invoke it through the
                   10086: name. Class binding is just a (often more convenient) way to achieve
                   10087: the same effect; it avoids name clutter and allows you to invoke
                   10088: methods directly without naming them first.
                   10089: 
                   10090: @cindex superclass binding
                   10091: @cindex parent class binding
                   10092: A frequent use of class binding is this: When we define a method
                   10093: for a selector, we often want the method to do what the selector does
                   10094: in the parent class, and a little more. There is a special word for
                   10095: this purpose: @code{[parent]}; @code{[parent]
                   10096: @emph{selector}} is equivalent to @code{[bind] @emph{parent
                   10097: selector}}, where @code{@emph{parent}} is the parent
                   10098: class of the current class. E.g., a method definition might look like:
1.21      crook    10099: 
1.26      crook    10100: @cindex @code{[parent]} usage
1.21      crook    10101: @example
1.26      crook    10102: :noname
                   10103:   dup [parent] foo \ do parent's foo on the receiving object
                   10104:   ... \ do some more
                   10105: ; overrides foo
1.21      crook    10106: @end example
                   10107: 
1.26      crook    10108: @cindex class binding as optimization
                   10109: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
                   10110: March 1997), Andrew McKewan presents class binding as an optimization
                   10111: technique. I recommend not using it for this purpose unless you are in
                   10112: an emergency. Late binding is pretty fast with this model anyway, so the
                   10113: benefit of using class binding is small; the cost of using class binding
                   10114: where it is not appropriate is reduced maintainability.
1.21      crook    10115: 
1.26      crook    10116: While we are at programming style questions: You should bind
                   10117: selectors only to ancestor classes of the receiving object. E.g., say,
                   10118: you know that the receiving object is of class @code{foo} or its
                   10119: descendents; then you should bind only to @code{foo} and its
                   10120: ancestors.
1.21      crook    10121: 
1.26      crook    10122: @node Method conveniences, Classes and Scoping, Class Binding, Objects
                   10123: @subsubsection Method conveniences
                   10124: @cindex method conveniences
1.1       anton    10125: 
1.26      crook    10126: In a method you usually access the receiving object pretty often.  If
                   10127: you define the method as a plain colon definition (e.g., with
                   10128: @code{:noname}), you may have to do a lot of stack
                   10129: gymnastics. To avoid this, you can define the method with @code{m:
                   10130: ... ;m}. E.g., you could define the method for
                   10131: @code{draw}ing a @code{circle} with
1.20      pazsan   10132: 
1.26      crook    10133: @cindex @code{this} usage
                   10134: @cindex @code{m:} usage
                   10135: @cindex @code{;m} usage
                   10136: @example
                   10137: m: ( x y circle -- )
                   10138:   ( x y ) this circle-radius @@ draw-circle ;m
                   10139: @end example
1.20      pazsan   10140: 
1.26      crook    10141: @cindex @code{exit} in @code{m: ... ;m}
                   10142: @cindex @code{exitm} discussion
                   10143: @cindex @code{catch} in @code{m: ... ;m}
                   10144: When this method is executed, the receiver object is removed from the
                   10145: stack; you can access it with @code{this} (admittedly, in this
                   10146: example the use of @code{m: ... ;m} offers no advantage). Note
                   10147: that I specify the stack effect for the whole method (i.e. including
                   10148: the receiver object), not just for the code between @code{m:}
                   10149: and @code{;m}. You cannot use @code{exit} in
                   10150: @code{m:...;m}; instead, use
                   10151: @code{exitm}.@footnote{Moreover, for any word that calls
                   10152: @code{catch} and was defined before loading
                   10153: @code{objects.fs}, you have to redefine it like I redefined
                   10154: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.20      pazsan   10155: 
1.26      crook    10156: @cindex @code{inst-var} usage
                   10157: You will frequently use sequences of the form @code{this
                   10158: @emph{field}} (in the example above: @code{this
                   10159: circle-radius}). If you use the field only in this way, you can
                   10160: define it with @code{inst-var} and eliminate the
                   10161: @code{this} before the field name. E.g., the @code{circle}
                   10162: class above could also be defined with:
1.20      pazsan   10163: 
1.26      crook    10164: @example
                   10165: graphical class
                   10166:   cell% inst-var radius
1.20      pazsan   10167: 
1.26      crook    10168: m: ( x y circle -- )
                   10169:   radius @@ draw-circle ;m
                   10170: overrides draw
1.20      pazsan   10171: 
1.26      crook    10172: m: ( n-radius circle -- )
                   10173:   radius ! ;m
                   10174: overrides construct
1.12      anton    10175: 
1.26      crook    10176: end-class circle
                   10177: @end example
1.12      anton    10178: 
1.26      crook    10179: @code{radius} can only be used in @code{circle} and its
                   10180: descendent classes and inside @code{m:...;m}.
1.12      anton    10181: 
1.26      crook    10182: @cindex @code{inst-value} usage
                   10183: You can also define fields with @code{inst-value}, which is
                   10184: to @code{inst-var} what @code{value} is to
                   10185: @code{variable}.  You can change the value of such a field with
                   10186: @code{[to-inst]}.  E.g., we could also define the class
                   10187: @code{circle} like this:
1.12      anton    10188: 
1.26      crook    10189: @example
                   10190: graphical class
                   10191:   inst-value radius
1.12      anton    10192: 
1.26      crook    10193: m: ( x y circle -- )
                   10194:   radius draw-circle ;m
                   10195: overrides draw
1.12      anton    10196: 
1.26      crook    10197: m: ( n-radius circle -- )
                   10198:   [to-inst] radius ;m
                   10199: overrides construct
1.21      crook    10200: 
1.26      crook    10201: end-class circle
1.12      anton    10202: @end example
                   10203: 
1.38      anton    10204: Finally, you can define named methods with @code{:m}.  One use of this
                   10205: feature is the definition of words that occur only in one class and are
                   10206: not intended to be overridden, but which still need method context
                   10207: (e.g., for accessing @code{inst-var}s).  Another use is for methods that
                   10208: would be bound frequently, if defined anonymously.
                   10209: 
1.12      anton    10210: 
1.37      anton    10211: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
1.26      crook    10212: @subsubsection Classes and Scoping
                   10213: @cindex classes and scoping
                   10214: @cindex scoping and classes
1.12      anton    10215: 
1.26      crook    10216: Inheritance is frequent, unlike structure extension. This exacerbates
                   10217: the problem with the field name convention (@pxref{Structure Naming
                   10218: Convention}): One always has to remember in which class the field was
                   10219: originally defined; changing a part of the class structure would require
                   10220: changes for renaming in otherwise unaffected code.
1.12      anton    10221: 
1.26      crook    10222: @cindex @code{inst-var} visibility
                   10223: @cindex @code{inst-value} visibility
                   10224: To solve this problem, I added a scoping mechanism (which was not in my
                   10225: original charter): A field defined with @code{inst-var} (or
                   10226: @code{inst-value}) is visible only in the class where it is defined and in
                   10227: the descendent classes of this class.  Using such fields only makes
                   10228: sense in @code{m:}-defined methods in these classes anyway.
1.12      anton    10229: 
1.26      crook    10230: This scoping mechanism allows us to use the unadorned field name,
                   10231: because name clashes with unrelated words become much less likely.
1.12      anton    10232: 
1.26      crook    10233: @cindex @code{protected} discussion
                   10234: @cindex @code{private} discussion
                   10235: Once we have this mechanism, we can also use it for controlling the
                   10236: visibility of other words: All words defined after
                   10237: @code{protected} are visible only in the current class and its
                   10238: descendents. @code{public} restores the compilation
                   10239: (i.e. @code{current}) word list that was in effect before. If you
                   10240: have several @code{protected}s without an intervening
                   10241: @code{public} or @code{set-current}, @code{public}
                   10242: will restore the compilation word list in effect before the first of
                   10243: these @code{protected}s.
1.12      anton    10244: 
1.37      anton    10245: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
                   10246: @subsubsection Dividing classes
                   10247: @cindex Dividing classes
                   10248: @cindex @code{methods}...@code{end-methods}
                   10249: 
                   10250: You may want to do the definition of methods separate from the
                   10251: definition of the class, its selectors, fields, and instance variables,
                   10252: i.e., separate the implementation from the definition.  You can do this
                   10253: in the following way:
                   10254: 
                   10255: @example
                   10256: graphical class
                   10257:   inst-value radius
                   10258: end-class circle
                   10259: 
                   10260: ... \ do some other stuff
                   10261: 
                   10262: circle methods \ now we are ready
                   10263: 
                   10264: m: ( x y circle -- )
                   10265:   radius draw-circle ;m
                   10266: overrides draw
                   10267: 
                   10268: m: ( n-radius circle -- )
                   10269:   [to-inst] radius ;m
                   10270: overrides construct
                   10271: 
                   10272: end-methods
                   10273: @end example
                   10274: 
                   10275: You can use several @code{methods}...@code{end-methods} sections.  The
                   10276: only things you can do to the class in these sections are: defining
                   10277: methods, and overriding the class's selectors.  You must not define new
                   10278: selectors or fields.
                   10279: 
                   10280: Note that you often have to override a selector before using it.  In
                   10281: particular, you usually have to override @code{construct} with a new
                   10282: method before you can invoke @code{heap-new} and friends.  E.g., you
                   10283: must not create a circle before the @code{overrides construct} sequence
                   10284: in the example above.
                   10285: 
                   10286: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
1.26      crook    10287: @subsubsection Object Interfaces
                   10288: @cindex object interfaces
                   10289: @cindex interfaces for objects
1.12      anton    10290: 
1.26      crook    10291: In this model you can only call selectors defined in the class of the
                   10292: receiving objects or in one of its ancestors. If you call a selector
                   10293: with a receiving object that is not in one of these classes, the
                   10294: result is undefined; if you are lucky, the program crashes
                   10295: immediately.
1.12      anton    10296: 
1.26      crook    10297: @cindex selectors common to hardly-related classes
                   10298: Now consider the case when you want to have a selector (or several)
                   10299: available in two classes: You would have to add the selector to a
                   10300: common ancestor class, in the worst case to @code{object}. You
                   10301: may not want to do this, e.g., because someone else is responsible for
                   10302: this ancestor class.
1.12      anton    10303: 
1.26      crook    10304: The solution for this problem is interfaces. An interface is a
                   10305: collection of selectors. If a class implements an interface, the
                   10306: selectors become available to the class and its descendents. A class
                   10307: can implement an unlimited number of interfaces. For the problem
                   10308: discussed above, we would define an interface for the selector(s), and
                   10309: both classes would implement the interface.
1.12      anton    10310: 
1.26      crook    10311: As an example, consider an interface @code{storage} for
                   10312: writing objects to disk and getting them back, and a class
                   10313: @code{foo} that implements it. The code would look like this:
1.12      anton    10314: 
1.26      crook    10315: @cindex @code{interface} usage
                   10316: @cindex @code{end-interface} usage
                   10317: @cindex @code{implementation} usage
                   10318: @example
                   10319: interface
                   10320:   selector write ( file object -- )
                   10321:   selector read1 ( file object -- )
                   10322: end-interface storage
1.12      anton    10323: 
1.26      crook    10324: bar class
                   10325:   storage implementation
1.12      anton    10326: 
1.26      crook    10327: ... overrides write
1.37      anton    10328: ... overrides read1
1.26      crook    10329: ...
                   10330: end-class foo
1.12      anton    10331: @end example
                   10332: 
1.26      crook    10333: @noindent
1.29      crook    10334: (I would add a word @code{read} @i{( file -- object )} that uses
1.26      crook    10335: @code{read1} internally, but that's beyond the point illustrated
                   10336: here.)
1.12      anton    10337: 
1.26      crook    10338: Note that you cannot use @code{protected} in an interface; and
                   10339: of course you cannot define fields.
1.12      anton    10340: 
1.26      crook    10341: In the Neon model, all selectors are available for all classes;
                   10342: therefore it does not need interfaces. The price you pay in this model
                   10343: is slower late binding, and therefore, added complexity to avoid late
                   10344: binding.
1.12      anton    10345: 
1.26      crook    10346: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
                   10347: @subsubsection @file{objects.fs} Implementation
                   10348: @cindex @file{objects.fs} implementation
1.12      anton    10349: 
1.26      crook    10350: @cindex @code{object-map} discussion
                   10351: An object is a piece of memory, like one of the data structures
                   10352: described with @code{struct...end-struct}. It has a field
                   10353: @code{object-map} that points to the method map for the object's
                   10354: class.
1.12      anton    10355: 
1.26      crook    10356: @cindex method map
                   10357: @cindex virtual function table
                   10358: The @emph{method map}@footnote{This is Self terminology; in C++
                   10359: terminology: virtual function table.} is an array that contains the
1.29      crook    10360: execution tokens (@i{xt}s) of the methods for the object's class. Each
1.26      crook    10361: selector contains an offset into a method map.
1.12      anton    10362: 
1.26      crook    10363: @cindex @code{selector} implementation, class
                   10364: @code{selector} is a defining word that uses
                   10365: @code{CREATE} and @code{DOES>}. The body of the
1.44      crook    10366: selector contains the offset; the @code{DOES>} action for a
1.26      crook    10367: class selector is, basically:
1.21      crook    10368: 
1.26      crook    10369: @example
                   10370: ( object addr ) @@ over object-map @@ + @@ execute
                   10371: @end example
1.12      anton    10372: 
1.26      crook    10373: Since @code{object-map} is the first field of the object, it
                   10374: does not generate any code. As you can see, calling a selector has a
                   10375: small, constant cost.
1.12      anton    10376: 
1.26      crook    10377: @cindex @code{current-interface} discussion
                   10378: @cindex class implementation and representation
                   10379: A class is basically a @code{struct} combined with a method
                   10380: map. During the class definition the alignment and size of the class
                   10381: are passed on the stack, just as with @code{struct}s, so
                   10382: @code{field} can also be used for defining class
                   10383: fields. However, passing more items on the stack would be
                   10384: inconvenient, so @code{class} builds a data structure in memory,
                   10385: which is accessed through the variable
                   10386: @code{current-interface}. After its definition is complete, the
                   10387: class is represented on the stack by a pointer (e.g., as parameter for
                   10388: a child class definition).
1.1       anton    10389: 
1.26      crook    10390: A new class starts off with the alignment and size of its parent,
                   10391: and a copy of the parent's method map. Defining new fields extends the
                   10392: size and alignment; likewise, defining new selectors extends the
1.29      crook    10393: method map. @code{overrides} just stores a new @i{xt} in the method
1.26      crook    10394: map at the offset given by the selector.
1.20      pazsan   10395: 
1.26      crook    10396: @cindex class binding, implementation
1.29      crook    10397: Class binding just gets the @i{xt} at the offset given by the selector
1.26      crook    10398: from the class's method map and @code{compile,}s (in the case of
                   10399: @code{[bind]}) it.
1.21      crook    10400: 
1.26      crook    10401: @cindex @code{this} implementation
                   10402: @cindex @code{catch} and @code{this}
                   10403: @cindex @code{this} and @code{catch}
                   10404: I implemented @code{this} as a @code{value}. At the
                   10405: start of an @code{m:...;m} method the old @code{this} is
                   10406: stored to the return stack and restored at the end; and the object on
                   10407: the TOS is stored @code{TO this}. This technique has one
                   10408: disadvantage: If the user does not leave the method via
                   10409: @code{;m}, but via @code{throw} or @code{exit},
                   10410: @code{this} is not restored (and @code{exit} may
                   10411: crash). To deal with the @code{throw} problem, I have redefined
                   10412: @code{catch} to save and restore @code{this}; the same
                   10413: should be done with any word that can catch an exception. As for
                   10414: @code{exit}, I simply forbid it (as a replacement, there is
                   10415: @code{exitm}).
1.21      crook    10416: 
1.26      crook    10417: @cindex @code{inst-var} implementation
                   10418: @code{inst-var} is just the same as @code{field}, with
                   10419: a different @code{DOES>} action:
                   10420: @example
                   10421: @@ this +
                   10422: @end example
                   10423: Similar for @code{inst-value}.
1.21      crook    10424: 
1.26      crook    10425: @cindex class scoping implementation
                   10426: Each class also has a word list that contains the words defined with
                   10427: @code{inst-var} and @code{inst-value}, and its protected
                   10428: words. It also has a pointer to its parent. @code{class} pushes
                   10429: the word lists of the class and all its ancestors onto the search order stack,
                   10430: and @code{end-class} drops them.
1.21      crook    10431: 
1.26      crook    10432: @cindex interface implementation
                   10433: An interface is like a class without fields, parent and protected
                   10434: words; i.e., it just has a method map. If a class implements an
                   10435: interface, its method map contains a pointer to the method map of the
                   10436: interface. The positive offsets in the map are reserved for class
                   10437: methods, therefore interface map pointers have negative
                   10438: offsets. Interfaces have offsets that are unique throughout the
                   10439: system, unlike class selectors, whose offsets are only unique for the
                   10440: classes where the selector is available (invokable).
1.21      crook    10441: 
1.26      crook    10442: This structure means that interface selectors have to perform one
                   10443: indirection more than class selectors to find their method. Their body
                   10444: contains the interface map pointer offset in the class method map, and
                   10445: the method offset in the interface method map. The
                   10446: @code{does>} action for an interface selector is, basically:
1.21      crook    10447: 
                   10448: @example
1.26      crook    10449: ( object selector-body )
                   10450: 2dup selector-interface @@ ( object selector-body object interface-offset )
                   10451: swap object-map @@ + @@ ( object selector-body map )
                   10452: swap selector-offset @@ + @@ execute
1.21      crook    10453: @end example
                   10454: 
1.26      crook    10455: where @code{object-map} and @code{selector-offset} are
                   10456: first fields and generate no code.
                   10457: 
                   10458: As a concrete example, consider the following code:
1.21      crook    10459: 
1.26      crook    10460: @example
                   10461: interface
                   10462:   selector if1sel1
                   10463:   selector if1sel2
                   10464: end-interface if1
1.21      crook    10465: 
1.26      crook    10466: object class
                   10467:   if1 implementation
                   10468:   selector cl1sel1
                   10469:   cell% inst-var cl1iv1
1.21      crook    10470: 
1.26      crook    10471: ' m1 overrides construct
                   10472: ' m2 overrides if1sel1
                   10473: ' m3 overrides if1sel2
                   10474: ' m4 overrides cl1sel2
                   10475: end-class cl1
1.21      crook    10476: 
1.26      crook    10477: create obj1 object dict-new drop
                   10478: create obj2 cl1    dict-new drop
                   10479: @end example
1.21      crook    10480: 
1.26      crook    10481: The data structure created by this code (including the data structure
                   10482: for @code{object}) is shown in the <a
                   10483: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
1.29      crook    10484: @comment TODO add this diagram..
1.21      crook    10485: 
1.26      crook    10486: @node Objects Glossary,  , Objects Implementation, Objects
                   10487: @subsubsection @file{objects.fs} Glossary
                   10488: @cindex @file{objects.fs} Glossary
1.21      crook    10489: 
1.44      crook    10490: 
1.26      crook    10491: doc---objects-bind
                   10492: doc---objects-<bind>
                   10493: doc---objects-bind'
                   10494: doc---objects-[bind]
                   10495: doc---objects-class
                   10496: doc---objects-class->map
                   10497: doc---objects-class-inst-size
                   10498: doc---objects-class-override!
                   10499: doc---objects-construct
                   10500: doc---objects-current'
                   10501: doc---objects-[current]
                   10502: doc---objects-current-interface
                   10503: doc---objects-dict-new
                   10504: doc---objects-drop-order
                   10505: doc---objects-end-class
                   10506: doc---objects-end-class-noname
                   10507: doc---objects-end-interface
                   10508: doc---objects-end-interface-noname
1.37      anton    10509: doc---objects-end-methods
1.26      crook    10510: doc---objects-exitm
                   10511: doc---objects-heap-new
                   10512: doc---objects-implementation
                   10513: doc---objects-init-object
                   10514: doc---objects-inst-value
                   10515: doc---objects-inst-var
                   10516: doc---objects-interface
1.38      anton    10517: doc---objects-m:
                   10518: doc---objects-:m
1.26      crook    10519: doc---objects-;m
                   10520: doc---objects-method
1.37      anton    10521: doc---objects-methods
1.26      crook    10522: doc---objects-object
                   10523: doc---objects-overrides
                   10524: doc---objects-[parent]
                   10525: doc---objects-print
                   10526: doc---objects-protected
                   10527: doc---objects-public
                   10528: doc---objects-push-order
                   10529: doc---objects-selector
                   10530: doc---objects-this
                   10531: doc---objects-<to-inst>
                   10532: doc---objects-[to-inst]
                   10533: doc---objects-to-this
                   10534: doc---objects-xt-new
1.21      crook    10535: 
1.44      crook    10536: 
1.26      crook    10537: @c -------------------------------------------------------------
                   10538: @node OOF, Mini-OOF, Objects, Object-oriented Forth
                   10539: @subsection The @file{oof.fs} model
                   10540: @cindex oof
                   10541: @cindex object-oriented programming
1.21      crook    10542: 
1.26      crook    10543: @cindex @file{objects.fs}
                   10544: @cindex @file{oof.fs}
1.21      crook    10545: 
1.26      crook    10546: This section describes the @file{oof.fs} package.
1.21      crook    10547: 
1.26      crook    10548: The package described in this section has been used in bigFORTH since 1991, and
                   10549: used for two large applications: a chromatographic system used to
                   10550: create new medicaments, and a graphic user interface library (MINOS).
1.21      crook    10551: 
1.26      crook    10552: You can find a description (in German) of @file{oof.fs} in @cite{Object
                   10553: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
                   10554: 10(2), 1994.
1.21      crook    10555: 
1.26      crook    10556: @menu
                   10557: * Properties of the OOF model::
                   10558: * Basic OOF Usage::
                   10559: * The OOF base class::
                   10560: * Class Declaration::
                   10561: * Class Implementation::
                   10562: @end menu
1.21      crook    10563: 
1.26      crook    10564: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
                   10565: @subsubsection Properties of the @file{oof.fs} model
                   10566: @cindex @file{oof.fs} properties
1.21      crook    10567: 
1.26      crook    10568: @itemize @bullet
                   10569: @item
                   10570: This model combines object oriented programming with information
                   10571: hiding. It helps you writing large application, where scoping is
                   10572: necessary, because it provides class-oriented scoping.
1.21      crook    10573: 
1.26      crook    10574: @item
                   10575: Named objects, object pointers, and object arrays can be created,
                   10576: selector invocation uses the ``object selector'' syntax. Selector invocation
                   10577: to objects and/or selectors on the stack is a bit less convenient, but
                   10578: possible.
1.21      crook    10579: 
1.26      crook    10580: @item
                   10581: Selector invocation and instance variable usage of the active object is
                   10582: straightforward, since both make use of the active object.
1.21      crook    10583: 
1.26      crook    10584: @item
                   10585: Late binding is efficient and easy to use.
1.21      crook    10586: 
1.26      crook    10587: @item
                   10588: State-smart objects parse selectors. However, extensibility is provided
                   10589: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.21      crook    10590: 
                   10591: @item
1.26      crook    10592: An implementation in ANS Forth is available.
                   10593: 
1.21      crook    10594: @end itemize
                   10595: 
                   10596: 
1.26      crook    10597: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
                   10598: @subsubsection Basic @file{oof.fs} Usage
                   10599: @cindex @file{oof.fs} usage
                   10600: 
                   10601: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.21      crook    10602: 
1.26      crook    10603: You can define a class for graphical objects like this:
1.21      crook    10604: 
1.26      crook    10605: @cindex @code{class} usage
                   10606: @cindex @code{class;} usage
                   10607: @cindex @code{method} usage
                   10608: @example
                   10609: object class graphical \ "object" is the parent class
                   10610:   method draw ( x y graphical -- )
                   10611: class;
                   10612: @end example
1.21      crook    10613: 
1.26      crook    10614: This code defines a class @code{graphical} with an
                   10615: operation @code{draw}.  We can perform the operation
                   10616: @code{draw} on any @code{graphical} object, e.g.:
1.21      crook    10617: 
1.26      crook    10618: @example
                   10619: 100 100 t-rex draw
                   10620: @end example
1.21      crook    10621: 
1.26      crook    10622: @noindent
                   10623: where @code{t-rex} is an object or object pointer, created with e.g.
                   10624: @code{graphical : t-rex}.
1.21      crook    10625: 
1.26      crook    10626: @cindex abstract class
                   10627: How do we create a graphical object? With the present definitions,
                   10628: we cannot create a useful graphical object. The class
                   10629: @code{graphical} describes graphical objects in general, but not
                   10630: any concrete graphical object type (C++ users would call it an
                   10631: @emph{abstract class}); e.g., there is no method for the selector
                   10632: @code{draw} in the class @code{graphical}.
1.21      crook    10633: 
1.26      crook    10634: For concrete graphical objects, we define child classes of the
                   10635: class @code{graphical}, e.g.:
1.21      crook    10636: 
                   10637: @example
1.26      crook    10638: graphical class circle \ "graphical" is the parent class
                   10639:   cell var circle-radius
                   10640: how:
                   10641:   : draw ( x y -- )
                   10642:     circle-radius @@ draw-circle ;
                   10643: 
                   10644:   : init ( n-radius -- (
                   10645:     circle-radius ! ;
                   10646: class;
                   10647: @end example
                   10648: 
                   10649: Here we define a class @code{circle} as a child of @code{graphical},
                   10650: with a field @code{circle-radius}; it defines new methods for the
                   10651: selectors @code{draw} and @code{init} (@code{init} is defined in
                   10652: @code{object}, the parent class of @code{graphical}).
1.21      crook    10653: 
1.26      crook    10654: Now we can create a circle in the dictionary with:
1.21      crook    10655: 
1.26      crook    10656: @example
                   10657: 50 circle : my-circle
1.21      crook    10658: @end example
                   10659: 
1.26      crook    10660: @noindent
                   10661: @code{:} invokes @code{init}, thus initializing the field
                   10662: @code{circle-radius} with 50. We can draw this new circle at (100,100)
                   10663: with:
1.21      crook    10664: 
                   10665: @example
1.26      crook    10666: 100 100 my-circle draw
1.21      crook    10667: @end example
                   10668: 
1.26      crook    10669: @cindex selector invocation, restrictions
                   10670: @cindex class definition, restrictions
                   10671: Note: You can only invoke a selector if the receiving object belongs to
                   10672: the class where the selector was defined or one of its descendents;
                   10673: e.g., you can invoke @code{draw} only for objects belonging to
                   10674: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
                   10675: mechanism will check if you try to invoke a selector that is not
                   10676: defined in this class hierarchy, so you'll get an error at compilation
                   10677: time.
                   10678: 
                   10679: 
                   10680: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
                   10681: @subsubsection The @file{oof.fs} base class
                   10682: @cindex @file{oof.fs} base class
                   10683: 
                   10684: When you define a class, you have to specify a parent class.  So how do
                   10685: you start defining classes? There is one class available from the start:
                   10686: @code{object}. You have to use it as ancestor for all classes. It is the
                   10687: only class that has no parent. Classes are also objects, except that
                   10688: they don't have instance variables; class manipulation such as
                   10689: inheritance or changing definitions of a class is handled through
                   10690: selectors of the class @code{object}.
                   10691: 
                   10692: @code{object} provides a number of selectors:
                   10693: 
1.21      crook    10694: @itemize @bullet
                   10695: @item
1.26      crook    10696: @code{class} for subclassing, @code{definitions} to add definitions
                   10697: later on, and @code{class?} to get type informations (is the class a
                   10698: subclass of the class passed on the stack?).
1.44      crook    10699: 
1.26      crook    10700: doc---object-class
                   10701: doc---object-definitions
                   10702: doc---object-class?
                   10703: 
1.44      crook    10704: 
1.21      crook    10705: @item
1.26      crook    10706: @code{init} and @code{dispose} as constructor and destructor of the
                   10707: object. @code{init} is invocated after the object's memory is allocated,
                   10708: while @code{dispose} also handles deallocation. Thus if you redefine
                   10709: @code{dispose}, you have to call the parent's dispose with @code{super
                   10710: dispose}, too.
1.44      crook    10711: 
1.26      crook    10712: doc---object-init
                   10713: doc---object-dispose
                   10714: 
1.44      crook    10715: 
1.21      crook    10716: @item
1.26      crook    10717: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
                   10718: @code{[]} to create named and unnamed objects and object arrays or
                   10719: object pointers.
1.44      crook    10720: 
1.26      crook    10721: doc---object-new
                   10722: doc---object-new[]
                   10723: doc---object-:
                   10724: doc---object-ptr
                   10725: doc---object-asptr
                   10726: doc---object-[]
1.21      crook    10727: 
1.44      crook    10728: 
1.26      crook    10729: @item
                   10730: @code{::} and @code{super} for explicit scoping. You should use explicit
                   10731: scoping only for super classes or classes with the same set of instance
                   10732: variables. Explicitly-scoped selectors use early binding.
1.44      crook    10733: 
1.26      crook    10734: doc---object-::
                   10735: doc---object-super
1.21      crook    10736: 
1.44      crook    10737: 
1.26      crook    10738: @item
                   10739: @code{self} to get the address of the object
1.44      crook    10740: 
1.26      crook    10741: doc---object-self
1.21      crook    10742: 
1.44      crook    10743: 
1.21      crook    10744: @item
1.26      crook    10745: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
                   10746: pointers and instance defers.
1.44      crook    10747: 
1.26      crook    10748: doc---object-bind
                   10749: doc---object-bound
                   10750: doc---object-link
                   10751: doc---object-is
                   10752: 
1.44      crook    10753: 
1.21      crook    10754: @item
1.26      crook    10755: @code{'} to obtain selector tokens, @code{send} to invocate selectors
                   10756: form the stack, and @code{postpone} to generate selector invocation code.
1.44      crook    10757: 
1.26      crook    10758: doc---object-'
                   10759: doc---object-postpone
                   10760: 
1.44      crook    10761: 
1.21      crook    10762: @item
1.26      crook    10763: @code{with} and @code{endwith} to select the active object from the
                   10764: stack, and enable its scope. Using @code{with} and @code{endwith}
                   10765: also allows you to create code using selector @code{postpone} without being
                   10766: trapped by the state-smart objects.
1.44      crook    10767: 
1.26      crook    10768: doc---object-with
                   10769: doc---object-endwith
                   10770: 
1.44      crook    10771: 
1.21      crook    10772: @end itemize
                   10773: 
1.26      crook    10774: @node Class Declaration, Class Implementation, The OOF base class, OOF
                   10775: @subsubsection Class Declaration
                   10776: @cindex class declaration
                   10777: 
                   10778: @itemize @bullet
                   10779: @item
                   10780: Instance variables
1.44      crook    10781: 
1.26      crook    10782: doc---oof-var
1.21      crook    10783: 
1.44      crook    10784: 
1.26      crook    10785: @item
                   10786: Object pointers
1.44      crook    10787: 
1.26      crook    10788: doc---oof-ptr
                   10789: doc---oof-asptr
1.21      crook    10790: 
1.44      crook    10791: 
1.26      crook    10792: @item
                   10793: Instance defers
1.44      crook    10794: 
1.26      crook    10795: doc---oof-defer
1.21      crook    10796: 
1.44      crook    10797: 
1.26      crook    10798: @item
                   10799: Method selectors
1.44      crook    10800: 
1.26      crook    10801: doc---oof-early
                   10802: doc---oof-method
1.21      crook    10803: 
1.44      crook    10804: 
1.26      crook    10805: @item
                   10806: Class-wide variables
1.44      crook    10807: 
1.26      crook    10808: doc---oof-static
1.21      crook    10809: 
1.44      crook    10810: 
1.26      crook    10811: @item
                   10812: End declaration
1.44      crook    10813: 
1.26      crook    10814: doc---oof-how:
                   10815: doc---oof-class;
1.21      crook    10816: 
1.44      crook    10817: 
1.26      crook    10818: @end itemize
1.21      crook    10819: 
1.26      crook    10820: @c -------------------------------------------------------------
                   10821: @node Class Implementation,  , Class Declaration, OOF
                   10822: @subsubsection Class Implementation
                   10823: @cindex class implementation
1.21      crook    10824: 
1.26      crook    10825: @c -------------------------------------------------------------
                   10826: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
                   10827: @subsection The @file{mini-oof.fs} model
                   10828: @cindex mini-oof
1.1       anton    10829: 
1.26      crook    10830: Gforth's third object oriented Forth package is a 12-liner. It uses a
                   10831: mixture of the @file{object.fs} and the @file{oof.fs} syntax,
                   10832: and reduces to the bare minimum of features. This is based on a posting
                   10833: of Bernd Paysan in comp.arch.
1.1       anton    10834: 
                   10835: @menu
1.48      anton    10836: * Basic Mini-OOF Usage::        
                   10837: * Mini-OOF Example::            
                   10838: * Mini-OOF Implementation::     
                   10839: * Comparison with other object models::  
1.1       anton    10840: @end menu
                   10841: 
1.26      crook    10842: @c -------------------------------------------------------------
1.48      anton    10843: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
1.26      crook    10844: @subsubsection Basic @file{mini-oof.fs} Usage
                   10845: @cindex mini-oof usage
1.1       anton    10846: 
1.28      crook    10847: There is a base class (@code{class}, which allocates one cell for the
                   10848: object pointer) plus seven other words: to define a method, a variable,
                   10849: a class; to end a class, to resolve binding, to allocate an object and
                   10850: to compile a class method.
1.26      crook    10851: @comment TODO better description of the last one
1.1       anton    10852: 
1.44      crook    10853: 
1.26      crook    10854: doc-object
                   10855: doc-method
                   10856: doc-var
                   10857: doc-class
                   10858: doc-end-class
                   10859: doc-defines
                   10860: doc-new
                   10861: doc-::
1.1       anton    10862: 
1.21      crook    10863: 
1.44      crook    10864: 
1.26      crook    10865: @c -------------------------------------------------------------
                   10866: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
                   10867: @subsubsection Mini-OOF Example
                   10868: @cindex mini-oof example
1.21      crook    10869: 
1.26      crook    10870: A short example shows how to use this package. This example, in slightly
                   10871: extended form, is supplied as @file{moof-exm.fs}
1.29      crook    10872: @comment TODO could flesh this out with some comments from the Forthwrite article
1.21      crook    10873: 
1.26      crook    10874: @example
                   10875: object class
                   10876:   method init
                   10877:   method draw
                   10878: end-class graphical
                   10879: @end example
1.21      crook    10880: 
1.26      crook    10881: This code defines a class @code{graphical} with an
                   10882: operation @code{draw}.  We can perform the operation
                   10883: @code{draw} on any @code{graphical} object, e.g.:
1.1       anton    10884: 
1.26      crook    10885: @example
                   10886: 100 100 t-rex draw
                   10887: @end example
1.1       anton    10888: 
1.26      crook    10889: where @code{t-rex} is an object or object pointer, created with e.g.
                   10890: @code{graphical new Constant t-rex}.
1.1       anton    10891: 
1.26      crook    10892: For concrete graphical objects, we define child classes of the
                   10893: class @code{graphical}, e.g.:
1.21      crook    10894: 
                   10895: @example
1.26      crook    10896: graphical class
                   10897:   cell var circle-radius
                   10898: end-class circle \ "graphical" is the parent class
1.21      crook    10899: 
1.26      crook    10900: :noname ( x y -- )
                   10901:   circle-radius @@ draw-circle ; circle defines draw
                   10902: :noname ( r -- )
                   10903:   circle-radius ! ; circle defines init
1.21      crook    10904: @end example
                   10905: 
1.26      crook    10906: There is no implicit init method, so we have to define one. The creation
                   10907: code of the object now has to call init explicitely.
1.21      crook    10908: 
1.26      crook    10909: @example
                   10910: circle new Constant my-circle
                   10911: 50 my-circle init
                   10912: @end example
1.21      crook    10913: 
1.26      crook    10914: It is also possible to add a function to create named objects with
                   10915: automatic call of @code{init}, given that all objects have @code{init}
                   10916: on the same place:
1.1       anton    10917: 
                   10918: @example
1.26      crook    10919: : new: ( .. o "name" -- )
                   10920:     new dup Constant init ;
                   10921: 80 circle new: large-circle
1.1       anton    10922: @end example
                   10923: 
1.26      crook    10924: We can draw this new circle at (100,100) with:
1.1       anton    10925: 
                   10926: @example
1.26      crook    10927: 100 100 my-circle draw
1.1       anton    10928: @end example
                   10929: 
1.48      anton    10930: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
1.26      crook    10931: @subsubsection @file{mini-oof.fs} Implementation
1.1       anton    10932: 
1.26      crook    10933: Object-oriented systems with late binding typically use a
                   10934: ``vtable''-approach: the first variable in each object is a pointer to a
                   10935: table, which contains the methods as function pointers. The vtable
                   10936: may also contain other information.
1.1       anton    10937: 
1.26      crook    10938: So first, let's declare methods:
1.1       anton    10939: 
1.26      crook    10940: @example
                   10941: : method ( m v -- m' v ) Create  over , swap cell+ swap
                   10942:   DOES> ( ... o -- ... ) @ over @ + @ execute ;
                   10943: @end example
1.1       anton    10944: 
1.26      crook    10945: During method declaration, the number of methods and instance
                   10946: variables is on the stack (in address units). @code{method} creates
                   10947: one method and increments the method number. To execute a method, it
                   10948: takes the object, fetches the vtable pointer, adds the offset, and
1.29      crook    10949: executes the @i{xt} stored there. Each method takes the object it is
1.26      crook    10950: invoked from as top of stack parameter. The method itself should
                   10951: consume that object.
1.1       anton    10952: 
1.26      crook    10953: Now, we also have to declare instance variables
1.21      crook    10954: 
1.26      crook    10955: @example
                   10956: : var ( m v size -- m v' ) Create  over , +
                   10957:   DOES> ( o -- addr ) @ + ;
                   10958: @end example
1.21      crook    10959: 
1.26      crook    10960: As before, a word is created with the current offset. Instance
                   10961: variables can have different sizes (cells, floats, doubles, chars), so
                   10962: all we do is take the size and add it to the offset. If your machine
                   10963: has alignment restrictions, put the proper @code{aligned} or
                   10964: @code{faligned} before the variable, to adjust the variable
                   10965: offset. That's why it is on the top of stack.
1.2       jwilke   10966: 
1.26      crook    10967: We need a starting point (the base object) and some syntactic sugar:
1.21      crook    10968: 
1.26      crook    10969: @example
                   10970: Create object  1 cells , 2 cells ,
                   10971: : class ( class -- class methods vars ) dup 2@ ;
                   10972: @end example
1.21      crook    10973: 
1.26      crook    10974: For inheritance, the vtable of the parent object has to be
                   10975: copied when a new, derived class is declared. This gives all the
                   10976: methods of the parent class, which can be overridden, though.
1.21      crook    10977: 
1.2       jwilke   10978: @example
1.26      crook    10979: : end-class  ( class methods vars -- )
                   10980:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
                   10981:   cell+ dup cell+ r> rot @ 2 cells /string move ;
                   10982: @end example
                   10983: 
                   10984: The first line creates the vtable, initialized with
                   10985: @code{noop}s. The second line is the inheritance mechanism, it
                   10986: copies the xts from the parent vtable.
1.2       jwilke   10987: 
1.26      crook    10988: We still have no way to define new methods, let's do that now:
1.2       jwilke   10989: 
1.26      crook    10990: @example
                   10991: : defines ( xt class -- ) ' >body @ + ! ;
1.2       jwilke   10992: @end example
                   10993: 
1.26      crook    10994: To allocate a new object, we need a word, too:
1.2       jwilke   10995: 
1.26      crook    10996: @example
                   10997: : new ( class -- o )  here over @ allot swap over ! ;
                   10998: @end example
1.2       jwilke   10999: 
1.26      crook    11000: Sometimes derived classes want to access the method of the
                   11001: parent object. There are two ways to achieve this with Mini-OOF:
                   11002: first, you could use named words, and second, you could look up the
                   11003: vtable of the parent object.
1.2       jwilke   11004: 
1.26      crook    11005: @example
                   11006: : :: ( class "name" -- ) ' >body @ + @ compile, ;
                   11007: @end example
1.2       jwilke   11008: 
                   11009: 
1.26      crook    11010: Nothing can be more confusing than a good example, so here is
                   11011: one. First let's declare a text object (called
                   11012: @code{button}), that stores text and position:
1.2       jwilke   11013: 
1.26      crook    11014: @example
                   11015: object class
                   11016:   cell var text
                   11017:   cell var len
                   11018:   cell var x
                   11019:   cell var y
                   11020:   method init
                   11021:   method draw
                   11022: end-class button
                   11023: @end example
1.2       jwilke   11024: 
1.26      crook    11025: @noindent
                   11026: Now, implement the two methods, @code{draw} and @code{init}:
1.2       jwilke   11027: 
1.26      crook    11028: @example
                   11029: :noname ( o -- )
                   11030:  >r r@ x @ r@ y @ at-xy  r@ text @ r> len @ type ;
                   11031:  button defines draw
                   11032: :noname ( addr u o -- )
                   11033:  >r 0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
                   11034:  button defines init
                   11035: @end example
1.2       jwilke   11036: 
1.26      crook    11037: @noindent
                   11038: To demonstrate inheritance, we define a class @code{bold-button}, with no
                   11039: new data and no new methods:
1.2       jwilke   11040: 
1.26      crook    11041: @example
                   11042: button class
                   11043: end-class bold-button
1.1       anton    11044: 
1.26      crook    11045: : bold   27 emit ." [1m" ;
                   11046: : normal 27 emit ." [0m" ;
                   11047: @end example
1.1       anton    11048: 
1.26      crook    11049: @noindent
                   11050: The class @code{bold-button} has a different draw method to
                   11051: @code{button}, but the new method is defined in terms of the draw method
                   11052: for @code{button}:
1.1       anton    11053: 
1.26      crook    11054: @example
                   11055: :noname bold [ button :: draw ] normal ; bold-button defines draw
                   11056: @end example
1.1       anton    11057: 
1.26      crook    11058: @noindent
                   11059: Finally, create two objects and apply methods:
1.1       anton    11060: 
1.26      crook    11061: @example
                   11062: button new Constant foo
                   11063: s" thin foo" foo init
                   11064: page
                   11065: foo draw
                   11066: bold-button new Constant bar
                   11067: s" fat bar" bar init
                   11068: 1 bar y !
                   11069: bar draw
                   11070: @end example
1.1       anton    11071: 
                   11072: 
1.48      anton    11073: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
                   11074: @subsection Comparison with other object models
1.26      crook    11075: @cindex comparison of object models
                   11076: @cindex object models, comparison
1.1       anton    11077: 
1.26      crook    11078: Many object-oriented Forth extensions have been proposed (@cite{A survey
                   11079: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
                   11080: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
                   11081: relation of the object models described here to two well-known and two
                   11082: closely-related (by the use of method maps) models.
1.1       anton    11083: 
1.26      crook    11084: @cindex Neon model
                   11085: The most popular model currently seems to be the Neon model (see
                   11086: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
                   11087: 1997) by Andrew McKewan) but this model has a number of limitations
                   11088: @footnote{A longer version of this critique can be
                   11089: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
                   11090: Dimensions, May 1997) by Anton Ertl.}:
1.1       anton    11091: 
1.26      crook    11092: @itemize @bullet
                   11093: @item
1.48      anton    11094: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
                   11095: to pass objects on the stack.
1.1       anton    11096: 
1.26      crook    11097: @item
                   11098: It requires that the selector parses the input stream (at
                   11099: compile time); this leads to reduced extensibility and to bugs that are+
                   11100: hard to find.
1.1       anton    11101: 
1.26      crook    11102: @item
                   11103: It allows using every selector to every object;
                   11104: this eliminates the need for classes, but makes it harder to create
                   11105: efficient implementations. 
                   11106: @end itemize
1.1       anton    11107: 
1.26      crook    11108: @cindex Pountain's object-oriented model
                   11109: Another well-known publication is @cite{Object-Oriented Forth} (Academic
                   11110: Press, London, 1987) by Dick Pountain. However, it is not really about
                   11111: object-oriented programming, because it hardly deals with late
                   11112: binding. Instead, it focuses on features like information hiding and
                   11113: overloading that are characteristic of modular languages like Ada (83).
1.1       anton    11114: 
1.26      crook    11115: @cindex Zsoter's object-oriented model
1.48      anton    11116: In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1)
                   11117: 1996, pages 31-35) Andras Zsoter describes a model that makes heavy use
                   11118: of an active object (like @code{this} in @file{objects.fs}): The active
                   11119: object is not only used for accessing all fields, but also specifies the
                   11120: receiving object of every selector invocation; you have to change the
                   11121: active object explicitly with @code{@{ ... @}}, whereas in
                   11122: @file{objects.fs} it changes more or less implicitly at @code{m:
                   11123: ... ;m}. Such a change at the method entry point is unnecessary with the
                   11124: Zsoter's model, because the receiving object is the active object
                   11125: already. On the other hand, the explicit change is absolutely necessary
                   11126: in that model, because otherwise no one could ever change the active
                   11127: object. An ANS Forth implementation of this model is available at
                   11128: @uref{http://www.forth.org/fig/oopf.html}.
1.1       anton    11129: 
1.26      crook    11130: @cindex @file{oof.fs}, differences to other models
                   11131: The @file{oof.fs} model combines information hiding and overloading
                   11132: resolution (by keeping names in various word lists) with object-oriented
                   11133: programming. It sets the active object implicitly on method entry, but
                   11134: also allows explicit changing (with @code{>o...o>} or with
                   11135: @code{with...endwith}). It uses parsing and state-smart objects and
                   11136: classes for resolving overloading and for early binding: the object or
                   11137: class parses the selector and determines the method from this. If the
                   11138: selector is not parsed by an object or class, it performs a call to the
                   11139: selector for the active object (late binding), like Zsoter's model.
                   11140: Fields are always accessed through the active object. The big
                   11141: disadvantage of this model is the parsing and the state-smartness, which
                   11142: reduces extensibility and increases the opportunities for subtle bugs;
                   11143: essentially, you are only safe if you never tick or @code{postpone} an
                   11144: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.1       anton    11145: 
1.26      crook    11146: @cindex @file{mini-oof.fs}, differences to other models
1.48      anton    11147: The @file{mini-oof.fs} model is quite similar to a very stripped-down
                   11148: version of the @file{objects.fs} model, but syntactically it is a
                   11149: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.1       anton    11150: 
1.26      crook    11151: @c -------------------------------------------------------------
1.47      crook    11152: @node Passing Commands to the OS, Keeping track of Time, Object-oriented Forth, Words
1.21      crook    11153: @section Passing Commands to the Operating System
                   11154: @cindex operating system - passing commands
                   11155: @cindex shell commands
                   11156: 
                   11157: Gforth allows you to pass an arbitrary string to the host operating
                   11158: system shell (if such a thing exists) for execution.
                   11159: 
1.44      crook    11160: 
1.21      crook    11161: doc-sh
                   11162: doc-system
                   11163: doc-$?
1.23      crook    11164: doc-getenv
1.21      crook    11165: 
1.44      crook    11166: 
1.26      crook    11167: @c -------------------------------------------------------------
1.47      crook    11168: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
                   11169: @section Keeping track of Time
                   11170: @cindex time-related words
                   11171: 
                   11172: Gforth implements time-related operations by making calls to the C
                   11173: library function, @code{gettimeofday}.
                   11174: 
                   11175: doc-ms
                   11176: doc-time&date
                   11177: 
                   11178: 
                   11179: 
                   11180: @c -------------------------------------------------------------
                   11181: @node Miscellaneous Words,  , Keeping track of Time, Words
1.21      crook    11182: @section Miscellaneous Words
                   11183: @cindex miscellaneous words
                   11184: 
1.29      crook    11185: @comment TODO find homes for these
                   11186: 
1.26      crook    11187: These section lists the ANS Forth words that are not documented
1.21      crook    11188: elsewhere in this manual. Ultimately, they all need proper homes.
                   11189: 
                   11190: doc-[compile]
                   11191: 
1.44      crook    11192: 
1.26      crook    11193: The following ANS Forth words are not currently supported by Gforth 
1.27      crook    11194: (@pxref{ANS conformance}):
1.21      crook    11195: 
                   11196: @code{EDITOR} 
                   11197: @code{EMIT?} 
                   11198: @code{FORGET} 
                   11199: 
1.24      anton    11200: @c ******************************************************************
                   11201: @node Error messages, Tools, Words, Top
                   11202: @chapter Error messages
                   11203: @cindex error messages
                   11204: @cindex backtrace
                   11205: 
                   11206: A typical Gforth error message looks like this:
                   11207: 
                   11208: @example
                   11209: in file included from :-1
                   11210: in file included from ./yyy.fs:1
                   11211: ./xxx.fs:4: Invalid memory address
                   11212: bar
                   11213: ^^^
1.25      anton    11214: $400E664C @@
                   11215: $400E6664 foo
1.24      anton    11216: @end example
                   11217: 
                   11218: The message identifying the error is @code{Invalid memory address}.  The
                   11219: error happened when text-interpreting line 4 of the file
                   11220: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
                   11221: word on the line where the error happened, is pointed out (with
                   11222: @code{^^^}).
                   11223: 
                   11224: The file containing the error was included in line 1 of @file{./yyy.fs},
                   11225: and @file{yyy.fs} was included from a non-file (in this case, by giving
                   11226: @file{yyy.fs} as command-line parameter to Gforth).
                   11227: 
                   11228: At the end of the error message you find a return stack dump that can be
                   11229: interpreted as a backtrace (possibly empty). On top you find the top of
                   11230: the return stack when the @code{throw} happened, and at the bottom you
                   11231: find the return stack entry just above the return stack of the topmost
                   11232: text interpreter.
                   11233: 
                   11234: To the right of most return stack entries you see a guess for the word
                   11235: that pushed that return stack entry as its return address. This gives a
                   11236: backtrace. In our case we see that @code{bar} called @code{foo}, and
                   11237: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
                   11238: address} exception).
                   11239: 
                   11240: Note that the backtrace is not perfect: We don't know which return stack
                   11241: entries are return addresses (so we may get false positives); and in
                   11242: some cases (e.g., for @code{abort"}) we cannot determine from the return
                   11243: address the word that pushed the return address, so for some return
                   11244: addresses you see no names in the return stack dump.
1.25      anton    11245: 
                   11246: @cindex @code{catch} and backtraces
                   11247: The return stack dump represents the return stack at the time when a
                   11248: specific @code{throw} was executed.  In programs that make use of
                   11249: @code{catch}, it is not necessarily clear which @code{throw} should be
                   11250: used for the return stack dump (e.g., consider one @code{throw} that
                   11251: indicates an error, which is caught, and during recovery another error
1.42      anton    11252: happens; which @code{throw} should be used for the stack dump?).  Gforth
1.25      anton    11253: presents the return stack dump for the first @code{throw} after the last
                   11254: executed (not returned-to) @code{catch}; this works well in the usual
                   11255: case.
                   11256: 
                   11257: @cindex @code{gforth-fast} and backtraces
                   11258: @cindex @code{gforth-fast}, difference from @code{gforth}
                   11259: @cindex backtraces with @code{gforth-fast}
                   11260: @cindex return stack dump with @code{gforth-fast}
                   11261: @code{gforth} is able to do a return stack dump for throws generated
                   11262: from primitives (e.g., invalid memory address, stack empty etc.);
                   11263: @code{gforth-fast} is only able to do a return stack dump from a
                   11264: directly called @code{throw} (including @code{abort} etc.).  This is the
1.30      anton    11265: only difference (apart from a speed factor of between 1.15 (K6-2) and
                   11266: 1.6 (21164A)) between @code{gforth} and @code{gforth-fast}.  Given an
                   11267: exception caused by a primitive in @code{gforth-fast}, you will
                   11268: typically see no return stack dump at all; however, if the exception is
                   11269: caught by @code{catch} (e.g., for restoring some state), and then
                   11270: @code{throw}n again, the return stack dump will be for the first such
                   11271: @code{throw}.
1.2       jwilke   11272: 
1.5       anton    11273: @c ******************************************************************
1.24      anton    11274: @node Tools, ANS conformance, Error messages, Top
1.1       anton    11275: @chapter Tools
                   11276: 
                   11277: @menu
                   11278: * ANS Report::                  Report the words used, sorted by wordset.
                   11279: @end menu
                   11280: 
                   11281: See also @ref{Emacs and Gforth}.
                   11282: 
                   11283: @node ANS Report,  , Tools, Tools
                   11284: @section @file{ans-report.fs}: Report the words used, sorted by wordset
                   11285: @cindex @file{ans-report.fs}
                   11286: @cindex report the words used in your program
                   11287: @cindex words used in your program
                   11288: 
                   11289: If you want to label a Forth program as ANS Forth Program, you must
                   11290: document which wordsets the program uses; for extension wordsets, it is
                   11291: helpful to list the words the program requires from these wordsets
                   11292: (because Forth systems are allowed to provide only some words of them).
                   11293: 
                   11294: The @file{ans-report.fs} tool makes it easy for you to determine which
                   11295: words from which wordset and which non-ANS words your application
                   11296: uses. You simply have to include @file{ans-report.fs} before loading the
                   11297: program you want to check. After loading your program, you can get the
                   11298: report with @code{print-ans-report}. A typical use is to run this as
                   11299: batch job like this:
                   11300: @example
                   11301: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
                   11302: @end example
                   11303: 
                   11304: The output looks like this (for @file{compat/control.fs}):
                   11305: @example
                   11306: The program uses the following words
                   11307: from CORE :
                   11308: : POSTPONE THEN ; immediate ?dup IF 0= 
                   11309: from BLOCK-EXT :
                   11310: \ 
                   11311: from FILE :
                   11312: ( 
                   11313: @end example
                   11314: 
                   11315: @subsection Caveats
                   11316: 
                   11317: Note that @file{ans-report.fs} just checks which words are used, not whether
                   11318: they are used in an ANS Forth conforming way!
                   11319: 
                   11320: Some words are defined in several wordsets in the
                   11321: standard. @file{ans-report.fs} reports them for only one of the
                   11322: wordsets, and not necessarily the one you expect. It depends on usage
                   11323: which wordset is the right one to specify. E.g., if you only use the
                   11324: compilation semantics of @code{S"}, it is a Core word; if you also use
                   11325: its interpretation semantics, it is a File word.
                   11326: 
                   11327: @c ******************************************************************
                   11328: @node ANS conformance, Model, Tools, Top
                   11329: @chapter ANS conformance
                   11330: @cindex ANS conformance of Gforth
                   11331: 
                   11332: To the best of our knowledge, Gforth is an
                   11333: 
                   11334: ANS Forth System
                   11335: @itemize @bullet
                   11336: @item providing the Core Extensions word set
                   11337: @item providing the Block word set
                   11338: @item providing the Block Extensions word set
                   11339: @item providing the Double-Number word set
                   11340: @item providing the Double-Number Extensions word set
                   11341: @item providing the Exception word set
                   11342: @item providing the Exception Extensions word set
                   11343: @item providing the Facility word set
1.40      anton    11344: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1       anton    11345: @item providing the File Access word set
                   11346: @item providing the File Access Extensions word set
                   11347: @item providing the Floating-Point word set
                   11348: @item providing the Floating-Point Extensions word set
                   11349: @item providing the Locals word set
                   11350: @item providing the Locals Extensions word set
                   11351: @item providing the Memory-Allocation word set
                   11352: @item providing the Memory-Allocation Extensions word set (that one's easy)
                   11353: @item providing the Programming-Tools word set
                   11354: @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
                   11355: @item providing the Search-Order word set
                   11356: @item providing the Search-Order Extensions word set
                   11357: @item providing the String word set
                   11358: @item providing the String Extensions word set (another easy one)
                   11359: @end itemize
                   11360: 
                   11361: @cindex system documentation
                   11362: In addition, ANS Forth systems are required to document certain
                   11363: implementation choices. This chapter tries to meet these
                   11364: requirements. In many cases it gives a way to ask the system for the
                   11365: information instead of providing the information directly, in
                   11366: particular, if the information depends on the processor, the operating
                   11367: system or the installation options chosen, or if they are likely to
                   11368: change during the maintenance of Gforth.
                   11369: 
                   11370: @comment The framework for the rest has been taken from pfe.
                   11371: 
                   11372: @menu
                   11373: * The Core Words::              
                   11374: * The optional Block word set::  
                   11375: * The optional Double Number word set::  
                   11376: * The optional Exception word set::  
                   11377: * The optional Facility word set::  
                   11378: * The optional File-Access word set::  
                   11379: * The optional Floating-Point word set::  
                   11380: * The optional Locals word set::  
                   11381: * The optional Memory-Allocation word set::  
                   11382: * The optional Programming-Tools word set::  
                   11383: * The optional Search-Order word set::  
                   11384: @end menu
                   11385: 
                   11386: 
                   11387: @c =====================================================================
                   11388: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
                   11389: @comment  node-name,  next,  previous,  up
                   11390: @section The Core Words
                   11391: @c =====================================================================
                   11392: @cindex core words, system documentation
                   11393: @cindex system documentation, core words
                   11394: 
                   11395: @menu
                   11396: * core-idef::                   Implementation Defined Options                   
                   11397: * core-ambcond::                Ambiguous Conditions                
                   11398: * core-other::                  Other System Documentation                  
                   11399: @end menu
                   11400: 
                   11401: @c ---------------------------------------------------------------------
                   11402: @node core-idef, core-ambcond, The Core Words, The Core Words
                   11403: @subsection Implementation Defined Options
                   11404: @c ---------------------------------------------------------------------
                   11405: @cindex core words, implementation-defined options
                   11406: @cindex implementation-defined options, core words
                   11407: 
                   11408: 
                   11409: @table @i
                   11410: @item (Cell) aligned addresses:
                   11411: @cindex cell-aligned addresses
                   11412: @cindex aligned addresses
                   11413: processor-dependent. Gforth's alignment words perform natural alignment
                   11414: (e.g., an address aligned for a datum of size 8 is divisible by
                   11415: 8). Unaligned accesses usually result in a @code{-23 THROW}.
                   11416: 
                   11417: @item @code{EMIT} and non-graphic characters:
                   11418: @cindex @code{EMIT} and non-graphic characters
                   11419: @cindex non-graphic characters and @code{EMIT}
                   11420: The character is output using the C library function (actually, macro)
                   11421: @code{putc}.
                   11422: 
                   11423: @item character editing of @code{ACCEPT} and @code{EXPECT}:
                   11424: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
                   11425: @cindex editing in @code{ACCEPT} and @code{EXPECT}
                   11426: @cindex @code{ACCEPT}, editing
                   11427: @cindex @code{EXPECT}, editing
                   11428: This is modeled on the GNU readline library (@pxref{Readline
                   11429: Interaction, , Command Line Editing, readline, The GNU Readline
                   11430: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
                   11431: producing a full word completion every time you type it (instead of
1.28      crook    11432: producing the common prefix of all completions). @xref{Command-line editing}.
1.1       anton    11433: 
                   11434: @item character set:
                   11435: @cindex character set
                   11436: The character set of your computer and display device. Gforth is
                   11437: 8-bit-clean (but some other component in your system may make trouble).
                   11438: 
                   11439: @item Character-aligned address requirements:
                   11440: @cindex character-aligned address requirements
                   11441: installation-dependent. Currently a character is represented by a C
                   11442: @code{unsigned char}; in the future we might switch to @code{wchar_t}
                   11443: (Comments on that requested).
                   11444: 
                   11445: @item character-set extensions and matching of names:
                   11446: @cindex character-set extensions and matching of names
1.26      crook    11447: @cindex case-sensitivity for name lookup
                   11448: @cindex name lookup, case-sensitivity
                   11449: @cindex locale and case-sensitivity
1.21      crook    11450: Any character except the ASCII NUL character can be used in a
1.1       anton    11451: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47      crook    11452: matching is performed using the C library function @code{strncasecmp}, whose
1.1       anton    11453: function is probably influenced by the locale. E.g., the @code{C} locale
                   11454: does not know about accents and umlauts, so they are matched
                   11455: case-sensitively in that locale. For portability reasons it is best to
                   11456: write programs such that they work in the @code{C} locale. Then one can
                   11457: use libraries written by a Polish programmer (who might use words
                   11458: containing ISO Latin-2 encoded characters) and by a French programmer
                   11459: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
                   11460: funny results for some of the words (which ones, depends on the font you
                   11461: are using)). Also, the locale you prefer may not be available in other
                   11462: operating systems. Hopefully, Unicode will solve these problems one day.
                   11463: 
                   11464: @item conditions under which control characters match a space delimiter:
                   11465: @cindex space delimiters
                   11466: @cindex control characters as delimiters
                   11467: If @code{WORD} is called with the space character as a delimiter, all
                   11468: white-space characters (as identified by the C macro @code{isspace()})
                   11469: are delimiters. @code{PARSE}, on the other hand, treats space like other
1.44      crook    11470: delimiters. @code{SWORD} treats space like @code{WORD}, but behaves
1.1       anton    11471: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
                   11472: interpreter (aka text interpreter) by default, treats all white-space
                   11473: characters as delimiters.
                   11474: 
1.26      crook    11475: @item format of the control-flow stack:
                   11476: @cindex control-flow stack, format
                   11477: The data stack is used as control-flow stack. The size of a control-flow
1.1       anton    11478: stack item in cells is given by the constant @code{cs-item-size}. At the
                   11479: time of this writing, an item consists of a (pointer to a) locals list
                   11480: (third), an address in the code (second), and a tag for identifying the
                   11481: item (TOS). The following tags are used: @code{defstart},
                   11482: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
                   11483: @code{scopestart}.
                   11484: 
                   11485: @item conversion of digits > 35
                   11486: @cindex digits > 35
                   11487: The characters @code{[\]^_'} are the digits with the decimal value
                   11488: 36@minus{}41. There is no way to input many of the larger digits.
                   11489: 
                   11490: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
                   11491: @cindex @code{EXPECT}, display after end of input
                   11492: @cindex @code{ACCEPT}, display after end of input
                   11493: The cursor is moved to the end of the entered string. If the input is
                   11494: terminated using the @kbd{Return} key, a space is typed.
                   11495: 
                   11496: @item exception abort sequence of @code{ABORT"}:
                   11497: @cindex exception abort sequence of @code{ABORT"}
                   11498: @cindex @code{ABORT"}, exception abort sequence
                   11499: The error string is stored into the variable @code{"error} and a
                   11500: @code{-2 throw} is performed.
                   11501: 
                   11502: @item input line terminator:
                   11503: @cindex input line terminator
                   11504: @cindex line terminator on input
1.26      crook    11505: @cindex newline character on input
1.1       anton    11506: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
                   11507: lines. One of these characters is typically produced when you type the
                   11508: @kbd{Enter} or @kbd{Return} key.
                   11509: 
                   11510: @item maximum size of a counted string:
                   11511: @cindex maximum size of a counted string
                   11512: @cindex counted string, maximum size
                   11513: @code{s" /counted-string" environment? drop .}. Currently 255 characters
                   11514: on all ports, but this may change.
                   11515: 
                   11516: @item maximum size of a parsed string:
                   11517: @cindex maximum size of a parsed string
                   11518: @cindex parsed string, maximum size
                   11519: Given by the constant @code{/line}. Currently 255 characters.
                   11520: 
                   11521: @item maximum size of a definition name, in characters:
                   11522: @cindex maximum size of a definition name, in characters
                   11523: @cindex name, maximum length
                   11524: 31
                   11525: 
                   11526: @item maximum string length for @code{ENVIRONMENT?}, in characters:
                   11527: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
                   11528: @cindex @code{ENVIRONMENT?} string length, maximum
                   11529: 31
                   11530: 
                   11531: @item method of selecting the user input device:
                   11532: @cindex user input device, method of selecting
                   11533: The user input device is the standard input. There is currently no way to
                   11534: change it from within Gforth. However, the input can typically be
                   11535: redirected in the command line that starts Gforth.
                   11536: 
                   11537: @item method of selecting the user output device:
                   11538: @cindex user output device, method of selecting
                   11539: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10      anton    11540: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
                   11541: output when the user output device is a terminal, otherwise the output
                   11542: is buffered.
1.1       anton    11543: 
                   11544: @item methods of dictionary compilation:
                   11545: What are we expected to document here?
                   11546: 
                   11547: @item number of bits in one address unit:
                   11548: @cindex number of bits in one address unit
                   11549: @cindex address unit, size in bits
                   11550: @code{s" address-units-bits" environment? drop .}. 8 in all current
                   11551: ports.
                   11552: 
                   11553: @item number representation and arithmetic:
                   11554: @cindex number representation and arithmetic
                   11555: Processor-dependent. Binary two's complement on all current ports.
                   11556: 
                   11557: @item ranges for integer types:
                   11558: @cindex ranges for integer types
                   11559: @cindex integer types, ranges
                   11560: Installation-dependent. Make environmental queries for @code{MAX-N},
                   11561: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
                   11562: unsigned (and positive) types is 0. The lower bound for signed types on
                   11563: two's complement and one's complement machines machines can be computed
                   11564: by adding 1 to the upper bound.
                   11565: 
                   11566: @item read-only data space regions:
                   11567: @cindex read-only data space regions
                   11568: @cindex data-space, read-only regions
                   11569: The whole Forth data space is writable.
                   11570: 
                   11571: @item size of buffer at @code{WORD}:
                   11572: @cindex size of buffer at @code{WORD}
                   11573: @cindex @code{WORD} buffer size
                   11574: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   11575: shared with the pictured numeric output string. If overwriting
                   11576: @code{PAD} is acceptable, it is as large as the remaining dictionary
                   11577: space, although only as much can be sensibly used as fits in a counted
                   11578: string.
                   11579: 
                   11580: @item size of one cell in address units:
                   11581: @cindex cell size
                   11582: @code{1 cells .}.
                   11583: 
                   11584: @item size of one character in address units:
                   11585: @cindex char size
                   11586: @code{1 chars .}. 1 on all current ports.
                   11587: 
                   11588: @item size of the keyboard terminal buffer:
                   11589: @cindex size of the keyboard terminal buffer
                   11590: @cindex terminal buffer, size
                   11591: Varies. You can determine the size at a specific time using @code{lp@@
                   11592: tib - .}. It is shared with the locals stack and TIBs of files that
                   11593: include the current file. You can change the amount of space for TIBs
                   11594: and locals stack at Gforth startup with the command line option
                   11595: @code{-l}.
                   11596: 
                   11597: @item size of the pictured numeric output buffer:
                   11598: @cindex size of the pictured numeric output buffer
                   11599: @cindex pictured numeric output buffer, size
                   11600: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   11601: shared with @code{WORD}.
                   11602: 
                   11603: @item size of the scratch area returned by @code{PAD}:
                   11604: @cindex size of the scratch area returned by @code{PAD}
                   11605: @cindex @code{PAD} size
                   11606: The remainder of dictionary space. @code{unused pad here - - .}.
                   11607: 
                   11608: @item system case-sensitivity characteristics:
                   11609: @cindex case-sensitivity characteristics
1.26      crook    11610: Dictionary searches are case-insensitive (except in
1.1       anton    11611: @code{TABLE}s). However, as explained above under @i{character-set
                   11612: extensions}, the matching for non-ASCII characters is determined by the
                   11613: locale you are using. In the default @code{C} locale all non-ASCII
                   11614: characters are matched case-sensitively.
                   11615: 
                   11616: @item system prompt:
                   11617: @cindex system prompt
                   11618: @cindex prompt
                   11619: @code{ ok} in interpret state, @code{ compiled} in compile state.
                   11620: 
                   11621: @item division rounding:
                   11622: @cindex division rounding
                   11623: installation dependent. @code{s" floored" environment? drop .}. We leave
                   11624: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
                   11625: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
                   11626: 
                   11627: @item values of @code{STATE} when true:
                   11628: @cindex @code{STATE} values
                   11629: -1.
                   11630: 
                   11631: @item values returned after arithmetic overflow:
                   11632: On two's complement machines, arithmetic is performed modulo
                   11633: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   11634: arithmetic (with appropriate mapping for signed types). Division by zero
                   11635: typically results in a @code{-55 throw} (Floating-point unidentified
                   11636: fault), although a @code{-10 throw} (divide by zero) would be more
                   11637: appropriate.
                   11638: 
                   11639: @item whether the current definition can be found after @t{DOES>}:
                   11640: @cindex @t{DOES>}, visibility of current definition
                   11641: No.
                   11642: 
                   11643: @end table
                   11644: 
                   11645: @c ---------------------------------------------------------------------
                   11646: @node core-ambcond, core-other, core-idef, The Core Words
                   11647: @subsection Ambiguous conditions
                   11648: @c ---------------------------------------------------------------------
                   11649: @cindex core words, ambiguous conditions
                   11650: @cindex ambiguous conditions, core words
                   11651: 
                   11652: @table @i
                   11653: 
                   11654: @item a name is neither a word nor a number:
                   11655: @cindex name not found
1.26      crook    11656: @cindex undefined word
1.1       anton    11657: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
                   11658: preserves the data and FP stack, so you don't lose more work than
                   11659: necessary.
                   11660: 
                   11661: @item a definition name exceeds the maximum length allowed:
1.26      crook    11662: @cindex word name too long
1.1       anton    11663: @code{-19 throw} (Word name too long)
                   11664: 
                   11665: @item addressing a region not inside the various data spaces of the forth system:
                   11666: @cindex Invalid memory address
1.32      anton    11667: The stacks, code space and header space are accessible. Machine code space is
1.1       anton    11668: typically readable. Accessing other addresses gives results dependent on
                   11669: the operating system. On decent systems: @code{-9 throw} (Invalid memory
                   11670: address).
                   11671: 
                   11672: @item argument type incompatible with parameter:
1.26      crook    11673: @cindex argument type mismatch
1.1       anton    11674: This is usually not caught. Some words perform checks, e.g., the control
                   11675: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
                   11676: mismatch).
                   11677: 
                   11678: @item attempting to obtain the execution token of a word with undefined execution semantics:
                   11679: @cindex Interpreting a compile-only word, for @code{'} etc.
                   11680: @cindex execution token of words with undefined execution semantics
                   11681: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
                   11682: get an execution token for @code{compile-only-error} (which performs a
                   11683: @code{-14 throw} when executed).
                   11684: 
                   11685: @item dividing by zero:
                   11686: @cindex dividing by zero
                   11687: @cindex floating point unidentified fault, integer division
1.24      anton    11688: On better platforms, this produces a @code{-10 throw} (Division by
                   11689: zero); on other systems, this typically results in a @code{-55 throw}
                   11690: (Floating-point unidentified fault).
1.1       anton    11691: 
                   11692: @item insufficient data stack or return stack space:
                   11693: @cindex insufficient data stack or return stack space
                   11694: @cindex stack overflow
1.26      crook    11695: @cindex address alignment exception, stack overflow
1.1       anton    11696: @cindex Invalid memory address, stack overflow
                   11697: Depending on the operating system, the installation, and the invocation
                   11698: of Gforth, this is either checked by the memory management hardware, or
1.24      anton    11699: it is not checked. If it is checked, you typically get a @code{-3 throw}
                   11700: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
                   11701: throw} (Invalid memory address) (depending on the platform and how you
                   11702: achieved the overflow) as soon as the overflow happens. If it is not
                   11703: checked, overflows typically result in mysterious illegal memory
                   11704: accesses, producing @code{-9 throw} (Invalid memory address) or
                   11705: @code{-23 throw} (Address alignment exception); they might also destroy
                   11706: the internal data structure of @code{ALLOCATE} and friends, resulting in
                   11707: various errors in these words.
1.1       anton    11708: 
                   11709: @item insufficient space for loop control parameters:
                   11710: @cindex insufficient space for loop control parameters
                   11711: like other return stack overflows.
                   11712: 
                   11713: @item insufficient space in the dictionary:
                   11714: @cindex insufficient space in the dictionary
                   11715: @cindex dictionary overflow
1.12      anton    11716: If you try to allot (either directly with @code{allot}, or indirectly
                   11717: with @code{,}, @code{create} etc.) more memory than available in the
                   11718: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
                   11719: to access memory beyond the end of the dictionary, the results are
                   11720: similar to stack overflows.
1.1       anton    11721: 
                   11722: @item interpreting a word with undefined interpretation semantics:
                   11723: @cindex interpreting a word with undefined interpretation semantics
                   11724: @cindex Interpreting a compile-only word
                   11725: For some words, we have defined interpretation semantics. For the
                   11726: others: @code{-14 throw} (Interpreting a compile-only word).
                   11727: 
                   11728: @item modifying the contents of the input buffer or a string literal:
                   11729: @cindex modifying the contents of the input buffer or a string literal
                   11730: These are located in writable memory and can be modified.
                   11731: 
                   11732: @item overflow of the pictured numeric output string:
                   11733: @cindex overflow of the pictured numeric output string
                   11734: @cindex pictured numeric output string, overflow
1.24      anton    11735: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1       anton    11736: 
                   11737: @item parsed string overflow:
                   11738: @cindex parsed string overflow
                   11739: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
                   11740: 
                   11741: @item producing a result out of range:
                   11742: @cindex result out of range
                   11743: On two's complement machines, arithmetic is performed modulo
                   11744: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   11745: arithmetic (with appropriate mapping for signed types). Division by zero
1.24      anton    11746: typically results in a @code{-10 throw} (divide by zero) or @code{-55
                   11747: throw} (floating point unidentified fault). @code{convert} and
                   11748: @code{>number} currently overflow silently.
1.1       anton    11749: 
                   11750: @item reading from an empty data or return stack:
                   11751: @cindex stack empty
                   11752: @cindex stack underflow
1.24      anton    11753: @cindex return stack underflow
1.1       anton    11754: The data stack is checked by the outer (aka text) interpreter after
                   11755: every word executed. If it has underflowed, a @code{-4 throw} (Stack
                   11756: underflow) is performed. Apart from that, stacks may be checked or not,
1.24      anton    11757: depending on operating system, installation, and invocation. If they are
                   11758: caught by a check, they typically result in @code{-4 throw} (Stack
                   11759: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
                   11760: (Invalid memory address), depending on the platform and which stack
                   11761: underflows and by how much. Note that even if the system uses checking
                   11762: (through the MMU), your program may have to underflow by a significant
                   11763: number of stack items to trigger the reaction (the reason for this is
                   11764: that the MMU, and therefore the checking, works with a page-size
                   11765: granularity).  If there is no checking, the symptoms resulting from an
                   11766: underflow are similar to those from an overflow.  Unbalanced return
                   11767: stack errors result in a variaty of symptoms, including @code{-9 throw}
                   11768: (Invalid memory address) and Illegal Instruction (typically @code{-260
                   11769: throw}).
1.1       anton    11770: 
                   11771: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
                   11772: @cindex unexpected end of the input buffer
                   11773: @cindex zero-length string as a name
                   11774: @cindex Attempt to use zero-length string as a name
                   11775: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
                   11776: use zero-length string as a name). Words like @code{'} probably will not
                   11777: find what they search. Note that it is possible to create zero-length
                   11778: names with @code{nextname} (should it not?).
                   11779: 
                   11780: @item @code{>IN} greater than input buffer:
                   11781: @cindex @code{>IN} greater than input buffer
                   11782: The next invocation of a parsing word returns a string with length 0.
                   11783: 
                   11784: @item @code{RECURSE} appears after @code{DOES>}:
                   11785: @cindex @code{RECURSE} appears after @code{DOES>}
                   11786: Compiles a recursive call to the defining word, not to the defined word.
                   11787: 
                   11788: @item argument input source different than current input source for @code{RESTORE-INPUT}:
                   11789: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26      crook    11790: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1       anton    11791: @cindex @code{RESTORE-INPUT}, Argument type mismatch
                   11792: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
                   11793: the end of the file was reached), its source-id may be
                   11794: reused. Therefore, restoring an input source specification referencing a
                   11795: closed file may lead to unpredictable results instead of a @code{-12
                   11796: THROW}.
                   11797: 
                   11798: In the future, Gforth may be able to restore input source specifications
                   11799: from other than the current input source.
                   11800: 
                   11801: @item data space containing definitions gets de-allocated:
                   11802: @cindex data space containing definitions gets de-allocated
                   11803: Deallocation with @code{allot} is not checked. This typically results in
                   11804: memory access faults or execution of illegal instructions.
                   11805: 
                   11806: @item data space read/write with incorrect alignment:
                   11807: @cindex data space read/write with incorrect alignment
                   11808: @cindex alignment faults
1.26      crook    11809: @cindex address alignment exception
1.1       anton    11810: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12      anton    11811: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1       anton    11812: alignment turned on, incorrect alignment results in a @code{-9 throw}
                   11813: (Invalid memory address). There are reportedly some processors with
1.12      anton    11814: alignment restrictions that do not report violations.
1.1       anton    11815: 
                   11816: @item data space pointer not properly aligned, @code{,}, @code{C,}:
                   11817: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
                   11818: Like other alignment errors.
                   11819: 
                   11820: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
                   11821: Like other stack underflows.
                   11822: 
                   11823: @item loop control parameters not available:
                   11824: @cindex loop control parameters not available
                   11825: Not checked. The counted loop words simply assume that the top of return
                   11826: stack items are loop control parameters and behave accordingly.
                   11827: 
                   11828: @item most recent definition does not have a name (@code{IMMEDIATE}):
                   11829: @cindex most recent definition does not have a name (@code{IMMEDIATE})
                   11830: @cindex last word was headerless
                   11831: @code{abort" last word was headerless"}.
                   11832: 
                   11833: @item name not defined by @code{VALUE} used by @code{TO}:
                   11834: @cindex name not defined by @code{VALUE} used by @code{TO}
                   11835: @cindex @code{TO} on non-@code{VALUE}s
                   11836: @cindex Invalid name argument, @code{TO}
                   11837: @code{-32 throw} (Invalid name argument) (unless name is a local or was
                   11838: defined by @code{CONSTANT}; in the latter case it just changes the constant).
                   11839: 
                   11840: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
                   11841: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26      crook    11842: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1       anton    11843: @code{-13 throw} (Undefined word)
                   11844: 
                   11845: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
                   11846: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
                   11847: Gforth behaves as if they were of the same type. I.e., you can predict
                   11848: the behaviour by interpreting all parameters as, e.g., signed.
                   11849: 
                   11850: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
                   11851: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
                   11852: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
                   11853: compilation semantics of @code{TO}.
                   11854: 
                   11855: @item String longer than a counted string returned by @code{WORD}:
1.26      crook    11856: @cindex string longer than a counted string returned by @code{WORD}
1.1       anton    11857: @cindex @code{WORD}, string overflow
                   11858: Not checked. The string will be ok, but the count will, of course,
                   11859: contain only the least significant bits of the length.
                   11860: 
                   11861: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
                   11862: @cindex @code{LSHIFT}, large shift counts
                   11863: @cindex @code{RSHIFT}, large shift counts
                   11864: Processor-dependent. Typical behaviours are returning 0 and using only
                   11865: the low bits of the shift count.
                   11866: 
                   11867: @item word not defined via @code{CREATE}:
                   11868: @cindex @code{>BODY} of non-@code{CREATE}d words
                   11869: @code{>BODY} produces the PFA of the word no matter how it was defined.
                   11870: 
                   11871: @cindex @code{DOES>} of non-@code{CREATE}d words
                   11872: @code{DOES>} changes the execution semantics of the last defined word no
                   11873: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
                   11874: @code{CREATE , DOES>}.
                   11875: 
                   11876: @item words improperly used outside @code{<#} and @code{#>}:
                   11877: Not checked. As usual, you can expect memory faults.
                   11878: 
                   11879: @end table
                   11880: 
                   11881: 
                   11882: @c ---------------------------------------------------------------------
                   11883: @node core-other,  , core-ambcond, The Core Words
                   11884: @subsection Other system documentation
                   11885: @c ---------------------------------------------------------------------
                   11886: @cindex other system documentation, core words
                   11887: @cindex core words, other system documentation
                   11888: 
                   11889: @table @i
                   11890: @item nonstandard words using @code{PAD}:
                   11891: @cindex @code{PAD} use by nonstandard words
                   11892: None.
                   11893: 
                   11894: @item operator's terminal facilities available:
                   11895: @cindex operator's terminal facilities available
                   11896: After processing the command line, Gforth goes into interactive mode,
                   11897: and you can give commands to Gforth interactively. The actual facilities
                   11898: available depend on how you invoke Gforth.
                   11899: 
                   11900: @item program data space available:
                   11901: @cindex program data space available
                   11902: @cindex data space available
                   11903: @code{UNUSED .} gives the remaining dictionary space. The total
                   11904: dictionary space can be specified with the @code{-m} switch
                   11905: (@pxref{Invoking Gforth}) when Gforth starts up.
                   11906: 
                   11907: @item return stack space available:
                   11908: @cindex return stack space available
                   11909: You can compute the total return stack space in cells with
                   11910: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
                   11911: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
                   11912: 
                   11913: @item stack space available:
                   11914: @cindex stack space available
                   11915: You can compute the total data stack space in cells with
                   11916: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
                   11917: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
                   11918: 
                   11919: @item system dictionary space required, in address units:
                   11920: @cindex system dictionary space required, in address units
                   11921: Type @code{here forthstart - .} after startup. At the time of this
                   11922: writing, this gives 80080 (bytes) on a 32-bit system.
                   11923: @end table
                   11924: 
                   11925: 
                   11926: @c =====================================================================
                   11927: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
                   11928: @section The optional Block word set
                   11929: @c =====================================================================
                   11930: @cindex system documentation, block words
                   11931: @cindex block words, system documentation
                   11932: 
                   11933: @menu
                   11934: * block-idef::                  Implementation Defined Options
                   11935: * block-ambcond::               Ambiguous Conditions               
                   11936: * block-other::                 Other System Documentation                 
                   11937: @end menu
                   11938: 
                   11939: 
                   11940: @c ---------------------------------------------------------------------
                   11941: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
                   11942: @subsection Implementation Defined Options
                   11943: @c ---------------------------------------------------------------------
                   11944: @cindex implementation-defined options, block words
                   11945: @cindex block words, implementation-defined options
                   11946: 
                   11947: @table @i
                   11948: @item the format for display by @code{LIST}:
                   11949: @cindex @code{LIST} display format
                   11950: First the screen number is displayed, then 16 lines of 64 characters,
                   11951: each line preceded by the line number.
                   11952: 
                   11953: @item the length of a line affected by @code{\}:
                   11954: @cindex length of a line affected by @code{\}
                   11955: @cindex @code{\}, line length in blocks
                   11956: 64 characters.
                   11957: @end table
                   11958: 
                   11959: 
                   11960: @c ---------------------------------------------------------------------
                   11961: @node block-ambcond, block-other, block-idef, The optional Block word set
                   11962: @subsection Ambiguous conditions
                   11963: @c ---------------------------------------------------------------------
                   11964: @cindex block words, ambiguous conditions
                   11965: @cindex ambiguous conditions, block words
                   11966: 
                   11967: @table @i
                   11968: @item correct block read was not possible:
                   11969: @cindex block read not possible
                   11970: Typically results in a @code{throw} of some OS-derived value (between
                   11971: -512 and -2048). If the blocks file was just not long enough, blanks are
                   11972: supplied for the missing portion.
                   11973: 
                   11974: @item I/O exception in block transfer:
                   11975: @cindex I/O exception in block transfer
                   11976: @cindex block transfer, I/O exception
                   11977: Typically results in a @code{throw} of some OS-derived value (between
                   11978: -512 and -2048).
                   11979: 
                   11980: @item invalid block number:
                   11981: @cindex invalid block number
                   11982: @cindex block number invalid
                   11983: @code{-35 throw} (Invalid block number)
                   11984: 
                   11985: @item a program directly alters the contents of @code{BLK}:
                   11986: @cindex @code{BLK}, altering @code{BLK}
                   11987: The input stream is switched to that other block, at the same
                   11988: position. If the storing to @code{BLK} happens when interpreting
                   11989: non-block input, the system will get quite confused when the block ends.
                   11990: 
                   11991: @item no current block buffer for @code{UPDATE}:
                   11992: @cindex @code{UPDATE}, no current block buffer
                   11993: @code{UPDATE} has no effect.
                   11994: 
                   11995: @end table
                   11996: 
                   11997: @c ---------------------------------------------------------------------
                   11998: @node block-other,  , block-ambcond, The optional Block word set
                   11999: @subsection Other system documentation
                   12000: @c ---------------------------------------------------------------------
                   12001: @cindex other system documentation, block words
                   12002: @cindex block words, other system documentation
                   12003: 
                   12004: @table @i
                   12005: @item any restrictions a multiprogramming system places on the use of buffer addresses:
                   12006: No restrictions (yet).
                   12007: 
                   12008: @item the number of blocks available for source and data:
                   12009: depends on your disk space.
                   12010: 
                   12011: @end table
                   12012: 
                   12013: 
                   12014: @c =====================================================================
                   12015: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
                   12016: @section The optional Double Number word set
                   12017: @c =====================================================================
                   12018: @cindex system documentation, double words
                   12019: @cindex double words, system documentation
                   12020: 
                   12021: @menu
                   12022: * double-ambcond::              Ambiguous Conditions              
                   12023: @end menu
                   12024: 
                   12025: 
                   12026: @c ---------------------------------------------------------------------
                   12027: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
                   12028: @subsection Ambiguous conditions
                   12029: @c ---------------------------------------------------------------------
                   12030: @cindex double words, ambiguous conditions
                   12031: @cindex ambiguous conditions, double words
                   12032: 
                   12033: @table @i
1.29      crook    12034: @item @i{d} outside of range of @i{n} in @code{D>S}:
                   12035: @cindex @code{D>S}, @i{d} out of range of @i{n} 
                   12036: The least significant cell of @i{d} is produced.
1.1       anton    12037: 
                   12038: @end table
                   12039: 
                   12040: 
                   12041: @c =====================================================================
                   12042: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
                   12043: @section The optional Exception word set
                   12044: @c =====================================================================
                   12045: @cindex system documentation, exception words
                   12046: @cindex exception words, system documentation
                   12047: 
                   12048: @menu
                   12049: * exception-idef::              Implementation Defined Options              
                   12050: @end menu
                   12051: 
                   12052: 
                   12053: @c ---------------------------------------------------------------------
                   12054: @node exception-idef,  , The optional Exception word set, The optional Exception word set
                   12055: @subsection Implementation Defined Options
                   12056: @c ---------------------------------------------------------------------
                   12057: @cindex implementation-defined options, exception words
                   12058: @cindex exception words, implementation-defined options
                   12059: 
                   12060: @table @i
                   12061: @item @code{THROW}-codes used in the system:
                   12062: @cindex @code{THROW}-codes used in the system
                   12063: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29      crook    12064: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1       anton    12065: codes -512@minus{}-2047 are used for OS errors (for file and memory
                   12066: allocation operations). The mapping from OS error numbers to throw codes
                   12067: is -512@minus{}@code{errno}. One side effect of this mapping is that
                   12068: undefined OS errors produce a message with a strange number; e.g.,
                   12069: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
                   12070: @end table
                   12071: 
                   12072: @c =====================================================================
                   12073: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
                   12074: @section The optional Facility word set
                   12075: @c =====================================================================
                   12076: @cindex system documentation, facility words
                   12077: @cindex facility words, system documentation
                   12078: 
                   12079: @menu
                   12080: * facility-idef::               Implementation Defined Options               
                   12081: * facility-ambcond::            Ambiguous Conditions            
                   12082: @end menu
                   12083: 
                   12084: 
                   12085: @c ---------------------------------------------------------------------
                   12086: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
                   12087: @subsection Implementation Defined Options
                   12088: @c ---------------------------------------------------------------------
                   12089: @cindex implementation-defined options, facility words
                   12090: @cindex facility words, implementation-defined options
                   12091: 
                   12092: @table @i
                   12093: @item encoding of keyboard events (@code{EKEY}):
                   12094: @cindex keyboard events, encoding in @code{EKEY}
                   12095: @cindex @code{EKEY}, encoding of keyboard events
1.40      anton    12096: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41      anton    12097: Other keys are encoded with the constants @code{k-left}, @code{k-right},
                   12098: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
                   12099: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
                   12100: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40      anton    12101: 
1.1       anton    12102: 
                   12103: @item duration of a system clock tick:
                   12104: @cindex duration of a system clock tick
                   12105: @cindex clock tick duration
                   12106: System dependent. With respect to @code{MS}, the time is specified in
                   12107: microseconds. How well the OS and the hardware implement this, is
                   12108: another question.
                   12109: 
                   12110: @item repeatability to be expected from the execution of @code{MS}:
                   12111: @cindex repeatability to be expected from the execution of @code{MS}
                   12112: @cindex @code{MS}, repeatability to be expected
                   12113: System dependent. On Unix, a lot depends on load. If the system is
                   12114: lightly loaded, and the delay is short enough that Gforth does not get
                   12115: swapped out, the performance should be acceptable. Under MS-DOS and
                   12116: other single-tasking systems, it should be good.
                   12117: 
                   12118: @end table
                   12119: 
                   12120: 
                   12121: @c ---------------------------------------------------------------------
                   12122: @node facility-ambcond,  , facility-idef, The optional Facility word set
                   12123: @subsection Ambiguous conditions
                   12124: @c ---------------------------------------------------------------------
                   12125: @cindex facility words, ambiguous conditions
                   12126: @cindex ambiguous conditions, facility words
                   12127: 
                   12128: @table @i
                   12129: @item @code{AT-XY} can't be performed on user output device:
                   12130: @cindex @code{AT-XY} can't be performed on user output device
                   12131: Largely terminal dependent. No range checks are done on the arguments.
                   12132: No errors are reported. You may see some garbage appearing, you may see
                   12133: simply nothing happen.
                   12134: 
                   12135: @end table
                   12136: 
                   12137: 
                   12138: @c =====================================================================
                   12139: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
                   12140: @section The optional File-Access word set
                   12141: @c =====================================================================
                   12142: @cindex system documentation, file words
                   12143: @cindex file words, system documentation
                   12144: 
                   12145: @menu
                   12146: * file-idef::                   Implementation Defined Options
                   12147: * file-ambcond::                Ambiguous Conditions                
                   12148: @end menu
                   12149: 
                   12150: @c ---------------------------------------------------------------------
                   12151: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
                   12152: @subsection Implementation Defined Options
                   12153: @c ---------------------------------------------------------------------
                   12154: @cindex implementation-defined options, file words
                   12155: @cindex file words, implementation-defined options
                   12156: 
                   12157: @table @i
                   12158: @item file access methods used:
                   12159: @cindex file access methods used
                   12160: @code{R/O}, @code{R/W} and @code{BIN} work as you would
                   12161: expect. @code{W/O} translates into the C file opening mode @code{w} (or
                   12162: @code{wb}): The file is cleared, if it exists, and created, if it does
                   12163: not (with both @code{open-file} and @code{create-file}).  Under Unix
                   12164: @code{create-file} creates a file with 666 permissions modified by your
                   12165: umask.
                   12166: 
                   12167: @item file exceptions:
                   12168: @cindex file exceptions
                   12169: The file words do not raise exceptions (except, perhaps, memory access
                   12170: faults when you pass illegal addresses or file-ids).
                   12171: 
                   12172: @item file line terminator:
                   12173: @cindex file line terminator
                   12174: System-dependent. Gforth uses C's newline character as line
                   12175: terminator. What the actual character code(s) of this are is
                   12176: system-dependent.
                   12177: 
                   12178: @item file name format:
                   12179: @cindex file name format
                   12180: System dependent. Gforth just uses the file name format of your OS.
                   12181: 
                   12182: @item information returned by @code{FILE-STATUS}:
                   12183: @cindex @code{FILE-STATUS}, returned information
                   12184: @code{FILE-STATUS} returns the most powerful file access mode allowed
                   12185: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
                   12186: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
                   12187: along with the returned mode.
                   12188: 
                   12189: @item input file state after an exception when including source:
                   12190: @cindex exception when including source
                   12191: All files that are left via the exception are closed.
                   12192: 
1.29      crook    12193: @item @i{ior} values and meaning:
                   12194: @cindex @i{ior} values and meaning
                   12195: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    12196: intended as throw codes. They typically are in the range
                   12197: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    12198: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    12199: 
                   12200: @item maximum depth of file input nesting:
                   12201: @cindex maximum depth of file input nesting
                   12202: @cindex file input nesting, maximum depth
                   12203: limited by the amount of return stack, locals/TIB stack, and the number
                   12204: of open files available. This should not give you troubles.
                   12205: 
                   12206: @item maximum size of input line:
                   12207: @cindex maximum size of input line
                   12208: @cindex input line size, maximum
                   12209: @code{/line}. Currently 255.
                   12210: 
                   12211: @item methods of mapping block ranges to files:
                   12212: @cindex mapping block ranges to files
                   12213: @cindex files containing blocks
                   12214: @cindex blocks in files
                   12215: By default, blocks are accessed in the file @file{blocks.fb} in the
                   12216: current working directory. The file can be switched with @code{USE}.
                   12217: 
                   12218: @item number of string buffers provided by @code{S"}:
                   12219: @cindex @code{S"}, number of string buffers
                   12220: 1
                   12221: 
                   12222: @item size of string buffer used by @code{S"}:
                   12223: @cindex @code{S"}, size of string buffer
                   12224: @code{/line}. currently 255.
                   12225: 
                   12226: @end table
                   12227: 
                   12228: @c ---------------------------------------------------------------------
                   12229: @node file-ambcond,  , file-idef, The optional File-Access word set
                   12230: @subsection Ambiguous conditions
                   12231: @c ---------------------------------------------------------------------
                   12232: @cindex file words, ambiguous conditions
                   12233: @cindex ambiguous conditions, file words
                   12234: 
                   12235: @table @i
                   12236: @item attempting to position a file outside its boundaries:
                   12237: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
                   12238: @code{REPOSITION-FILE} is performed as usual: Afterwards,
                   12239: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
                   12240: 
                   12241: @item attempting to read from file positions not yet written:
                   12242: @cindex reading from file positions not yet written
                   12243: End-of-file, i.e., zero characters are read and no error is reported.
                   12244: 
1.29      crook    12245: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
                   12246: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
1.1       anton    12247: An appropriate exception may be thrown, but a memory fault or other
                   12248: problem is more probable.
                   12249: 
1.29      crook    12250: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
                   12251: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
                   12252: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
                   12253: The @i{ior} produced by the operation, that discovered the problem, is
1.1       anton    12254: thrown.
                   12255: 
                   12256: @item named file cannot be opened (@code{INCLUDED}):
                   12257: @cindex @code{INCLUDED}, named file cannot be opened
1.29      crook    12258: The @i{ior} produced by @code{open-file} is thrown.
1.1       anton    12259: 
                   12260: @item requesting an unmapped block number:
                   12261: @cindex unmapped block numbers
                   12262: There are no unmapped legal block numbers. On some operating systems,
                   12263: writing a block with a large number may overflow the file system and
                   12264: have an error message as consequence.
                   12265: 
                   12266: @item using @code{source-id} when @code{blk} is non-zero:
                   12267: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
                   12268: @code{source-id} performs its function. Typically it will give the id of
                   12269: the source which loaded the block. (Better ideas?)
                   12270: 
                   12271: @end table
                   12272: 
                   12273: 
                   12274: @c =====================================================================
                   12275: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
                   12276: @section The optional Floating-Point word set
                   12277: @c =====================================================================
                   12278: @cindex system documentation, floating-point words
                   12279: @cindex floating-point words, system documentation
                   12280: 
                   12281: @menu
                   12282: * floating-idef::               Implementation Defined Options
                   12283: * floating-ambcond::            Ambiguous Conditions            
                   12284: @end menu
                   12285: 
                   12286: 
                   12287: @c ---------------------------------------------------------------------
                   12288: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
                   12289: @subsection Implementation Defined Options
                   12290: @c ---------------------------------------------------------------------
                   12291: @cindex implementation-defined options, floating-point words
                   12292: @cindex floating-point words, implementation-defined options
                   12293: 
                   12294: @table @i
                   12295: @item format and range of floating point numbers:
                   12296: @cindex format and range of floating point numbers
                   12297: @cindex floating point numbers, format and range
                   12298: System-dependent; the @code{double} type of C.
                   12299: 
1.29      crook    12300: @item results of @code{REPRESENT} when @i{float} is out of range:
                   12301: @cindex  @code{REPRESENT}, results when @i{float} is out of range
1.1       anton    12302: System dependent; @code{REPRESENT} is implemented using the C library
                   12303: function @code{ecvt()} and inherits its behaviour in this respect.
                   12304: 
                   12305: @item rounding or truncation of floating-point numbers:
                   12306: @cindex rounding of floating-point numbers
                   12307: @cindex truncation of floating-point numbers
                   12308: @cindex floating-point numbers, rounding or truncation
                   12309: System dependent; the rounding behaviour is inherited from the hosting C
                   12310: compiler. IEEE-FP-based (i.e., most) systems by default round to
                   12311: nearest, and break ties by rounding to even (i.e., such that the last
                   12312: bit of the mantissa is 0).
                   12313: 
                   12314: @item size of floating-point stack:
                   12315: @cindex floating-point stack size
                   12316: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
                   12317: the floating-point stack (in floats). You can specify this on startup
                   12318: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
                   12319: 
                   12320: @item width of floating-point stack:
                   12321: @cindex floating-point stack width 
                   12322: @code{1 floats}.
                   12323: 
                   12324: @end table
                   12325: 
                   12326: 
                   12327: @c ---------------------------------------------------------------------
                   12328: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
                   12329: @subsection Ambiguous conditions
                   12330: @c ---------------------------------------------------------------------
                   12331: @cindex floating-point words, ambiguous conditions
                   12332: @cindex ambiguous conditions, floating-point words
                   12333: 
                   12334: @table @i
                   12335: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
                   12336: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
                   12337: System-dependent. Typically results in a @code{-23 THROW} like other
                   12338: alignment violations.
                   12339: 
                   12340: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
                   12341: @cindex @code{f@@} used with an address that is not float aligned
                   12342: @cindex @code{f!} used with an address that is not float aligned
                   12343: System-dependent. Typically results in a @code{-23 THROW} like other
                   12344: alignment violations.
                   12345: 
                   12346: @item floating-point result out of range:
                   12347: @cindex floating-point result out of range
                   12348: System-dependent. Can result in a @code{-55 THROW} (Floating-point
                   12349: unidentified fault), or can produce a special value representing, e.g.,
                   12350: Infinity.
                   12351: 
                   12352: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
                   12353: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
                   12354: System-dependent. Typically results in an alignment fault like other
                   12355: alignment violations.
                   12356: 
1.35      anton    12357: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
                   12358: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1       anton    12359: The floating-point number is converted into decimal nonetheless.
                   12360: 
                   12361: @item Both arguments are equal to zero (@code{FATAN2}):
                   12362: @cindex @code{FATAN2}, both arguments are equal to zero
                   12363: System-dependent. @code{FATAN2} is implemented using the C library
                   12364: function @code{atan2()}.
                   12365: 
1.29      crook    12366: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
                   12367: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
                   12368: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1       anton    12369: because of small errors and the tan will be a very large (or very small)
                   12370: but finite number.
                   12371: 
1.29      crook    12372: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
                   12373: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1       anton    12374: The result is rounded to the nearest float.
                   12375: 
                   12376: @item dividing by zero:
                   12377: @cindex dividing by zero, floating-point
                   12378: @cindex floating-point dividing by zero
                   12379: @cindex floating-point unidentified fault, FP divide-by-zero
                   12380: @code{-55 throw} (Floating-point unidentified fault)
                   12381: 
                   12382: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
                   12383: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
                   12384: System dependent. On IEEE-FP based systems the number is converted into
                   12385: an infinity.
                   12386: 
1.29      crook    12387: @item @i{float}<1 (@code{FACOSH}):
                   12388: @cindex @code{FACOSH}, @i{float}<1
1.1       anton    12389: @cindex floating-point unidentified fault, @code{FACOSH}
                   12390: @code{-55 throw} (Floating-point unidentified fault)
                   12391: 
1.29      crook    12392: @item @i{float}=<-1 (@code{FLNP1}):
                   12393: @cindex @code{FLNP1}, @i{float}=<-1
1.1       anton    12394: @cindex floating-point unidentified fault, @code{FLNP1}
                   12395: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29      crook    12396: negative infinity is typically produced for @i{float}=-1.
1.1       anton    12397: 
1.29      crook    12398: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
                   12399: @cindex @code{FLN}, @i{float}=<0
                   12400: @cindex @code{FLOG}, @i{float}=<0
1.1       anton    12401: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
                   12402: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29      crook    12403: negative infinity is typically produced for @i{float}=0.
1.1       anton    12404: 
1.29      crook    12405: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
                   12406: @cindex @code{FASINH}, @i{float}<0
                   12407: @cindex @code{FSQRT}, @i{float}<0
1.1       anton    12408: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
                   12409: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
                   12410: produces values for these inputs on my Linux box (Bug in the C library?)
                   12411: 
1.29      crook    12412: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
                   12413: @cindex @code{FACOS}, |@i{float}|>1
                   12414: @cindex @code{FASIN}, |@i{float}|>1
                   12415: @cindex @code{FATANH}, |@i{float}|>1
1.1       anton    12416: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
                   12417: @code{-55 throw} (Floating-point unidentified fault).
                   12418: 
1.29      crook    12419: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
                   12420: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1       anton    12421: @cindex floating-point unidentified fault, @code{F>D}
                   12422: @code{-55 throw} (Floating-point unidentified fault).
                   12423: 
                   12424: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
                   12425: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
                   12426: This does not happen.
                   12427: @end table
                   12428: 
                   12429: @c =====================================================================
                   12430: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
                   12431: @section The optional Locals word set
                   12432: @c =====================================================================
                   12433: @cindex system documentation, locals words
                   12434: @cindex locals words, system documentation
                   12435: 
                   12436: @menu
                   12437: * locals-idef::                 Implementation Defined Options                 
                   12438: * locals-ambcond::              Ambiguous Conditions              
                   12439: @end menu
                   12440: 
                   12441: 
                   12442: @c ---------------------------------------------------------------------
                   12443: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
                   12444: @subsection Implementation Defined Options
                   12445: @c ---------------------------------------------------------------------
                   12446: @cindex implementation-defined options, locals words
                   12447: @cindex locals words, implementation-defined options
                   12448: 
                   12449: @table @i
                   12450: @item maximum number of locals in a definition:
                   12451: @cindex maximum number of locals in a definition
                   12452: @cindex locals, maximum number in a definition
                   12453: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
                   12454: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
                   12455: characters. The number of locals in a definition is bounded by the size
                   12456: of locals-buffer, which contains the names of the locals.
                   12457: 
                   12458: @end table
                   12459: 
                   12460: 
                   12461: @c ---------------------------------------------------------------------
                   12462: @node locals-ambcond,  , locals-idef, The optional Locals word set
                   12463: @subsection Ambiguous conditions
                   12464: @c ---------------------------------------------------------------------
                   12465: @cindex locals words, ambiguous conditions
                   12466: @cindex ambiguous conditions, locals words
                   12467: 
                   12468: @table @i
                   12469: @item executing a named local in interpretation state:
                   12470: @cindex local in interpretation state
                   12471: @cindex Interpreting a compile-only word, for a local
                   12472: Locals have no interpretation semantics. If you try to perform the
                   12473: interpretation semantics, you will get a @code{-14 throw} somewhere
                   12474: (Interpreting a compile-only word). If you perform the compilation
                   12475: semantics, the locals access will be compiled (irrespective of state).
                   12476: 
1.29      crook    12477: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1       anton    12478: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
                   12479: @cindex @code{TO} on non-@code{VALUE}s and non-locals
                   12480: @cindex Invalid name argument, @code{TO}
                   12481: @code{-32 throw} (Invalid name argument)
                   12482: 
                   12483: @end table
                   12484: 
                   12485: 
                   12486: @c =====================================================================
                   12487: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
                   12488: @section The optional Memory-Allocation word set
                   12489: @c =====================================================================
                   12490: @cindex system documentation, memory-allocation words
                   12491: @cindex memory-allocation words, system documentation
                   12492: 
                   12493: @menu
                   12494: * memory-idef::                 Implementation Defined Options                 
                   12495: @end menu
                   12496: 
                   12497: 
                   12498: @c ---------------------------------------------------------------------
                   12499: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
                   12500: @subsection Implementation Defined Options
                   12501: @c ---------------------------------------------------------------------
                   12502: @cindex implementation-defined options, memory-allocation words
                   12503: @cindex memory-allocation words, implementation-defined options
                   12504: 
                   12505: @table @i
1.29      crook    12506: @item values and meaning of @i{ior}:
                   12507: @cindex  @i{ior} values and meaning
                   12508: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    12509: intended as throw codes. They typically are in the range
                   12510: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    12511: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    12512: 
                   12513: @end table
                   12514: 
                   12515: @c =====================================================================
                   12516: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
                   12517: @section The optional Programming-Tools word set
                   12518: @c =====================================================================
                   12519: @cindex system documentation, programming-tools words
                   12520: @cindex programming-tools words, system documentation
                   12521: 
                   12522: @menu
                   12523: * programming-idef::            Implementation Defined Options            
                   12524: * programming-ambcond::         Ambiguous Conditions         
                   12525: @end menu
                   12526: 
                   12527: 
                   12528: @c ---------------------------------------------------------------------
                   12529: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
                   12530: @subsection Implementation Defined Options
                   12531: @c ---------------------------------------------------------------------
                   12532: @cindex implementation-defined options, programming-tools words
                   12533: @cindex programming-tools words, implementation-defined options
                   12534: 
                   12535: @table @i
                   12536: @item ending sequence for input following @code{;CODE} and @code{CODE}:
                   12537: @cindex @code{;CODE} ending sequence
                   12538: @cindex @code{CODE} ending sequence
                   12539: @code{END-CODE}
                   12540: 
                   12541: @item manner of processing input following @code{;CODE} and @code{CODE}:
                   12542: @cindex @code{;CODE}, processing input
                   12543: @cindex @code{CODE}, processing input
                   12544: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
                   12545: the input is processed by the text interpreter, (starting) in interpret
                   12546: state.
                   12547: 
                   12548: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
                   12549: @cindex @code{ASSEMBLER}, search order capability
                   12550: The ANS Forth search order word set.
                   12551: 
                   12552: @item source and format of display by @code{SEE}:
                   12553: @cindex @code{SEE}, source and format of output
                   12554: The source for @code{see} is the intermediate code used by the inner
                   12555: interpreter.  The current @code{see} tries to output Forth source code
                   12556: as well as possible.
                   12557: 
                   12558: @end table
                   12559: 
                   12560: @c ---------------------------------------------------------------------
                   12561: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
                   12562: @subsection Ambiguous conditions
                   12563: @c ---------------------------------------------------------------------
                   12564: @cindex programming-tools words, ambiguous conditions
                   12565: @cindex ambiguous conditions, programming-tools words
                   12566: 
                   12567: @table @i
                   12568: 
1.21      crook    12569: @item deleting the compilation word list (@code{FORGET}):
                   12570: @cindex @code{FORGET}, deleting the compilation word list
1.1       anton    12571: Not implemented (yet).
                   12572: 
1.29      crook    12573: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
                   12574: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
                   12575: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1       anton    12576: @cindex control-flow stack underflow
                   12577: This typically results in an @code{abort"} with a descriptive error
                   12578: message (may change into a @code{-22 throw} (Control structure mismatch)
                   12579: in the future). You may also get a memory access error. If you are
                   12580: unlucky, this ambiguous condition is not caught.
                   12581: 
1.29      crook    12582: @item @i{name} can't be found (@code{FORGET}):
                   12583: @cindex @code{FORGET}, @i{name} can't be found
1.1       anton    12584: Not implemented (yet).
                   12585: 
1.29      crook    12586: @item @i{name} not defined via @code{CREATE}:
                   12587: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1       anton    12588: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
                   12589: the execution semantics of the last defined word no matter how it was
                   12590: defined.
                   12591: 
                   12592: @item @code{POSTPONE} applied to @code{[IF]}:
                   12593: @cindex @code{POSTPONE} applied to @code{[IF]}
                   12594: @cindex @code{[IF]} and @code{POSTPONE}
                   12595: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
                   12596: equivalent to @code{[IF]}.
                   12597: 
                   12598: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
                   12599: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
                   12600: Continue in the same state of conditional compilation in the next outer
                   12601: input source. Currently there is no warning to the user about this.
                   12602: 
                   12603: @item removing a needed definition (@code{FORGET}):
                   12604: @cindex @code{FORGET}, removing a needed definition
                   12605: Not implemented (yet).
                   12606: 
                   12607: @end table
                   12608: 
                   12609: 
                   12610: @c =====================================================================
                   12611: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
                   12612: @section The optional Search-Order word set
                   12613: @c =====================================================================
                   12614: @cindex system documentation, search-order words
                   12615: @cindex search-order words, system documentation
                   12616: 
                   12617: @menu
                   12618: * search-idef::                 Implementation Defined Options                 
                   12619: * search-ambcond::              Ambiguous Conditions              
                   12620: @end menu
                   12621: 
                   12622: 
                   12623: @c ---------------------------------------------------------------------
                   12624: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
                   12625: @subsection Implementation Defined Options
                   12626: @c ---------------------------------------------------------------------
                   12627: @cindex implementation-defined options, search-order words
                   12628: @cindex search-order words, implementation-defined options
                   12629: 
                   12630: @table @i
                   12631: @item maximum number of word lists in search order:
                   12632: @cindex maximum number of word lists in search order
                   12633: @cindex search order, maximum depth
                   12634: @code{s" wordlists" environment? drop .}. Currently 16.
                   12635: 
                   12636: @item minimum search order:
                   12637: @cindex minimum search order
                   12638: @cindex search order, minimum
                   12639: @code{root root}.
                   12640: 
                   12641: @end table
                   12642: 
                   12643: @c ---------------------------------------------------------------------
                   12644: @node search-ambcond,  , search-idef, The optional Search-Order word set
                   12645: @subsection Ambiguous conditions
                   12646: @c ---------------------------------------------------------------------
                   12647: @cindex search-order words, ambiguous conditions
                   12648: @cindex ambiguous conditions, search-order words
                   12649: 
                   12650: @table @i
1.21      crook    12651: @item changing the compilation word list (during compilation):
                   12652: @cindex changing the compilation word list (during compilation)
                   12653: @cindex compilation word list, change before definition ends
                   12654: The word is entered into the word list that was the compilation word list
1.1       anton    12655: at the start of the definition. Any changes to the name field (e.g.,
                   12656: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
                   12657: are applied to the latest defined word (as reported by @code{last} or
1.21      crook    12658: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1       anton    12659: 
                   12660: @item search order empty (@code{previous}):
                   12661: @cindex @code{previous}, search order empty
1.26      crook    12662: @cindex vocstack empty, @code{previous}
1.1       anton    12663: @code{abort" Vocstack empty"}.
                   12664: 
                   12665: @item too many word lists in search order (@code{also}):
                   12666: @cindex @code{also}, too many word lists in search order
1.26      crook    12667: @cindex vocstack full, @code{also}
1.1       anton    12668: @code{abort" Vocstack full"}.
                   12669: 
                   12670: @end table
                   12671: 
                   12672: @c ***************************************************************
                   12673: @node Model, Integrating Gforth, ANS conformance, Top
                   12674: @chapter Model
                   12675: 
                   12676: This chapter has yet to be written. It will contain information, on
                   12677: which internal structures you can rely.
                   12678: 
                   12679: @c ***************************************************************
                   12680: @node Integrating Gforth, Emacs and Gforth, Model, Top
                   12681: @chapter Integrating Gforth into C programs
                   12682: 
                   12683: This is not yet implemented.
                   12684: 
                   12685: Several people like to use Forth as scripting language for applications
                   12686: that are otherwise written in C, C++, or some other language.
                   12687: 
                   12688: The Forth system ATLAST provides facilities for embedding it into
                   12689: applications; unfortunately it has several disadvantages: most
                   12690: importantly, it is not based on ANS Forth, and it is apparently dead
                   12691: (i.e., not developed further and not supported). The facilities
1.21      crook    12692: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1       anton    12693: making the switch should not be hard.
                   12694: 
                   12695: We also tried to design the interface such that it can easily be
                   12696: implemented by other Forth systems, so that we may one day arrive at a
                   12697: standardized interface. Such a standard interface would allow you to
                   12698: replace the Forth system without having to rewrite C code.
                   12699: 
                   12700: You embed the Gforth interpreter by linking with the library
                   12701: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
                   12702: global symbols in this library that belong to the interface, have the
                   12703: prefix @code{forth_}. (Global symbols that are used internally have the
                   12704: prefix @code{gforth_}).
                   12705: 
                   12706: You can include the declarations of Forth types and the functions and
                   12707: variables of the interface with @code{#include <forth.h>}.
                   12708: 
                   12709: Types.
                   12710: 
                   12711: Variables.
                   12712: 
                   12713: Data and FP Stack pointer. Area sizes.
                   12714: 
                   12715: functions.
                   12716: 
                   12717: forth_init(imagefile)
                   12718: forth_evaluate(string) exceptions?
                   12719: forth_goto(address) (or forth_execute(xt)?)
                   12720: forth_continue() (a corountining mechanism)
                   12721: 
                   12722: Adding primitives.
                   12723: 
                   12724: No checking.
                   12725: 
                   12726: Signals?
                   12727: 
                   12728: Accessing the Stacks
                   12729: 
1.26      crook    12730: @c ******************************************************************
1.1       anton    12731: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
                   12732: @chapter Emacs and Gforth
                   12733: @cindex Emacs and Gforth
                   12734: 
                   12735: @cindex @file{gforth.el}
                   12736: @cindex @file{forth.el}
                   12737: @cindex Rydqvist, Goran
                   12738: @cindex comment editing commands
                   12739: @cindex @code{\}, editing with Emacs
                   12740: @cindex debug tracer editing commands
                   12741: @cindex @code{~~}, removal with Emacs
                   12742: @cindex Forth mode in Emacs
                   12743: Gforth comes with @file{gforth.el}, an improved version of
                   12744: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26      crook    12745: improvements are:
                   12746: 
                   12747: @itemize @bullet
                   12748: @item
                   12749: A better (but still not perfect) handling of indentation.
                   12750: @item
                   12751: Comment paragraph filling (@kbd{M-q})
                   12752: @item
                   12753: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
                   12754: @item
                   12755: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41      anton    12756: @item
                   12757: Support of the @code{info-lookup} feature for looking up the
                   12758: documentation of a word.
1.26      crook    12759: @end itemize
                   12760: 
                   12761: I left the stuff I do not use alone, even though some of it only makes
                   12762: sense for TILE. To get a description of these features, enter Forth mode
                   12763: and type @kbd{C-h m}.
1.1       anton    12764: 
                   12765: @cindex source location of error or debugging output in Emacs
                   12766: @cindex error output, finding the source location in Emacs
                   12767: @cindex debugging output, finding the source location in Emacs
                   12768: In addition, Gforth supports Emacs quite well: The source code locations
                   12769: given in error messages, debugging output (from @code{~~}) and failed
                   12770: assertion messages are in the right format for Emacs' compilation mode
                   12771: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
                   12772: Manual}) so the source location corresponding to an error or other
                   12773: message is only a few keystrokes away (@kbd{C-x `} for the next error,
                   12774: @kbd{C-c C-c} for the error under the cursor).
                   12775: 
                   12776: @cindex @file{TAGS} file
                   12777: @cindex @file{etags.fs}
                   12778: @cindex viewing the source of a word in Emacs
1.43      anton    12779: @cindex @code{require}, placement in files
                   12780: @cindex @code{include}, placement in files
                   12781: Also, if you @code{require} @file{etags.fs}, a new @file{TAGS} file will
1.26      crook    12782: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1       anton    12783: contains the definitions of all words defined afterwards. You can then
                   12784: find the source for a word using @kbd{M-.}. Note that emacs can use
                   12785: several tags files at the same time (e.g., one for the Gforth sources
                   12786: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
                   12787: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
                   12788: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43      anton    12789: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
                   12790: with @file{etags.fs}, you should avoid putting definitions both before
                   12791: and after @code{require} etc., otherwise you will see the same file
                   12792: visited several times by commands like @code{tags-search}.
1.1       anton    12793: 
1.41      anton    12794: @cindex viewing the documentation of a word in Emacs
                   12795: @cindex context-sensitive help
                   12796: Moreover, for words documented in this manual, you can look up the
                   12797: glossary entry quickly by using @kbd{C-h TAB}
                   12798: (@code{info-lookup-symbol}, see @pxref{Documentation, ,Documentation
                   12799: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
1.42      anton    12800: later and does not work for words containing @code{:}.
1.41      anton    12801: 
                   12802: 
1.1       anton    12803: @cindex @file{.emacs}
                   12804: To get all these benefits, add the following lines to your @file{.emacs}
                   12805: file:
                   12806: 
                   12807: @example
                   12808: (autoload 'forth-mode "gforth.el")
                   12809: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
                   12810: @end example
                   12811: 
1.26      crook    12812: @c ******************************************************************
1.1       anton    12813: @node Image Files, Engine, Emacs and Gforth, Top
                   12814: @chapter Image Files
1.26      crook    12815: @cindex image file
                   12816: @cindex @file{.fi} files
1.1       anton    12817: @cindex precompiled Forth code
                   12818: @cindex dictionary in persistent form
                   12819: @cindex persistent form of dictionary
                   12820: 
                   12821: An image file is a file containing an image of the Forth dictionary,
                   12822: i.e., compiled Forth code and data residing in the dictionary.  By
                   12823: convention, we use the extension @code{.fi} for image files.
                   12824: 
                   12825: @menu
1.18      anton    12826: * Image Licensing Issues::      Distribution terms for images.
                   12827: * Image File Background::       Why have image files?
1.29      crook    12828: * Non-Relocatable Image Files::   don't always work.
1.18      anton    12829: * Data-Relocatable Image Files::  are better.
1.29      crook    12830: * Fully Relocatable Image Files:: better yet.
1.18      anton    12831: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.29      crook    12832: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.18      anton    12833: * Modifying the Startup Sequence::  and turnkey applications.
1.1       anton    12834: @end menu
                   12835: 
1.18      anton    12836: @node Image Licensing Issues, Image File Background, Image Files, Image Files
                   12837: @section Image Licensing Issues
                   12838: @cindex license for images
                   12839: @cindex image license
                   12840: 
                   12841: An image created with @code{gforthmi} (@pxref{gforthmi}) or
                   12842: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
                   12843: original image; i.e., according to copyright law it is a derived work of
                   12844: the original image.
                   12845: 
                   12846: Since Gforth is distributed under the GNU GPL, the newly created image
                   12847: falls under the GNU GPL, too. In particular, this means that if you
                   12848: distribute the image, you have to make all of the sources for the image
                   12849: available, including those you wrote.  For details see @ref{License, ,
                   12850: GNU General Public License (Section 3)}.
                   12851: 
                   12852: If you create an image with @code{cross} (@pxref{cross.fs}), the image
                   12853: contains only code compiled from the sources you gave it; if none of
                   12854: these sources is under the GPL, the terms discussed above do not apply
                   12855: to the image. However, if your image needs an engine (a gforth binary)
                   12856: that is under the GPL, you should make sure that you distribute both in
                   12857: a way that is at most a @emph{mere aggregation}, if you don't want the
                   12858: terms of the GPL to apply to the image.
                   12859: 
                   12860: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1       anton    12861: @section Image File Background
                   12862: @cindex image file background
                   12863: 
                   12864: Our Forth system consists not only of primitives, but also of
                   12865: definitions written in Forth. Since the Forth compiler itself belongs to
                   12866: those definitions, it is not possible to start the system with the
                   12867: primitives and the Forth source alone. Therefore we provide the Forth
1.26      crook    12868: code as an image file in nearly executable form. When Gforth starts up,
                   12869: a C routine loads the image file into memory, optionally relocates the
                   12870: addresses, then sets up the memory (stacks etc.) according to
                   12871: information in the image file, and (finally) starts executing Forth
                   12872: code.
1.1       anton    12873: 
                   12874: The image file variants represent different compromises between the
                   12875: goals of making it easy to generate image files and making them
                   12876: portable.
                   12877: 
                   12878: @cindex relocation at run-time
1.26      crook    12879: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1       anton    12880: run-time. This avoids many of the complications discussed below (image
                   12881: files are data relocatable without further ado), but costs performance
                   12882: (one addition per memory access).
                   12883: 
                   12884: @cindex relocation at load-time
1.26      crook    12885: By contrast, the Gforth loader performs relocation at image load time. The
                   12886: loader also has to replace tokens that represent primitive calls with the
1.1       anton    12887: appropriate code-field addresses (or code addresses in the case of
                   12888: direct threading).
                   12889: 
                   12890: There are three kinds of image files, with different degrees of
                   12891: relocatability: non-relocatable, data-relocatable, and fully relocatable
                   12892: image files.
                   12893: 
                   12894: @cindex image file loader
                   12895: @cindex relocating loader
                   12896: @cindex loader for image files
                   12897: These image file variants have several restrictions in common; they are
                   12898: caused by the design of the image file loader:
                   12899: 
                   12900: @itemize @bullet
                   12901: @item
                   12902: There is only one segment; in particular, this means, that an image file
                   12903: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26      crook    12904: them). The contents of the stacks are not represented, either.
1.1       anton    12905: 
                   12906: @item
                   12907: The only kinds of relocation supported are: adding the same offset to
                   12908: all cells that represent data addresses; and replacing special tokens
                   12909: with code addresses or with pieces of machine code.
                   12910: 
                   12911: If any complex computations involving addresses are performed, the
                   12912: results cannot be represented in the image file. Several applications that
                   12913: use such computations come to mind:
                   12914: @itemize @minus
                   12915: @item
                   12916: Hashing addresses (or data structures which contain addresses) for table
                   12917: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
                   12918: purpose, you will have no problem, because the hash tables are
                   12919: recomputed automatically when the system is started. If you use your own
                   12920: hash tables, you will have to do something similar.
                   12921: 
                   12922: @item
                   12923: There's a cute implementation of doubly-linked lists that uses
                   12924: @code{XOR}ed addresses. You could represent such lists as singly-linked
                   12925: in the image file, and restore the doubly-linked representation on
                   12926: startup.@footnote{In my opinion, though, you should think thrice before
                   12927: using a doubly-linked list (whatever implementation).}
                   12928: 
                   12929: @item
                   12930: The code addresses of run-time routines like @code{docol:} cannot be
                   12931: represented in the image file (because their tokens would be replaced by
                   12932: machine code in direct threaded implementations). As a workaround,
                   12933: compute these addresses at run-time with @code{>code-address} from the
                   12934: executions tokens of appropriate words (see the definitions of
                   12935: @code{docol:} and friends in @file{kernel.fs}).
                   12936: 
                   12937: @item
                   12938: On many architectures addresses are represented in machine code in some
                   12939: shifted or mangled form. You cannot put @code{CODE} words that contain
                   12940: absolute addresses in this form in a relocatable image file. Workarounds
                   12941: are representing the address in some relative form (e.g., relative to
                   12942: the CFA, which is present in some register), or loading the address from
                   12943: a place where it is stored in a non-mangled form.
                   12944: @end itemize
                   12945: @end itemize
                   12946: 
                   12947: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
                   12948: @section Non-Relocatable Image Files
                   12949: @cindex non-relocatable image files
1.26      crook    12950: @cindex image file, non-relocatable
1.1       anton    12951: 
                   12952: These files are simple memory dumps of the dictionary. They are specific
                   12953: to the executable (i.e., @file{gforth} file) they were created
                   12954: with. What's worse, they are specific to the place on which the
                   12955: dictionary resided when the image was created. Now, there is no
                   12956: guarantee that the dictionary will reside at the same place the next
                   12957: time you start Gforth, so there's no guarantee that a non-relocatable
                   12958: image will work the next time (Gforth will complain instead of crashing,
                   12959: though).
                   12960: 
                   12961: You can create a non-relocatable image file with
                   12962: 
1.44      crook    12963: 
1.1       anton    12964: doc-savesystem
                   12965: 
1.44      crook    12966: 
1.1       anton    12967: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
                   12968: @section Data-Relocatable Image Files
                   12969: @cindex data-relocatable image files
1.26      crook    12970: @cindex image file, data-relocatable
1.1       anton    12971: 
                   12972: These files contain relocatable data addresses, but fixed code addresses
                   12973: (instead of tokens). They are specific to the executable (i.e.,
                   12974: @file{gforth} file) they were created with. For direct threading on some
                   12975: architectures (e.g., the i386), data-relocatable images do not work. You
                   12976: get a data-relocatable image, if you use @file{gforthmi} with a
                   12977: Gforth binary that is not doubly indirect threaded (@pxref{Fully
                   12978: Relocatable Image Files}).
                   12979: 
                   12980: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
                   12981: @section Fully Relocatable Image Files
                   12982: @cindex fully relocatable image files
1.26      crook    12983: @cindex image file, fully relocatable
1.1       anton    12984: 
                   12985: @cindex @file{kern*.fi}, relocatability
                   12986: @cindex @file{gforth.fi}, relocatability
                   12987: These image files have relocatable data addresses, and tokens for code
                   12988: addresses. They can be used with different binaries (e.g., with and
                   12989: without debugging) on the same machine, and even across machines with
                   12990: the same data formats (byte order, cell size, floating point
                   12991: format). However, they are usually specific to the version of Gforth
                   12992: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
                   12993: are fully relocatable.
                   12994: 
                   12995: There are two ways to create a fully relocatable image file:
                   12996: 
                   12997: @menu
1.29      crook    12998: * gforthmi::                    The normal way
1.1       anton    12999: * cross.fs::                    The hard way
                   13000: @end menu
                   13001: 
                   13002: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
                   13003: @subsection @file{gforthmi}
                   13004: @cindex @file{comp-i.fs}
                   13005: @cindex @file{gforthmi}
                   13006: 
                   13007: You will usually use @file{gforthmi}. If you want to create an
1.29      crook    13008: image @i{file} that contains everything you would load by invoking
                   13009: Gforth with @code{gforth @i{options}}, you simply say:
1.1       anton    13010: @example
1.29      crook    13011: gforthmi @i{file} @i{options}
1.1       anton    13012: @end example
                   13013: 
                   13014: E.g., if you want to create an image @file{asm.fi} that has the file
                   13015: @file{asm.fs} loaded in addition to the usual stuff, you could do it
                   13016: like this:
                   13017: 
                   13018: @example
                   13019: gforthmi asm.fi asm.fs
                   13020: @end example
                   13021: 
1.27      crook    13022: @file{gforthmi} is implemented as a sh script and works like this: It
                   13023: produces two non-relocatable images for different addresses and then
                   13024: compares them. Its output reflects this: first you see the output (if
                   13025: any) of the two Gforth invocations that produce the nonrelocatable image
                   13026: files, then you see the output of the comparing program: It displays the
                   13027: offset used for data addresses and the offset used for code addresses;
1.1       anton    13028: moreover, for each cell that cannot be represented correctly in the
1.44      crook    13029: image files, it displays a line like this:
1.1       anton    13030: 
                   13031: @example
                   13032:      78DC         BFFFFA50         BFFFFA40
                   13033: @end example
                   13034: 
                   13035: This means that at offset $78dc from @code{forthstart}, one input image
                   13036: contains $bffffa50, and the other contains $bffffa40. Since these cells
                   13037: cannot be represented correctly in the output image, you should examine
                   13038: these places in the dictionary and verify that these cells are dead
                   13039: (i.e., not read before they are written).
1.39      anton    13040: 
                   13041: @cindex --application, @code{gforthmi} option
                   13042: If you insert the option @code{--application} in front of the image file
                   13043: name, you will get an image that uses the @code{--appl-image} option
                   13044: instead of the @code{--image-file} option (@pxref{Invoking
                   13045: Gforth}). When you execute such an image on Unix (by typing the image
                   13046: name as command), the Gforth engine will pass all options to the image
                   13047: instead of trying to interpret them as engine options.
1.1       anton    13048: 
1.27      crook    13049: If you type @file{gforthmi} with no arguments, it prints some usage
                   13050: instructions.
                   13051: 
1.1       anton    13052: @cindex @code{savesystem} during @file{gforthmi}
                   13053: @cindex @code{bye} during @file{gforthmi}
                   13054: @cindex doubly indirect threaded code
1.44      crook    13055: @cindex environment variables
                   13056: @cindex @code{GFORTHD} -- environment variable
                   13057: @cindex @code{GFORTH} -- environment variable
1.1       anton    13058: @cindex @code{gforth-ditc}
1.29      crook    13059: There are a few wrinkles: After processing the passed @i{options}, the
1.1       anton    13060: words @code{savesystem} and @code{bye} must be visible. A special doubly
                   13061: indirect threaded version of the @file{gforth} executable is used for
                   13062: creating the nonrelocatable images; you can pass the exact filename of
                   13063: this executable through the environment variable @code{GFORTHD}
                   13064: (default: @file{gforth-ditc}); if you pass a version that is not doubly
                   13065: indirect threaded, you will not get a fully relocatable image, but a
1.27      crook    13066: data-relocatable image (because there is no code address offset). The
                   13067: normal @file{gforth} executable is used for creating the relocatable
                   13068: image; you can pass the exact filename of this executable through the
                   13069: environment variable @code{GFORTH}.
1.1       anton    13070: 
                   13071: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
                   13072: @subsection @file{cross.fs}
                   13073: @cindex @file{cross.fs}
                   13074: @cindex cross-compiler
                   13075: @cindex metacompiler
1.47      crook    13076: @cindex target compiler
1.1       anton    13077: 
                   13078: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47      crook    13079: programming language (@pxref{Cross Compiler}).
1.1       anton    13080: 
1.47      crook    13081: @code{cross} allows you to create image files for machines with
1.1       anton    13082: different data sizes and data formats than the one used for generating
                   13083: the image file. You can also use it to create an application image that
                   13084: does not contain a Forth compiler. These features are bought with
                   13085: restrictions and inconveniences in programming. E.g., addresses have to
                   13086: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
                   13087: order to make the code relocatable.
                   13088: 
                   13089: 
                   13090: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
                   13091: @section Stack and Dictionary Sizes
                   13092: @cindex image file, stack and dictionary sizes
                   13093: @cindex dictionary size default
                   13094: @cindex stack size default
                   13095: 
                   13096: If you invoke Gforth with a command line flag for the size
                   13097: (@pxref{Invoking Gforth}), the size you specify is stored in the
                   13098: dictionary. If you save the dictionary with @code{savesystem} or create
                   13099: an image with @file{gforthmi}, this size will become the default
                   13100: for the resulting image file. E.g., the following will create a
1.21      crook    13101: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1       anton    13102: 
                   13103: @example
                   13104: gforthmi gforth.fi -m 1M
                   13105: @end example
                   13106: 
                   13107: In other words, if you want to set the default size for the dictionary
                   13108: and the stacks of an image, just invoke @file{gforthmi} with the
                   13109: appropriate options when creating the image.
                   13110: 
                   13111: @cindex stack size, cache-friendly
                   13112: Note: For cache-friendly behaviour (i.e., good performance), you should
                   13113: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
                   13114: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
                   13115: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
                   13116: 
                   13117: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
                   13118: @section Running Image Files
                   13119: @cindex running image files
                   13120: @cindex invoking image files
                   13121: @cindex image file invocation
                   13122: 
                   13123: @cindex -i, invoke image file
                   13124: @cindex --image file, invoke image file
1.29      crook    13125: You can invoke Gforth with an image file @i{image} instead of the
1.1       anton    13126: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
                   13127: @example
1.29      crook    13128: gforth -i @i{image}
1.1       anton    13129: @end example
                   13130: 
                   13131: @cindex executable image file
1.26      crook    13132: @cindex image file, executable
1.1       anton    13133: If your operating system supports starting scripts with a line of the
                   13134: form @code{#! ...}, you just have to type the image file name to start
                   13135: Gforth with this image file (note that the file extension @code{.fi} is
1.29      crook    13136: just a convention). I.e., to run Gforth with the image file @i{image},
                   13137: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27      crook    13138: This works because every @code{.fi} file starts with a line of this
                   13139: format:
                   13140: 
                   13141: @example
                   13142: #! /usr/local/bin/gforth-0.4.0 -i
                   13143: @end example
                   13144: 
                   13145: The file and pathname for the Gforth engine specified on this line is
                   13146: the specific Gforth executable that it was built against; i.e. the value
                   13147: of the environment variable @code{GFORTH} at the time that
                   13148: @file{gforthmi} was executed.
1.1       anton    13149: 
1.27      crook    13150: You can make use of the same shell capability to make a Forth source
                   13151: file into an executable. For example, if you place this text in a file:
1.26      crook    13152: 
                   13153: @example
                   13154: #! /usr/local/bin/gforth
                   13155: 
                   13156: ." Hello, world" CR
                   13157: bye
                   13158: @end example
                   13159: 
                   13160: @noindent
1.27      crook    13161: and then make the file executable (chmod +x in Unix), you can run it
1.26      crook    13162: directly from the command line. The sequence @code{#!} is used in two
                   13163: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29      crook    13164: system@footnote{The Unix kernel actually recognises two types of files:
                   13165: executable files and files of data, where the data is processed by an
                   13166: interpreter that is specified on the ``interpreter line'' -- the first
                   13167: line of the file, starting with the sequence #!. There may be a small
                   13168: limit (e.g., 32) on the number of characters that may be specified on
                   13169: the interpreter line.} secondly it is treated as a comment character by
                   13170: Gforth. Because of the second usage, a space is required between
                   13171: @code{#!} and the path to the executable.
1.27      crook    13172: 
                   13173: The disadvantage of this latter technique, compared with using
                   13174: @file{gforthmi}, is that it is slower; the Forth source code is compiled
                   13175: on-the-fly, each time the program is invoked.
                   13176: 
1.26      crook    13177: 
1.1       anton    13178: doc-#!
                   13179: 
1.44      crook    13180: 
1.1       anton    13181: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
                   13182: @section Modifying the Startup Sequence
                   13183: @cindex startup sequence for image file
                   13184: @cindex image file initialization sequence
                   13185: @cindex initialization sequence of image file
                   13186: 
                   13187: You can add your own initialization to the startup sequence through the
1.26      crook    13188: deferred word @code{'cold}. @code{'cold} is invoked just before the
                   13189: image-specific command line processing (by default, loading files and
                   13190: evaluating (@code{-e}) strings) starts.
1.1       anton    13191: 
                   13192: A sequence for adding your initialization usually looks like this:
                   13193: 
                   13194: @example
                   13195: :noname
                   13196:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
                   13197:     ... \ your stuff
                   13198: ; IS 'cold
                   13199: @end example
                   13200: 
                   13201: @cindex turnkey image files
1.26      crook    13202: @cindex image file, turnkey applications
1.1       anton    13203: You can make a turnkey image by letting @code{'cold} execute a word
                   13204: (your turnkey application) that never returns; instead, it exits Gforth
                   13205: via @code{bye} or @code{throw}.
                   13206: 
                   13207: @cindex command-line arguments, access
                   13208: @cindex arguments on the command line, access
                   13209: You can access the (image-specific) command-line arguments through the
1.26      crook    13210: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1       anton    13211: access to @code{argv}.
                   13212: 
1.26      crook    13213: If @code{'cold} exits normally, Gforth processes the command-line
                   13214: arguments as files to be loaded and strings to be evaluated.  Therefore,
                   13215: @code{'cold} should remove the arguments it has used in this case.
                   13216: 
1.44      crook    13217: 
                   13218: 
1.26      crook    13219: doc-'cold
1.1       anton    13220: doc-argc
                   13221: doc-argv
                   13222: doc-arg
                   13223: 
                   13224: 
1.44      crook    13225: 
1.1       anton    13226: @c ******************************************************************
1.13      pazsan   13227: @node Engine, Binding to System Library, Image Files, Top
1.1       anton    13228: @chapter Engine
                   13229: @cindex engine
                   13230: @cindex virtual machine
                   13231: 
1.26      crook    13232: Reading this chapter is not necessary for programming with Gforth. It
1.1       anton    13233: may be helpful for finding your way in the Gforth sources.
                   13234: 
                   13235: The ideas in this section have also been published in the papers
                   13236: @cite{ANS fig/GNU/??? Forth} (in German) by Bernd Paysan, presented at
                   13237: the Forth-Tagung '93 and @cite{A Portable Forth Engine} by M. Anton
                   13238: Ertl, presented at EuroForth '93; the latter is available at
1.47      crook    13239: @*@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z}.
1.1       anton    13240: 
                   13241: @menu
                   13242: * Portability::                 
                   13243: * Threading::                   
                   13244: * Primitives::                  
                   13245: * Performance::                 
                   13246: @end menu
                   13247: 
                   13248: @node Portability, Threading, Engine, Engine
                   13249: @section Portability
                   13250: @cindex engine portability
                   13251: 
1.26      crook    13252: An important goal of the Gforth Project is availability across a wide
                   13253: range of personal machines. fig-Forth, and, to a lesser extent, F83,
                   13254: achieved this goal by manually coding the engine in assembly language
                   13255: for several then-popular processors. This approach is very
                   13256: labor-intensive and the results are short-lived due to progress in
                   13257: computer architecture.
1.1       anton    13258: 
                   13259: @cindex C, using C for the engine
                   13260: Others have avoided this problem by coding in C, e.g., Mitch Bradley
                   13261: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
                   13262: particularly popular for UNIX-based Forths due to the large variety of
                   13263: architectures of UNIX machines. Unfortunately an implementation in C
                   13264: does not mix well with the goals of efficiency and with using
                   13265: traditional techniques: Indirect or direct threading cannot be expressed
                   13266: in C, and switch threading, the fastest technique available in C, is
                   13267: significantly slower. Another problem with C is that it is very
                   13268: cumbersome to express double integer arithmetic.
                   13269: 
                   13270: @cindex GNU C for the engine
                   13271: @cindex long long
                   13272: Fortunately, there is a portable language that does not have these
                   13273: limitations: GNU C, the version of C processed by the GNU C compiler
                   13274: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
                   13275: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
                   13276: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
                   13277: threading possible, its @code{long long} type (@pxref{Long Long, ,
                   13278: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
                   13279: double numbers@footnote{Unfortunately, long longs are not implemented
                   13280: properly on all machines (e.g., on alpha-osf1, long longs are only 64
                   13281: bits, the same size as longs (and pointers), but they should be twice as
1.4       anton    13282: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1       anton    13283: C Manual}). So, we had to implement doubles in C after all. Still, on
                   13284: most machines we can use long longs and achieve better performance than
                   13285: with the emulation package.}. GNU C is available for free on all
                   13286: important (and many unimportant) UNIX machines, VMS, 80386s running
                   13287: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
                   13288: on all these machines.
                   13289: 
                   13290: Writing in a portable language has the reputation of producing code that
                   13291: is slower than assembly. For our Forth engine we repeatedly looked at
                   13292: the code produced by the compiler and eliminated most compiler-induced
                   13293: inefficiencies by appropriate changes in the source code.
                   13294: 
                   13295: @cindex explicit register declarations
                   13296: @cindex --enable-force-reg, configuration flag
                   13297: @cindex -DFORCE_REG
                   13298: However, register allocation cannot be portably influenced by the
                   13299: programmer, leading to some inefficiencies on register-starved
                   13300: machines. We use explicit register declarations (@pxref{Explicit Reg
                   13301: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
                   13302: improve the speed on some machines. They are turned on by using the
                   13303: configuration flag @code{--enable-force-reg} (@code{gcc} switch
                   13304: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
                   13305: machine, but also on the compiler version: On some machines some
                   13306: compiler versions produce incorrect code when certain explicit register
                   13307: declarations are used. So by default @code{-DFORCE_REG} is not used.
                   13308: 
                   13309: @node Threading, Primitives, Portability, Engine
                   13310: @section Threading
                   13311: @cindex inner interpreter implementation
                   13312: @cindex threaded code implementation
                   13313: 
                   13314: @cindex labels as values
                   13315: GNU C's labels as values extension (available since @code{gcc-2.0},
                   13316: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29      crook    13317: makes it possible to take the address of @i{label} by writing
                   13318: @code{&&@i{label}}.  This address can then be used in a statement like
                   13319: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1       anton    13320: @code{goto x}.
                   13321: 
1.26      crook    13322: @cindex @code{NEXT}, indirect threaded
1.1       anton    13323: @cindex indirect threaded inner interpreter
                   13324: @cindex inner interpreter, indirect threaded
1.26      crook    13325: With this feature an indirect threaded @code{NEXT} looks like:
1.1       anton    13326: @example
                   13327: cfa = *ip++;
                   13328: ca = *cfa;
                   13329: goto *ca;
                   13330: @end example
                   13331: @cindex instruction pointer
                   13332: For those unfamiliar with the names: @code{ip} is the Forth instruction
                   13333: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
                   13334: execution token and points to the code field of the next word to be
                   13335: executed; The @code{ca} (code address) fetched from there points to some
                   13336: executable code, e.g., a primitive or the colon definition handler
                   13337: @code{docol}.
                   13338: 
1.26      crook    13339: @cindex @code{NEXT}, direct threaded
1.1       anton    13340: @cindex direct threaded inner interpreter
                   13341: @cindex inner interpreter, direct threaded
                   13342: Direct threading is even simpler:
                   13343: @example
                   13344: ca = *ip++;
                   13345: goto *ca;
                   13346: @end example
                   13347: 
                   13348: Of course we have packaged the whole thing neatly in macros called
1.26      crook    13349: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1       anton    13350: 
                   13351: @menu
                   13352: * Scheduling::                  
                   13353: * Direct or Indirect Threaded?::  
                   13354: * DOES>::                       
                   13355: @end menu
                   13356: 
                   13357: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
                   13358: @subsection Scheduling
                   13359: @cindex inner interpreter optimization
                   13360: 
                   13361: There is a little complication: Pipelined and superscalar processors,
                   13362: i.e., RISC and some modern CISC machines can process independent
                   13363: instructions while waiting for the results of an instruction. The
                   13364: compiler usually reorders (schedules) the instructions in a way that
                   13365: achieves good usage of these delay slots. However, on our first tries
                   13366: the compiler did not do well on scheduling primitives. E.g., for
                   13367: @code{+} implemented as
                   13368: @example
                   13369: n=sp[0]+sp[1];
                   13370: sp++;
                   13371: sp[0]=n;
                   13372: NEXT;
                   13373: @end example
1.26      crook    13374: the @code{NEXT} comes strictly after the other code, i.e., there is nearly no
1.1       anton    13375: scheduling. After a little thought the problem becomes clear: The
1.21      crook    13376: compiler cannot know that @code{sp} and @code{ip} point to different
                   13377: addresses (and the version of @code{gcc} we used would not know it even
                   13378: if it was possible), so it could not move the load of the cfa above the
                   13379: store to the TOS. Indeed the pointers could be the same, if code on or
                   13380: very near the top of stack were executed. In the interest of speed we
                   13381: chose to forbid this probably unused ``feature'' and helped the compiler
1.26      crook    13382: in scheduling: @code{NEXT} is divided into the loading part (@code{NEXT_P1})
1.21      crook    13383: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
1.1       anton    13384: @example
                   13385: n=sp[0]+sp[1];
                   13386: sp++;
                   13387: NEXT_P1;
                   13388: sp[0]=n;
                   13389: NEXT_P2;
                   13390: @end example
                   13391: This can be scheduled optimally by the compiler.
                   13392: 
                   13393: This division can be turned off with the switch @code{-DCISC_NEXT}. This
                   13394: switch is on by default on machines that do not profit from scheduling
                   13395: (e.g., the 80386), in order to preserve registers.
                   13396: 
                   13397: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
                   13398: @subsection Direct or Indirect Threaded?
                   13399: @cindex threading, direct or indirect?
                   13400: 
                   13401: @cindex -DDIRECT_THREADED
                   13402: Both! After packaging the nasty details in macro definitions we
                   13403: realized that we could switch between direct and indirect threading by
                   13404: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
                   13405: defining a few machine-specific macros for the direct-threading case.
                   13406: On the Forth level we also offer access words that hide the
                   13407: differences between the threading methods (@pxref{Threading Words}).
                   13408: 
                   13409: Indirect threading is implemented completely machine-independently.
                   13410: Direct threading needs routines for creating jumps to the executable
1.21      crook    13411: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
                   13412: machine-dependent, but they do not amount to many source lines. Therefore,
                   13413: even porting direct threading to a new machine requires little effort.
1.1       anton    13414: 
                   13415: @cindex --enable-indirect-threaded, configuration flag
                   13416: @cindex --enable-direct-threaded, configuration flag
                   13417: The default threading method is machine-dependent. You can enforce a
                   13418: specific threading method when building Gforth with the configuration
                   13419: flag @code{--enable-direct-threaded} or
                   13420: @code{--enable-indirect-threaded}. Note that direct threading is not
                   13421: supported on all machines.
                   13422: 
                   13423: @node DOES>,  , Direct or Indirect Threaded?, Threading
                   13424: @subsection DOES>
                   13425: @cindex @code{DOES>} implementation
                   13426: 
1.26      crook    13427: @cindex @code{dodoes} routine
                   13428: @cindex @code{DOES>}-code
1.1       anton    13429: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
                   13430: the chunk of code executed by every word defined by a
                   13431: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
                   13432: the Forth code to be executed, i.e. the code after the
1.26      crook    13433: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
1.1       anton    13434: 
1.21      crook    13435: In fig-Forth the code field points directly to the @code{dodoes} and the
1.45      crook    13436: @code{DOES>}-code address is stored in the cell after the code address (i.e. at
1.29      crook    13437: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
1.1       anton    13438: the Forth-79 and all later standards, because in fig-Forth this address
                   13439: lies in the body (which is illegal in these standards). However, by
                   13440: making the code field larger for all words this solution becomes legal
                   13441: again. We use this approach for the indirect threaded version and for
                   13442: direct threading on some machines. Leaving a cell unused in most words
                   13443: is a bit wasteful, but on the machines we are targeting this is hardly a
                   13444: problem. The other reason for having a code field size of two cells is
                   13445: to avoid having different image files for direct and indirect threaded
                   13446: systems (direct threaded systems require two-cell code fields on many
                   13447: machines).
                   13448: 
1.26      crook    13449: @cindex @code{DOES>}-handler
1.1       anton    13450: The other approach is that the code field points or jumps to the cell
1.26      crook    13451: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
                   13452: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
                   13453: @code{DOES>}-code address by computing the code address, i.e., the address of
1.45      crook    13454: the jump to @code{dodoes}, and add the length of that jump field. A variant of
1.1       anton    13455: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
                   13456: return address (which can be found in the return register on RISCs) is
1.26      crook    13457: the @code{DOES>}-code address. Since the two cells available in the code field
1.1       anton    13458: are used up by the jump to the code address in direct threading on many
                   13459: architectures, we use this approach for direct threading on these
                   13460: architectures. We did not want to add another cell to the code field.
                   13461: 
                   13462: @node Primitives, Performance, Threading, Engine
                   13463: @section Primitives
                   13464: @cindex primitives, implementation
                   13465: @cindex virtual machine instructions, implementation
                   13466: 
                   13467: @menu
                   13468: * Automatic Generation::        
                   13469: * TOS Optimization::            
                   13470: * Produced code::               
                   13471: @end menu
                   13472: 
                   13473: @node Automatic Generation, TOS Optimization, Primitives, Primitives
                   13474: @subsection Automatic Generation
                   13475: @cindex primitives, automatic generation
                   13476: 
                   13477: @cindex @file{prims2x.fs}
                   13478: Since the primitives are implemented in a portable language, there is no
                   13479: longer any need to minimize the number of primitives. On the contrary,
                   13480: having many primitives has an advantage: speed. In order to reduce the
                   13481: number of errors in primitives and to make programming them easier, we
                   13482: provide a tool, the primitive generator (@file{prims2x.fs}), that
                   13483: automatically generates most (and sometimes all) of the C code for a
                   13484: primitive from the stack effect notation.  The source for a primitive
                   13485: has the following form:
                   13486: 
                   13487: @cindex primitive source format
                   13488: @format
1.46      pazsan   13489: @i{Forth-name}  @i{stack-effect}        @i{category}    [@i{pronounc.}]
1.29      crook    13490: [@code{""}@i{glossary entry}@code{""}]
                   13491: @i{C code}
1.1       anton    13492: [@code{:}
1.29      crook    13493: @i{Forth code}]
1.1       anton    13494: @end format
                   13495: 
                   13496: The items in brackets are optional. The category and glossary fields
                   13497: are there for generating the documentation, the Forth code is there
                   13498: for manual implementations on machines without GNU C. E.g., the source
                   13499: for the primitive @code{+} is:
                   13500: @example
                   13501: +    n1 n2 -- n    core    plus
                   13502: n = n1+n2;
                   13503: @end example
                   13504: 
                   13505: This looks like a specification, but in fact @code{n = n1+n2} is C
                   13506: code. Our primitive generation tool extracts a lot of information from
                   13507: the stack effect notations@footnote{We use a one-stack notation, even
                   13508: though we have separate data and floating-point stacks; The separate
                   13509: notation can be generated easily from the unified notation.}: The number
                   13510: of items popped from and pushed on the stack, their type, and by what
                   13511: name they are referred to in the C code. It then generates a C code
                   13512: prelude and postlude for each primitive. The final C code for @code{+}
                   13513: looks like this:
                   13514: 
                   13515: @example
1.46      pazsan   13516: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
1.1       anton    13517: /*  */                          /* documentation */
                   13518: @{
                   13519: DEF_CA                          /* definition of variable ca (indirect threading) */
                   13520: Cell n1;                        /* definitions of variables */
                   13521: Cell n2;
                   13522: Cell n;
                   13523: n1 = (Cell) sp[1];              /* input */
                   13524: n2 = (Cell) TOS;
                   13525: sp += 1;                        /* stack adjustment */
                   13526: NAME("+")                       /* debugging output (with -DDEBUG) */
                   13527: @{
                   13528: n = n1+n2;                      /* C code taken from the source */
                   13529: @}
                   13530: NEXT_P1;                        /* NEXT part 1 */
                   13531: TOS = (Cell)n;                  /* output */
                   13532: NEXT_P2;                        /* NEXT part 2 */
                   13533: @}
                   13534: @end example
                   13535: 
                   13536: This looks long and inefficient, but the GNU C compiler optimizes quite
                   13537: well and produces optimal code for @code{+} on, e.g., the R3000 and the
                   13538: HP RISC machines: Defining the @code{n}s does not produce any code, and
                   13539: using them as intermediate storage also adds no cost.
                   13540: 
1.26      crook    13541: There are also other optimizations that are not illustrated by this
                   13542: example: assignments between simple variables are usually for free (copy
1.1       anton    13543: propagation). If one of the stack items is not used by the primitive
                   13544: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
                   13545: (dead code elimination). On the other hand, there are some things that
                   13546: the compiler does not do, therefore they are performed by
                   13547: @file{prims2x.fs}: The compiler does not optimize code away that stores
                   13548: a stack item to the place where it just came from (e.g., @code{over}).
                   13549: 
                   13550: While programming a primitive is usually easy, there are a few cases
                   13551: where the programmer has to take the actions of the generator into
                   13552: account, most notably @code{?dup}, but also words that do not (always)
1.26      crook    13553: fall through to @code{NEXT}.
1.1       anton    13554: 
                   13555: @node TOS Optimization, Produced code, Automatic Generation, Primitives
                   13556: @subsection TOS Optimization
                   13557: @cindex TOS optimization for primitives
                   13558: @cindex primitives, keeping the TOS in a register
                   13559: 
                   13560: An important optimization for stack machine emulators, e.g., Forth
                   13561: engines, is keeping  one or more of the top stack items in
1.29      crook    13562: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
                   13563: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1       anton    13564: @itemize @bullet
                   13565: @item
1.29      crook    13566: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1       anton    13567: due to fewer loads from and stores to the stack.
1.29      crook    13568: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
                   13569: @i{y<n}, due to additional moves between registers.
1.1       anton    13570: @end itemize
                   13571: 
                   13572: @cindex -DUSE_TOS
                   13573: @cindex -DUSE_NO_TOS
                   13574: In particular, keeping one item in a register is never a disadvantage,
                   13575: if there are enough registers. Keeping two items in registers is a
                   13576: disadvantage for frequent words like @code{?branch}, constants,
                   13577: variables, literals and @code{i}. Therefore our generator only produces
                   13578: code that keeps zero or one items in registers. The generated C code
                   13579: covers both cases; the selection between these alternatives is made at
                   13580: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
                   13581: code for @code{+} is just a simple variable name in the one-item case,
                   13582: otherwise it is a macro that expands into @code{sp[0]}. Note that the
                   13583: GNU C compiler tries to keep simple variables like @code{TOS} in
                   13584: registers, and it usually succeeds, if there are enough registers.
                   13585: 
                   13586: @cindex -DUSE_FTOS
                   13587: @cindex -DUSE_NO_FTOS
                   13588: The primitive generator performs the TOS optimization for the
                   13589: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
                   13590: operations the benefit of this optimization is even larger:
                   13591: floating-point operations take quite long on most processors, but can be
                   13592: performed in parallel with other operations as long as their results are
                   13593: not used. If the FP-TOS is kept in a register, this works. If
                   13594: it is kept on the stack, i.e., in memory, the store into memory has to
                   13595: wait for the result of the floating-point operation, lengthening the
                   13596: execution time of the primitive considerably.
                   13597: 
                   13598: The TOS optimization makes the automatic generation of primitives a
                   13599: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
                   13600: @code{TOS} is not sufficient. There are some special cases to
                   13601: consider:
                   13602: @itemize @bullet
                   13603: @item In the case of @code{dup ( w -- w w )} the generator must not
                   13604: eliminate the store to the original location of the item on the stack,
                   13605: if the TOS optimization is turned on.
                   13606: @item Primitives with stack effects of the form @code{--}
1.29      crook    13607: @i{out1}...@i{outy} must store the TOS to the stack at the start.
                   13608: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1       anton    13609: must load the TOS from the stack at the end. But for the null stack
                   13610: effect @code{--} no stores or loads should be generated.
                   13611: @end itemize
                   13612: 
                   13613: @node Produced code,  , TOS Optimization, Primitives
                   13614: @subsection Produced code
                   13615: @cindex primitives, assembly code listing
                   13616: 
                   13617: @cindex @file{engine.s}
                   13618: To see what assembly code is produced for the primitives on your machine
                   13619: with your compiler and your flag settings, type @code{make engine.s} and
                   13620: look at the resulting file @file{engine.s}.
                   13621: 
                   13622: @node  Performance,  , Primitives, Engine
                   13623: @section Performance
                   13624: @cindex performance of some Forth interpreters
                   13625: @cindex engine performance
                   13626: @cindex benchmarking Forth systems
                   13627: @cindex Gforth performance
                   13628: 
                   13629: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
                   13630: impossible to write a significantly faster engine.
                   13631: 
                   13632: On register-starved machines like the 386 architecture processors
                   13633: improvements are possible, because @code{gcc} does not utilize the
                   13634: registers as well as a human, even with explicit register declarations;
                   13635: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
                   13636: and hand-tuned it for the 486; this system is 1.19 times faster on the
                   13637: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40      anton    13638: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
                   13639: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
                   13640: registers fit in real registers (and we can even afford to use the TOS
                   13641: optimization), resulting in a speedup of 1.14 on the sieve over the
                   13642: earlier results.
1.1       anton    13643: 
                   13644: @cindex Win32Forth performance
                   13645: @cindex NT Forth performance
                   13646: @cindex eforth performance
                   13647: @cindex ThisForth performance
                   13648: @cindex PFE performance
                   13649: @cindex TILE performance
1.40      anton    13650: The potential advantage of assembly language implementations
1.1       anton    13651: is not necessarily realized in complete Forth systems: We compared
1.40      anton    13652: Gforth-0.4.9 (direct threaded, compiled with @code{gcc-2.95.1} and
1.1       anton    13653: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
                   13654: 1994) and Eforth (with and without peephole (aka pinhole) optimization
                   13655: of the threaded code); all these systems were written in assembly
                   13656: language. We also compared Gforth with three systems written in C:
                   13657: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
                   13658: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
1.21      crook    13659: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
                   13660: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
1.1       anton    13661: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
                   13662: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
                   13663: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
                   13664: 486DX2/66 with similar memory performance under Windows NT. Marcel
                   13665: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
                   13666: added the peephole optimizer, ran the benchmarks and reported the
                   13667: results.
1.40      anton    13668: 
1.1       anton    13669: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
                   13670: matrix multiplication come from the Stanford integer benchmarks and have
                   13671: been translated into Forth by Martin Fraeman; we used the versions
                   13672: included in the TILE Forth package, but with bigger data set sizes; and
                   13673: a recursive Fibonacci number computation for benchmarking calling
                   13674: performance. The following table shows the time taken for the benchmarks
                   13675: scaled by the time taken by Gforth (in other words, it shows the speedup
                   13676: factor that Gforth achieved over the other systems).
                   13677: 
                   13678: @example
1.40      anton    13679: relative      Win32-    NT       eforth       This-      
1.1       anton    13680:   time  Gforth Forth Forth eforth  +opt   PFE Forth  TILE
1.40      anton    13681: sieve     1.00  1.58  1.30   1.58  0.97  1.80  3.63  9.79
                   13682: bubble    1.00  1.55  1.67   1.75  1.04  1.78        4.59
                   13683: matmul    1.00  1.67  1.53   1.66  0.84  1.79        4.63
                   13684: fib       1.00  1.75  1.53   1.40  0.99  1.99  3.43  4.93
1.1       anton    13685: @end example
                   13686: 
1.26      crook    13687: You may be quite surprised by the good performance of Gforth when
                   13688: compared with systems written in assembly language. One important reason
                   13689: for the disappointing performance of these other systems is probably
                   13690: that they are not written optimally for the 486 (e.g., they use the
                   13691: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
                   13692: but costly method for relocating the Forth image: like @code{cforth}, it
                   13693: computes the actual addresses at run time, resulting in two address
                   13694: computations per @code{NEXT} (@pxref{Image File Background}).
                   13695: 
1.40      anton    13696: Only Eforth with the peephole optimizer performs comparable to
                   13697: Gforth. The speedups achieved with peephole optimization of threaded
                   13698: code are quite remarkable. Adding a peephole optimizer to Gforth should
                   13699: cause similar speedups.
1.1       anton    13700: 
                   13701: The speedup of Gforth over PFE, ThisForth and TILE can be easily
                   13702: explained with the self-imposed restriction of the latter systems to
                   13703: standard C, which makes efficient threading impossible (however, the
1.4       anton    13704: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1       anton    13705: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
                   13706: Moreover, current C compilers have a hard time optimizing other aspects
                   13707: of the ThisForth and the TILE source.
                   13708: 
1.26      crook    13709: The performance of Gforth on 386 architecture processors varies widely
                   13710: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
                   13711: allocate any of the virtual machine registers into real machine
                   13712: registers by itself and would not work correctly with explicit register
1.40      anton    13713: declarations, giving a 1.5 times slower engine (on a 486DX2/66 running
1.26      crook    13714: the Sieve) than the one measured above.
1.1       anton    13715: 
1.26      crook    13716: Note that there have been several releases of Win32Forth since the
                   13717: release presented here, so the results presented above may have little
1.40      anton    13718: predictive value for the performance of Win32Forth today (results for
                   13719: the current release on an i486DX2/66 are welcome).
1.1       anton    13720: 
                   13721: @cindex @file{Benchres}
                   13722: In @cite{Translating Forth to Efficient C} by M. Anton Ertl and Martin
                   13723: Maierhofer (presented at EuroForth '95), an indirect threaded version of
                   13724: Gforth is compared with Win32Forth, NT Forth, PFE, and ThisForth; that
1.40      anton    13725: version of Gforth is slower on a 486 than the direct threaded version
                   13726: used here. The paper available at
1.47      crook    13727: @*@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz};
1.1       anton    13728: it also contains numbers for some native code systems. You can find a
                   13729: newer version of these measurements at
1.47      crook    13730: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1       anton    13731: find numbers for Gforth on various machines in @file{Benchres}.
                   13732: 
1.26      crook    13733: @c ******************************************************************
1.13      pazsan   13734: @node Binding to System Library, Cross Compiler, Engine, Top
1.14      pazsan   13735: @chapter Binding to System Library
1.13      pazsan   13736: 
                   13737: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14      pazsan   13738: @chapter Cross Compiler
1.47      crook    13739: @cindex @file{cross.fs}
                   13740: @cindex cross-compiler
                   13741: @cindex metacompiler
                   13742: @cindex target compiler
1.13      pazsan   13743: 
1.46      pazsan   13744: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
                   13745: mostly written in Forth, including crucial parts like the outer
                   13746: interpreter and compiler, it needs compiled Forth code to get
                   13747: started. The cross compiler allows to create new images for other
                   13748: architectures, even running under another Forth system.
1.13      pazsan   13749: 
                   13750: @menu
                   13751: * Using the Cross Compiler::
                   13752: * How the Cross Compiler Works::
                   13753: @end menu
                   13754: 
1.21      crook    13755: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14      pazsan   13756: @section Using the Cross Compiler
1.46      pazsan   13757: 
                   13758: The cross compiler uses a language that resembles Forth, but isn't. The
                   13759: main difference is that you can execute Forth code after definition,
                   13760: while you usually can't execute the code compiled by cross, because the
                   13761: code you are compiling is typically for a different computer than the
                   13762: one you are compiling on.
                   13763: 
                   13764: The Makefile is already set up to allow you to create kernels for new
                   13765: architectures with a simple make command. The generic kernels using the
                   13766: GCC compiled virtual machine are created in the normal build process
                   13767: with @code{make}. To create a embedded Gforth executable for e.g. the
                   13768: 8086 processor (running on a DOS machine), type
                   13769: 
                   13770: @example
                   13771: make kernl-8086.fi
                   13772: @end example
                   13773: 
                   13774: This will use the machine description from the @file{arch/8086}
                   13775: directory to create a new kernel. A machine file may look like that:
                   13776: 
                   13777: @example
                   13778: \ Parameter for target systems                         06oct92py
                   13779: 
                   13780:     4 Constant cell             \ cell size in bytes
                   13781:     2 Constant cell<<           \ cell shift to bytes
                   13782:     5 Constant cell>bit         \ cell shift to bits
                   13783:     8 Constant bits/char        \ bits per character
                   13784:     8 Constant bits/byte        \ bits per byte [default: 8]
                   13785:     8 Constant float            \ bytes per float
                   13786:     8 Constant /maxalign        \ maximum alignment in bytes
                   13787: false Constant bigendian        \ byte order
                   13788: ( true=big, false=little )
                   13789: 
                   13790: include machpc.fs               \ feature list
                   13791: @end example
                   13792: 
                   13793: This part is obligatory for the cross compiler itself, the feature list
                   13794: is used by the kernel to conditionally compile some features in and out,
                   13795: depending on whether the target supports these features.
                   13796: 
                   13797: There are some optional features, if you define your own primitives,
                   13798: have an assembler, or need special, nonstandard preparation to make the
                   13799: boot process work. @code{asm-include} include an assembler,
                   13800: @code{prims-include} includes primitives, and @code{>boot} prepares for
                   13801: booting.
                   13802: 
                   13803: @example
                   13804: : asm-include    ." Include assembler" cr
                   13805:   s" arch/8086/asm.fs" included ;
                   13806: 
                   13807: : prims-include  ." Include primitives" cr
                   13808:   s" arch/8086/prim.fs" included ;
                   13809: 
                   13810: : >boot          ." Prepare booting" cr
                   13811:   s" ' boot >body into-forth 1+ !" evaluate ;
                   13812: @end example
                   13813: 
                   13814: These words are used as sort of macro during the cross compilation in
                   13815: the file @file{kernel/main.fs}. Instead of using this macros, it would
                   13816: be possible --- but more complicated --- to write a new kernel project
                   13817: file, too.
                   13818: 
                   13819: @file{kernel/main.fs} expects the machine description file name on the
                   13820: stack; the cross compiler itself (@file{cross.fs}) assumes that either
                   13821: @code{mach-file} leaves a counted string on the stack, or
                   13822: @code{machine-file} leaves an address, count pair of the filename on the
                   13823: stack.
                   13824: 
                   13825: The feature list is typically controlled using @code{SetValue}, generic
                   13826: files that are used by several projects can use @code{DefaultValue}
                   13827: instead. Both functions work like @code{Value}, when the value isn't
                   13828: defined, but @code{SetValue} works like @code{to} if the value is
                   13829: defined, and @code{DefaultValue} doesn't set anything, if the value is
                   13830: defined.
                   13831: 
                   13832: @example
                   13833: \ generic mach file for pc gforth                       03sep97jaw
                   13834: 
                   13835: true DefaultValue NIL  \ relocating
                   13836: 
                   13837: >ENVIRON
                   13838: 
                   13839: true DefaultValue file          \ controls the presence of the
                   13840:                                 \ file access wordset
                   13841: true DefaultValue OS            \ flag to indicate a operating system
                   13842: 
                   13843: true DefaultValue prims         \ true: primitives are c-code
                   13844: 
                   13845: true DefaultValue floating      \ floating point wordset is present
                   13846: 
                   13847: true DefaultValue glocals       \ gforth locals are present
                   13848:                                 \ will be loaded
                   13849: true DefaultValue dcomps        \ double number comparisons
                   13850: 
                   13851: true DefaultValue hash          \ hashing primitives are loaded/present
                   13852: 
                   13853: true DefaultValue xconds        \ used together with glocals,
                   13854:                                 \ special conditionals supporting gforths'
                   13855:                                 \ local variables
                   13856: true DefaultValue header        \ save a header information
                   13857: 
                   13858: true DefaultValue backtrace     \ enables backtrace code
                   13859: 
                   13860: false DefaultValue ec
                   13861: false DefaultValue crlf
                   13862: 
                   13863: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
                   13864: 
                   13865: &16 KB          DefaultValue stack-size
                   13866: &15 KB &512 +   DefaultValue fstack-size
                   13867: &15 KB          DefaultValue rstack-size
                   13868: &14 KB &512 +   DefaultValue lstack-size
                   13869: @end example
1.13      pazsan   13870: 
1.48      anton    13871: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
1.14      pazsan   13872: @section How the Cross Compiler Works
1.13      pazsan   13873: 
                   13874: @node Bugs, Origin, Cross Compiler, Top
1.21      crook    13875: @appendix Bugs
1.1       anton    13876: @cindex bug reporting
                   13877: 
1.21      crook    13878: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1       anton    13879: 
                   13880: If you find a bug, please send a bug report to
1.33      anton    13881: @email{bug-gforth@@gnu.org}. A bug report should include this
1.21      crook    13882: information:
                   13883: 
                   13884: @itemize @bullet
                   13885: @item
                   13886: The Gforth version used (it is announced at the start of an
                   13887: interactive Gforth session).
                   13888: @item
                   13889: The machine and operating system (on Unix
                   13890: systems @code{uname -a} will report this information).
                   13891: @item
                   13892: The installation options (send the file @file{config.status}).
                   13893: @item
                   13894: A complete list of changes (if any) you (or your installer) have made to the
                   13895: Gforth sources.
                   13896: @item
                   13897: A program (or a sequence of keyboard commands) that reproduces the bug.
                   13898: @item
                   13899: A description of what you think constitutes the buggy behaviour.
                   13900: @end itemize
1.1       anton    13901: 
                   13902: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
                   13903: to Report Bugs, gcc.info, GNU C Manual}.
                   13904: 
                   13905: 
1.21      crook    13906: @node Origin, Forth-related information, Bugs, Top
                   13907: @appendix Authors and Ancestors of Gforth
1.1       anton    13908: 
                   13909: @section Authors and Contributors
                   13910: @cindex authors of Gforth
                   13911: @cindex contributors to Gforth
                   13912: 
                   13913: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
                   13914: Ertl. The third major author was Jens Wilke.  Lennart Benschop (who was
                   13915: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
                   13916: with their continuous feedback. Lennart Benshop contributed
                   13917: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
                   13918: support for calling C libraries. Helpful comments also came from Paul
                   13919: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.12      anton    13920: Wavrik, Barrie Stott, Marc de Groot, and Jorge Acerada. Since the
                   13921: release of Gforth-0.2.1 there were also helpful comments from many
                   13922: others; thank you all, sorry for not listing you here (but digging
1.23      crook    13923: through my mailbox to extract your names is on my to-do list). Since the
                   13924: release of Gforth-0.4.0 Neal Crook worked on the manual.
1.1       anton    13925: 
                   13926: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
                   13927: and autoconf, among others), and to the creators of the Internet: Gforth
1.21      crook    13928: was developed across the Internet, and its authors did not meet
1.20      pazsan   13929: physically for the first 4 years of development.
1.1       anton    13930: 
                   13931: @section Pedigree
1.26      crook    13932: @cindex pedigree of Gforth
1.1       anton    13933: 
1.20      pazsan   13934: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
1.1       anton    13935: Dirk Zoller) will cross-fertilize each other. Of course, a significant
                   13936: part of the design of Gforth was prescribed by ANS Forth.
                   13937: 
1.20      pazsan   13938: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1       anton    13939: 32 bit native code version of VolksForth for the Atari ST, written
                   13940: mostly by Dietrich Weineck.
                   13941: 
                   13942: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
                   13943: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
                   13944: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
                   13945: 
                   13946: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
                   13947: Forth-83 standard. !! Pedigree? When?
                   13948: 
                   13949: A team led by Bill Ragsdale implemented fig-Forth on many processors in
                   13950: 1979. Robert Selzer and Bill Ragsdale developed the original
                   13951: implementation of fig-Forth for the 6502 based on microForth.
                   13952: 
                   13953: The principal architect of microForth was Dean Sanderson. microForth was
                   13954: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
                   13955: the 1802, and subsequently implemented on the 8080, the 6800 and the
                   13956: Z80.
                   13957: 
                   13958: All earlier Forth systems were custom-made, usually by Charles Moore,
                   13959: who discovered (as he puts it) Forth during the late 60s. The first full
                   13960: Forth existed in 1971.
                   13961: 
                   13962: A part of the information in this section comes from @cite{The Evolution
                   13963: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
                   13964: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
                   13965: Notices 28(3), 1993.  You can find more historical and genealogical
                   13966: information about Forth there.
                   13967: 
1.21      crook    13968: @node Forth-related information, Word Index, Origin, Top
                   13969: @appendix Other Forth-related information
                   13970: @cindex Forth-related information
                   13971: 
                   13972: @menu
                   13973: * Internet resources::
                   13974: * Books::
                   13975: * The Forth Interest Group::
                   13976: * Conferences::
                   13977: @end menu
                   13978: 
                   13979: 
                   13980: @node Internet resources, Books, Forth-related information, Forth-related information
                   13981: @section Internet resources
1.26      crook    13982: @cindex internet resources
1.21      crook    13983: 
                   13984: @cindex comp.lang.forth
                   13985: @cindex frequently asked questions
1.45      crook    13986: There is an active news group (comp.lang.forth) discussing Forth and
1.21      crook    13987: Forth-related issues. A frequently-asked-questions (FAQ) list
1.45      crook    13988: is posted to the news group regularly, and archived at these sites:
1.21      crook    13989: 
                   13990: @itemize @bullet
                   13991: @item
1.47      crook    13992: @uref{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
1.21      crook    13993: @item
1.47      crook    13994: @uref{ftp://ftp.forth.org/pub/Forth/FAQ/}
1.21      crook    13995: @end itemize
                   13996: 
                   13997: The FAQ list should be considered mandatory reading before posting to
1.45      crook    13998: the news group.
1.21      crook    13999: 
                   14000: Here are some other web sites holding Forth-related material:
                   14001: 
                   14002: @itemize @bullet
                   14003: @item
1.47      crook    14004: @uref{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
1.21      crook    14005: @item
1.47      crook    14006: @uref{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
1.21      crook    14007: @item
1.47      crook    14008: @uref{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
1.21      crook    14009: @item
1.47      crook    14010: @uref{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
1.21      crook    14011: Research page, including links to the Journal of Forth Application and
                   14012: Research (JFAR) and a searchable Forth bibliography.
                   14013: @end itemize
                   14014: 
                   14015: 
                   14016: @node Books, The Forth Interest Group, Internet resources, Forth-related information
                   14017: @section Books
1.26      crook    14018: @cindex books on Forth
1.21      crook    14019: 
                   14020: As the Standard is relatively new, there are not many books out yet. It
                   14021: is not recommended to learn Forth by using Gforth and a book that is not
                   14022: written for ANS Forth, as you will not know your mistakes from the
                   14023: deviations of the book. However, books based on the Forth-83 standard
                   14024: should be ok, because ANS Forth is primarily an extension of Forth-83.
1.44      crook    14025: Refer to the Forth FAQ for details of Forth-related books.
1.21      crook    14026: 
                   14027: @cindex standard document for ANS Forth
                   14028: @cindex ANS Forth document
                   14029: The definite reference if you want to write ANS Forth programs is, of
1.26      crook    14030: course, the ANS Forth document. It is available in printed form from the
1.21      crook    14031: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
                   14032: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
                   14033: $200. You can also get it from Global Engineering Documents (Tel.: USA
                   14034: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
                   14035: 
                   14036: @cite{dpANS6}, the last draft of the standard, which was then submitted
                   14037: to ANSI for publication is available electronically and for free in some
                   14038: MS Word format, and it has been converted to HTML
1.47      crook    14039: (@uref{http://www.taygeta.com/forth/dpans.html}; this HTML version also
1.44      crook    14040: includes the answers to Requests for Interpretation (RFIs). Some
                   14041: pointers to these versions can be found through
1.47      crook    14042: @*@uref{http://www.complang.tuwien.ac.at/projects/forth.html}.
1.44      crook    14043: 
1.21      crook    14044: 
                   14045: @node The Forth Interest Group, Conferences, Books, Forth-related information
                   14046: @section The Forth Interest Group
                   14047: @cindex Forth interest group (FIG)
                   14048: 
                   14049: The Forth Interest Group (FIG) is a world-wide, non-profit,
1.26      crook    14050: member-supported organisation. It publishes a regular magazine,
                   14051: @var{FORTH Dimensions}, and offers other benefits of membership. You can
                   14052: contact the FIG through their office email address:
                   14053: @email{office@@forth.org} or by visiting their web site at
1.47      crook    14054: @uref{http://www.forth.org/}. This web site also includes links to FIG
1.26      crook    14055: chapters in other countries and American cities
1.47      crook    14056: (@uref{http://www.forth.org/chapters.html}).
1.21      crook    14057: 
1.48      anton    14058: @node Conferences,  , The Forth Interest Group, Forth-related information
1.21      crook    14059: @section Conferences
                   14060: @cindex Conferences
                   14061: 
                   14062: There are several regular conferences related to Forth. They are all
1.26      crook    14063: well-publicised in @var{FORTH Dimensions} and on the comp.lang.forth
1.45      crook    14064: news group:
1.21      crook    14065: 
                   14066: @itemize @bullet
                   14067: @item
                   14068: FORML -- the Forth modification laboratory convenes every year near
                   14069: Monterey, California.
                   14070: @item
                   14071: The Rochester Forth Conference -- an annual conference traditionally
                   14072: held in Rochester, New York.
                   14073: @item
                   14074: EuroForth -- this European conference takes place annually.
                   14075: @end itemize
                   14076: 
                   14077: 
1.41      anton    14078: @node Word Index, Name Index, Forth-related information, Top
1.1       anton    14079: @unnumbered Word Index
                   14080: 
1.26      crook    14081: This index is a list of Forth words that have ``glossary'' entries
                   14082: within this manual. Each word is listed with its stack effect and
                   14083: wordset.
1.1       anton    14084: 
                   14085: @printindex fn
                   14086: 
1.41      anton    14087: @node Name Index, Concept Index, Word Index, Top
                   14088: @unnumbered Name Index
                   14089: 
                   14090: This index is a list of Forth words that have ``glossary'' entries
                   14091: within this manual.
                   14092: 
                   14093: @printindex ky
                   14094: 
                   14095: @node Concept Index,  , Name Index, Top
1.1       anton    14096: @unnumbered Concept and Word Index
                   14097: 
1.26      crook    14098: Not all entries listed in this index are present verbatim in the
                   14099: text. This index also duplicates, in abbreviated form, all of the words
                   14100: listed in the Word Index (only the names are listed for the words here).
1.1       anton    14101: 
                   14102: @printindex cp
                   14103: 
                   14104: @contents
                   14105: @bye
                   14106: 

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