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

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
                     25: @comment @setchapternewpage odd
1.29      crook      26: @comment TODO this gets left in by HTML converter
1.12      anton      27: @macro progstyle {}
                     28: Programming style note:
1.3       anton      29: @end macro
1.48    ! anton      30: 
        !            31: @macro assignment {}
        !            32: @table @i
        !            33: @item Assignment:
        !            34: @end macro
        !            35: @macro endassignment {}
        !            36: @end table
        !            37: @end macro
        !            38: 
1.1       anton      39: @comment %**end of header (This is for running Texinfo on a region.)
                     40: 
1.29      crook      41: 
                     42: @comment ----------------------------------------------------------
                     43: @comment macros for beautifying glossary entries
                     44: @comment if these are used, need to strip them out for HTML converter
                     45: @comment else they get repeated verbatim in HTML output.
                     46: @comment .. not working yet.
                     47: 
                     48: @macro GLOSS-START {}
                     49: @iftex
                     50: @ninerm
                     51: @end iftex
                     52: @end macro
                     53: 
                     54: @macro GLOSS-END {}
                     55: @iftex
                     56: @rm
                     57: @end iftex
                     58: @end macro
                     59: 
                     60: @comment ----------------------------------------------------------
                     61: 
                     62: 
1.10      anton      63: @include version.texi
                     64: 
1.1       anton      65: @ifinfo
1.11      anton      66: This file documents Gforth @value{VERSION}
1.1       anton      67: 
1.26      crook      68: Copyright @copyright{} 1995-1999 Free Software Foundation, Inc.
1.1       anton      69: 
                     70:      Permission is granted to make and distribute verbatim copies of
                     71:      this manual provided the copyright notice and this permission notice
                     72:      are preserved on all copies.
                     73:      
                     74: @ignore
                     75:      Permission is granted to process this file through TeX and print the
                     76:      results, provided the printed document carries a copying permission
                     77:      notice identical to this one except for the removal of this paragraph
                     78:      (this paragraph not being relevant to the printed manual).
                     79:      
                     80: @end ignore
                     81:      Permission is granted to copy and distribute modified versions of this
                     82:      manual under the conditions for verbatim copying, provided also that the
                     83:      sections entitled "Distribution" and "General Public License" are
                     84:      included exactly as in the original, and provided that the entire
                     85:      resulting derived work is distributed under the terms of a permission
                     86:      notice identical to this one.
                     87:      
                     88:      Permission is granted to copy and distribute translations of this manual
                     89:      into another language, under the above conditions for modified versions,
                     90:      except that the sections entitled "Distribution" and "General Public
                     91:      License" may be included in a translation approved by the author instead
                     92:      of in the original English.
                     93: @end ifinfo
                     94: 
                     95: @finalout
                     96: @titlepage
                     97: @sp 10
                     98: @center @titlefont{Gforth Manual}
                     99: @sp 2
1.11      anton     100: @center for version @value{VERSION}
1.1       anton     101: @sp 2
1.34      anton     102: @center Neal Crook
1.1       anton     103: @center Anton Ertl
1.6       pazsan    104: @center Bernd Paysan
1.5       anton     105: @center Jens Wilke
1.1       anton     106: @sp 3
1.47      crook     107: @center This manual is permanently under construction and was last updated on 15-Mar-2000
1.1       anton     108: 
                    109: @comment  The following two commands start the copyright page.
                    110: @page
                    111: @vskip 0pt plus 1filll
1.29      crook     112: Copyright @copyright{} 1995--1999 Free Software Foundation, Inc.
1.1       anton     113: 
                    114: @comment !! Published by ... or You can get a copy of this manual ...
                    115: 
                    116:      Permission is granted to make and distribute verbatim copies of
                    117:      this manual provided the copyright notice and this permission notice
                    118:      are preserved on all copies.
                    119:      
                    120:      Permission is granted to copy and distribute modified versions of this
                    121:      manual under the conditions for verbatim copying, provided also that the
                    122:      sections entitled "Distribution" and "General Public License" are
                    123:      included exactly as in the original, and provided that the entire
                    124:      resulting derived work is distributed under the terms of a permission
                    125:      notice identical to this one.
                    126:      
                    127:      Permission is granted to copy and distribute translations of this manual
                    128:      into another language, under the above conditions for modified versions,
                    129:      except that the sections entitled "Distribution" and "General Public
                    130:      License" may be included in a translation approved by the author instead
                    131:      of in the original English.
                    132: @end titlepage
                    133: 
                    134: @node Top, License, (dir), (dir)
                    135: @ifinfo
                    136: Gforth is a free implementation of ANS Forth available on many
1.11      anton     137: personal machines. This manual corresponds to version @value{VERSION}.
1.1       anton     138: @end ifinfo
                    139: 
                    140: @menu
1.21      crook     141: * License::                     The GPL
1.26      crook     142: * Goals::                       About the Gforth Project
1.29      crook     143: * Gforth Environment::          Starting (and exiting) Gforth
1.48    ! anton     144: * Tutorial::                    Hands-on Forth Tutorial
1.21      crook     145: * Introduction::                An introduction to ANS Forth
1.1       anton     146: * Words::                       Forth words available in Gforth
1.24      anton     147: * Error messages::              How to interpret them
1.1       anton     148: * Tools::                       Programming tools
                    149: * ANS conformance::             Implementation-defined options etc.
                    150: * Model::                       The abstract machine of Gforth
                    151: * Integrating Gforth::          Forth as scripting language for applications
                    152: * Emacs and Gforth::            The Gforth Mode
                    153: * Image Files::                 @code{.fi} files contain compiled code
                    154: * Engine::                      The inner interpreter and the primitives
1.24      anton     155: * Binding to System Library::   
1.13      pazsan    156: * Cross Compiler::              The Cross Compiler
1.1       anton     157: * Bugs::                        How to report them
                    158: * Origin::                      Authors and ancestors of Gforth
1.21      crook     159: * Forth-related information::   Books and places to look on the WWW
1.1       anton     160: * Word Index::                  An item for each Forth word
1.41      anton     161: * Name Index::                  Forth words, only names listed
1.1       anton     162: * Concept Index::               A menu covering many topics
1.12      anton     163: 
1.48    ! anton     164: @detailmenu --- The Detailed Node Listing ---
1.12      anton     165: 
1.26      crook     166: Goals of Gforth
                    167: 
                    168: * Gforth Extensions Sinful?::
                    169: 
1.29      crook     170: Gforth Environment
                    171: 
1.32      anton     172: * Invoking Gforth::             Getting in
                    173: * Leaving Gforth::              Getting out
                    174: * Command-line editing::        
1.48    ! anton     175: * Upper and lower case::        
        !           176: * Environment variables::       that affect how Gforth starts up
1.32      anton     177: * Gforth Files::                What gets installed and where
1.48    ! anton     178: * Startup speed::               When 35ms is not fast enough ...
        !           179: 
        !           180: Forth Tutorial
        !           181: 
        !           182: * Starting Gforth Tutorial::    
        !           183: * Syntax Tutorial::             
        !           184: * Crash Course Tutorial::       
        !           185: * Stack Tutorial::              
        !           186: * Arithmetics Tutorial::        
        !           187: * Stack Manipulation Tutorial::  
        !           188: * Using files for Forth code Tutorial::  
        !           189: * Comments Tutorial::           
        !           190: * Colon Definitions Tutorial::  
        !           191: * Decompilation Tutorial::      
        !           192: * Stack-Effect Comments Tutorial::  
        !           193: * Types Tutorial::              
        !           194: * Factoring Tutorial::          
        !           195: * Designing the stack effect Tutorial::  
        !           196: * Local Variables Tutorial::    
        !           197: * Conditional execution Tutorial::  
        !           198: * Flags and Comparisons Tutorial::  
        !           199: * General Loops Tutorial::      
        !           200: * Counted loops Tutorial::      
        !           201: * Recursion Tutorial::          
        !           202: * Leaving definitions or loops Tutorial::  
        !           203: * Return Stack Tutorial::       
        !           204: * Memory Tutorial::             
        !           205: * Characters and Strings Tutorial::  
        !           206: * Alignment Tutorial::          
        !           207: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
        !           208: * Execution Tokens Tutorial::   
        !           209: * Exceptions Tutorial::         
        !           210: * Defining Words Tutorial::     
        !           211: * Arrays and Records Tutorial::  
        !           212: * POSTPONE Tutorial::           
        !           213: * Literal Tutorial::            
        !           214: * Advanced macros Tutorial::    
        !           215: * Compilation Tokens Tutorial::  
        !           216: * Wordlists and Search Order Tutorial::  
1.29      crook     217: 
1.24      anton     218: An Introduction to ANS Forth
                    219: 
                    220: * Introducing the Text Interpreter::
                    221: * Stacks and Postfix notation::
                    222: * Your first definition::
                    223: * How does that work?::
                    224: * Forth is written in Forth::
                    225: * Review - elements of a Forth system::
1.29      crook     226: * Where to go next::
1.24      anton     227: * Exercises::
                    228: 
1.12      anton     229: Forth Words
                    230: 
                    231: * Notation::                    
1.21      crook     232: * Comments::
                    233: * Boolean Flags::
1.12      anton     234: * Arithmetic::                  
                    235: * Stack Manipulation::          
                    236: * Memory::                      
                    237: * Control Structures::          
                    238: * Defining Words::              
1.47      crook     239: * Interpretation and Compilation Semantics::
                    240: * Tokens for Words::            
1.21      crook     241: * The Text Interpreter::
                    242: * Word Lists::                   
                    243: * Environmental Queries::
1.12      anton     244: * Files::                       
                    245: * Blocks::                      
                    246: * Other I/O::                   
                    247: * Programming Tools::           
                    248: * Assembler and Code Words::    
                    249: * Threading Words::             
1.26      crook     250: * Locals::                      
                    251: * Structures::                  
                    252: * Object-oriented Forth::       
1.21      crook     253: * Passing Commands to the OS::
1.47      crook     254: * Keeping track of Time::
1.21      crook     255: * Miscellaneous Words::
1.12      anton     256: 
                    257: Arithmetic
                    258: 
                    259: * Single precision::            
                    260: * Bitwise operations::          
1.21      crook     261: * Double precision::            Double-cell integer arithmetic
                    262: * Numeric comparison::
1.32      anton     263: * Mixed precision::             Operations with single and double-cell integers
1.12      anton     264: * Floating Point::              
                    265: 
                    266: Stack Manipulation
                    267: 
                    268: * Data stack::                  
                    269: * Floating point stack::        
                    270: * Return stack::                
                    271: * Locals stack::                
                    272: * Stack pointer manipulation::  
                    273: 
                    274: Memory
                    275: 
1.32      anton     276: * Memory model::                
                    277: * Dictionary allocation::       
                    278: * Heap Allocation::             
                    279: * Memory Access::               
                    280: * Address arithmetic::          
                    281: * Memory Blocks::               
1.12      anton     282: 
                    283: Control Structures
                    284: 
1.41      anton     285: * Selection::                   IF ... ELSE ... ENDIF
                    286: * Simple Loops::                BEGIN ...
1.32      anton     287: * Counted Loops::               DO
                    288: * Arbitrary control structures::
                    289: * Calls and returns::
1.12      anton     290: * Exception Handling::          
                    291: 
                    292: Defining Words
                    293: 
1.45      crook     294: * CREATE::
1.44      crook     295: * Variables::                   Variables and user variables
                    296: * Constants::
                    297: * Values::                      Initialised variables
1.32      anton     298: * Colon Definitions::
1.44      crook     299: * Anonymous Definitions::       Definitions without names
1.32      anton     300: * User-defined Defining Words::
1.44      crook     301: * Deferred words::              Allow forward references
                    302: * Aliases::
1.32      anton     303: * Supplying names::
1.47      crook     304: 
                    305: Interpretation and Compilation Semantics
                    306: 
1.44      crook     307: * Combined words::
1.12      anton     308: 
1.21      crook     309: The Text Interpreter
                    310: 
1.29      crook     311: * Input Sources::
1.21      crook     312: * Number Conversion::
                    313: * Interpret/Compile states::
                    314: * Literals::
                    315: * Interpreter Directives::
                    316: 
1.26      crook     317: Word Lists
                    318: 
                    319: * Why use word lists?::
                    320: * Word list examples::
                    321: 
                    322: Files
                    323: 
1.48    ! anton     324: * Forth source files::          
        !           325: * General files::               
        !           326: * Search Paths::                
        !           327: 
        !           328: Search Paths
        !           329: 
        !           330: * Forth Search Paths::          
1.26      crook     331: * General Search Paths::        
                    332: 
                    333: Other I/O
                    334: 
1.32      anton     335: * Simple numeric output::       Predefined formats
                    336: * Formatted numeric output::    Formatted (pictured) output
                    337: * String Formats::              How Forth stores strings in memory
                    338: * Displaying characters and strings:: Other stuff
                    339: * Input::                       Input
1.26      crook     340: 
                    341: Programming Tools
                    342: 
                    343: * Debugging::                   Simple and quick.
                    344: * Assertions::                  Making your programs self-checking.
1.46      pazsan    345: * Singlestep Debugger::         Executing your program word by word.
1.26      crook     346: 
                    347: Locals
                    348: 
                    349: * Gforth locals::               
                    350: * ANS Forth locals::            
                    351: 
                    352: Gforth locals
                    353: 
                    354: * Where are locals visible by name?::  
                    355: * How long do locals live?::    
                    356: * Programming Style::           
                    357: * Implementation::              
                    358: 
1.12      anton     359: Structures
                    360: 
                    361: * Why explicit structure support?::  
                    362: * Structure Usage::             
                    363: * Structure Naming Convention::  
                    364: * Structure Implementation::    
                    365: * Structure Glossary::          
                    366: 
                    367: Object-oriented Forth
                    368: 
1.48    ! anton     369: * Why object-oriented programming?::  
        !           370: * Object-Oriented Terminology::  
        !           371: * Objects::                     
        !           372: * OOF::                         
        !           373: * Mini-OOF::                    
1.23      crook     374: * Comparison with other object models::  
1.12      anton     375: 
1.24      anton     376: The @file{objects.fs} model
1.12      anton     377: 
                    378: * Properties of the Objects model::  
                    379: * Basic Objects Usage::         
1.41      anton     380: * The Objects base class::      
1.12      anton     381: * Creating objects::            
                    382: * Object-Oriented Programming Style::  
                    383: * Class Binding::               
                    384: * Method conveniences::         
                    385: * Classes and Scoping::         
1.41      anton     386: * Dividing classes::            
1.12      anton     387: * Object Interfaces::           
                    388: * Objects Implementation::      
                    389: * Objects Glossary::            
                    390: 
1.24      anton     391: The @file{oof.fs} model
1.12      anton     392: 
                    393: * Properties of the OOF model::
                    394: * Basic OOF Usage::
1.23      crook     395: * The OOF base class::
1.12      anton     396: * Class Declaration::
                    397: * Class Implementation::
                    398: 
1.24      anton     399: The @file{mini-oof.fs} model
1.23      crook     400: 
1.48    ! anton     401: * Basic Mini-OOF Usage::        
        !           402: * Mini-OOF Example::            
        !           403: * Mini-OOF Implementation::     
        !           404: * Comparison with other object models::  
1.23      crook     405: 
1.12      anton     406: Tools
                    407: 
                    408: * ANS Report::                  Report the words used, sorted by wordset.
                    409: 
                    410: ANS conformance
                    411: 
                    412: * The Core Words::              
                    413: * The optional Block word set::  
                    414: * The optional Double Number word set::  
                    415: * The optional Exception word set::  
                    416: * The optional Facility word set::  
                    417: * The optional File-Access word set::  
                    418: * The optional Floating-Point word set::  
                    419: * The optional Locals word set::  
                    420: * The optional Memory-Allocation word set::  
                    421: * The optional Programming-Tools word set::  
                    422: * The optional Search-Order word set::  
                    423: 
                    424: The Core Words
                    425: 
                    426: * core-idef::                   Implementation Defined Options                   
                    427: * core-ambcond::                Ambiguous Conditions                
                    428: * core-other::                  Other System Documentation                  
                    429: 
                    430: The optional Block word set
                    431: 
                    432: * block-idef::                  Implementation Defined Options
                    433: * block-ambcond::               Ambiguous Conditions               
                    434: * block-other::                 Other System Documentation                 
                    435: 
                    436: The optional Double Number word set
                    437: 
                    438: * double-ambcond::              Ambiguous Conditions              
                    439: 
                    440: The optional Exception word set
                    441: 
                    442: * exception-idef::              Implementation Defined Options              
                    443: 
                    444: The optional Facility word set
                    445: 
                    446: * facility-idef::               Implementation Defined Options               
                    447: * facility-ambcond::            Ambiguous Conditions            
                    448: 
                    449: The optional File-Access word set
                    450: 
                    451: * file-idef::                   Implementation Defined Options
                    452: * file-ambcond::                Ambiguous Conditions                
                    453: 
                    454: The optional Floating-Point word set
                    455: 
                    456: * floating-idef::               Implementation Defined Options
                    457: * floating-ambcond::            Ambiguous Conditions            
                    458: 
                    459: The optional Locals word set
                    460: 
                    461: * locals-idef::                 Implementation Defined Options                 
                    462: * locals-ambcond::              Ambiguous Conditions              
                    463: 
                    464: The optional Memory-Allocation word set
                    465: 
                    466: * memory-idef::                 Implementation Defined Options                 
                    467: 
                    468: The optional Programming-Tools word set
                    469: 
                    470: * programming-idef::            Implementation Defined Options            
                    471: * programming-ambcond::         Ambiguous Conditions         
                    472: 
                    473: The optional Search-Order word set
                    474: 
                    475: * search-idef::                 Implementation Defined Options                 
                    476: * search-ambcond::              Ambiguous Conditions              
                    477: 
                    478: Image Files
                    479: 
1.24      anton     480: * Image Licensing Issues::      Distribution terms for images.
                    481: * Image File Background::       Why have image files?
1.32      anton     482: * Non-Relocatable Image Files::   don't always work.
1.24      anton     483: * Data-Relocatable Image Files::  are better.
1.32      anton     484: * Fully Relocatable Image Files:: better yet.
1.24      anton     485: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.32      anton     486: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.24      anton     487: * Modifying the Startup Sequence::  and turnkey applications.
1.12      anton     488: 
                    489: Fully Relocatable Image Files
                    490: 
1.27      crook     491: * gforthmi::                    The normal way
1.12      anton     492: * cross.fs::                    The hard way
                    493: 
                    494: Engine
                    495: 
                    496: * Portability::                 
                    497: * Threading::                   
                    498: * Primitives::                  
                    499: * Performance::                 
                    500: 
                    501: Threading
                    502: 
                    503: * Scheduling::                  
                    504: * Direct or Indirect Threaded?::  
                    505: * DOES>::                       
                    506: 
                    507: Primitives
                    508: 
                    509: * Automatic Generation::        
                    510: * TOS Optimization::            
                    511: * Produced code::               
1.13      pazsan    512: 
                    513: Cross Compiler
                    514: 
                    515: * Using the Cross Compiler::
                    516: * How the Cross Compiler Works::
                    517: 
1.24      anton     518: Other Forth-related information
1.21      crook     519: 
                    520: * Internet resources::
                    521: * Books::
                    522: * The Forth Interest Group::
                    523: * Conferences::
                    524: 
1.24      anton     525: @end detailmenu
1.1       anton     526: @end menu
                    527: 
1.26      crook     528: @node License, Goals, Top, Top
1.1       anton     529: @unnumbered GNU GENERAL PUBLIC LICENSE
                    530: @center Version 2, June 1991
                    531: 
                    532: @display
                    533: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
                    534: 675 Mass Ave, Cambridge, MA 02139, USA
                    535: 
                    536: Everyone is permitted to copy and distribute verbatim copies
                    537: of this license document, but changing it is not allowed.
                    538: @end display
                    539: 
                    540: @unnumberedsec Preamble
                    541: 
                    542:   The licenses for most software are designed to take away your
                    543: freedom to share and change it.  By contrast, the GNU General Public
                    544: License is intended to guarantee your freedom to share and change free
                    545: software---to make sure the software is free for all its users.  This
                    546: General Public License applies to most of the Free Software
                    547: Foundation's software and to any other program whose authors commit to
                    548: using it.  (Some other Free Software Foundation software is covered by
                    549: the GNU Library General Public License instead.)  You can apply it to
                    550: your programs, too.
                    551: 
                    552:   When we speak of free software, we are referring to freedom, not
                    553: price.  Our General Public Licenses are designed to make sure that you
                    554: have the freedom to distribute copies of free software (and charge for
                    555: this service if you wish), that you receive source code or can get it
                    556: if you want it, that you can change the software or use pieces of it
                    557: in new free programs; and that you know you can do these things.
                    558: 
                    559:   To protect your rights, we need to make restrictions that forbid
                    560: anyone to deny you these rights or to ask you to surrender the rights.
                    561: These restrictions translate to certain responsibilities for you if you
                    562: distribute copies of the software, or if you modify it.
                    563: 
                    564:   For example, if you distribute copies of such a program, whether
                    565: gratis or for a fee, you must give the recipients all the rights that
                    566: you have.  You must make sure that they, too, receive or can get the
                    567: source code.  And you must show them these terms so they know their
                    568: rights.
                    569: 
                    570:   We protect your rights with two steps: (1) copyright the software, and
                    571: (2) offer you this license which gives you legal permission to copy,
                    572: distribute and/or modify the software.
                    573: 
                    574:   Also, for each author's protection and ours, we want to make certain
                    575: that everyone understands that there is no warranty for this free
                    576: software.  If the software is modified by someone else and passed on, we
                    577: want its recipients to know that what they have is not the original, so
                    578: that any problems introduced by others will not reflect on the original
                    579: authors' reputations.
                    580: 
                    581:   Finally, any free program is threatened constantly by software
                    582: patents.  We wish to avoid the danger that redistributors of a free
                    583: program will individually obtain patent licenses, in effect making the
                    584: program proprietary.  To prevent this, we have made it clear that any
                    585: patent must be licensed for everyone's free use or not licensed at all.
                    586: 
                    587:   The precise terms and conditions for copying, distribution and
                    588: modification follow.
                    589: 
                    590: @iftex
                    591: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
                    592: @end iftex
                    593: @ifinfo
                    594: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
                    595: @end ifinfo
                    596: 
                    597: @enumerate 0
                    598: @item
                    599: This License applies to any program or other work which contains
                    600: a notice placed by the copyright holder saying it may be distributed
                    601: under the terms of this General Public License.  The ``Program'', below,
                    602: refers to any such program or work, and a ``work based on the Program''
                    603: means either the Program or any derivative work under copyright law:
                    604: that is to say, a work containing the Program or a portion of it,
                    605: either verbatim or with modifications and/or translated into another
                    606: language.  (Hereinafter, translation is included without limitation in
                    607: the term ``modification''.)  Each licensee is addressed as ``you''.
                    608: 
                    609: Activities other than copying, distribution and modification are not
                    610: covered by this License; they are outside its scope.  The act of
                    611: running the Program is not restricted, and the output from the Program
                    612: is covered only if its contents constitute a work based on the
                    613: Program (independent of having been made by running the Program).
                    614: Whether that is true depends on what the Program does.
                    615: 
                    616: @item
                    617: You may copy and distribute verbatim copies of the Program's
                    618: source code as you receive it, in any medium, provided that you
                    619: conspicuously and appropriately publish on each copy an appropriate
                    620: copyright notice and disclaimer of warranty; keep intact all the
                    621: notices that refer to this License and to the absence of any warranty;
                    622: and give any other recipients of the Program a copy of this License
                    623: along with the Program.
                    624: 
                    625: You may charge a fee for the physical act of transferring a copy, and
                    626: you may at your option offer warranty protection in exchange for a fee.
                    627: 
                    628: @item
                    629: You may modify your copy or copies of the Program or any portion
                    630: of it, thus forming a work based on the Program, and copy and
                    631: distribute such modifications or work under the terms of Section 1
                    632: above, provided that you also meet all of these conditions:
                    633: 
                    634: @enumerate a
                    635: @item
                    636: You must cause the modified files to carry prominent notices
                    637: stating that you changed the files and the date of any change.
                    638: 
                    639: @item
                    640: You must cause any work that you distribute or publish, that in
                    641: whole or in part contains or is derived from the Program or any
                    642: part thereof, to be licensed as a whole at no charge to all third
                    643: parties under the terms of this License.
                    644: 
                    645: @item
                    646: If the modified program normally reads commands interactively
                    647: when run, you must cause it, when started running for such
                    648: interactive use in the most ordinary way, to print or display an
                    649: announcement including an appropriate copyright notice and a
                    650: notice that there is no warranty (or else, saying that you provide
                    651: a warranty) and that users may redistribute the program under
                    652: these conditions, and telling the user how to view a copy of this
                    653: License.  (Exception: if the Program itself is interactive but
                    654: does not normally print such an announcement, your work based on
                    655: the Program is not required to print an announcement.)
                    656: @end enumerate
                    657: 
                    658: These requirements apply to the modified work as a whole.  If
                    659: identifiable sections of that work are not derived from the Program,
                    660: and can be reasonably considered independent and separate works in
                    661: themselves, then this License, and its terms, do not apply to those
                    662: sections when you distribute them as separate works.  But when you
                    663: distribute the same sections as part of a whole which is a work based
                    664: on the Program, the distribution of the whole must be on the terms of
                    665: this License, whose permissions for other licensees extend to the
                    666: entire whole, and thus to each and every part regardless of who wrote it.
                    667: 
                    668: Thus, it is not the intent of this section to claim rights or contest
                    669: your rights to work written entirely by you; rather, the intent is to
                    670: exercise the right to control the distribution of derivative or
                    671: collective works based on the Program.
                    672: 
                    673: In addition, mere aggregation of another work not based on the Program
                    674: with the Program (or with a work based on the Program) on a volume of
                    675: a storage or distribution medium does not bring the other work under
                    676: the scope of this License.
                    677: 
                    678: @item
                    679: You may copy and distribute the Program (or a work based on it,
                    680: under Section 2) in object code or executable form under the terms of
                    681: Sections 1 and 2 above provided that you also do one of the following:
                    682: 
                    683: @enumerate a
                    684: @item
                    685: Accompany it with the complete corresponding machine-readable
                    686: source code, which must be distributed under the terms of Sections
                    687: 1 and 2 above on a medium customarily used for software interchange; or,
                    688: 
                    689: @item
                    690: Accompany it with a written offer, valid for at least three
                    691: years, to give any third party, for a charge no more than your
                    692: cost of physically performing source distribution, a complete
                    693: machine-readable copy of the corresponding source code, to be
                    694: distributed under the terms of Sections 1 and 2 above on a medium
                    695: customarily used for software interchange; or,
                    696: 
                    697: @item
                    698: Accompany it with the information you received as to the offer
                    699: to distribute corresponding source code.  (This alternative is
                    700: allowed only for noncommercial distribution and only if you
                    701: received the program in object code or executable form with such
                    702: an offer, in accord with Subsection b above.)
                    703: @end enumerate
                    704: 
                    705: The source code for a work means the preferred form of the work for
                    706: making modifications to it.  For an executable work, complete source
                    707: code means all the source code for all modules it contains, plus any
                    708: associated interface definition files, plus the scripts used to
                    709: control compilation and installation of the executable.  However, as a
                    710: special exception, the source code distributed need not include
                    711: anything that is normally distributed (in either source or binary
                    712: form) with the major components (compiler, kernel, and so on) of the
                    713: operating system on which the executable runs, unless that component
                    714: itself accompanies the executable.
                    715: 
                    716: If distribution of executable or object code is made by offering
                    717: access to copy from a designated place, then offering equivalent
                    718: access to copy the source code from the same place counts as
                    719: distribution of the source code, even though third parties are not
                    720: compelled to copy the source along with the object code.
                    721: 
                    722: @item
                    723: You may not copy, modify, sublicense, or distribute the Program
                    724: except as expressly provided under this License.  Any attempt
                    725: otherwise to copy, modify, sublicense or distribute the Program is
                    726: void, and will automatically terminate your rights under this License.
                    727: However, parties who have received copies, or rights, from you under
                    728: this License will not have their licenses terminated so long as such
                    729: parties remain in full compliance.
                    730: 
                    731: @item
                    732: You are not required to accept this License, since you have not
                    733: signed it.  However, nothing else grants you permission to modify or
                    734: distribute the Program or its derivative works.  These actions are
                    735: prohibited by law if you do not accept this License.  Therefore, by
                    736: modifying or distributing the Program (or any work based on the
                    737: Program), you indicate your acceptance of this License to do so, and
                    738: all its terms and conditions for copying, distributing or modifying
                    739: the Program or works based on it.
                    740: 
                    741: @item
                    742: Each time you redistribute the Program (or any work based on the
                    743: Program), the recipient automatically receives a license from the
                    744: original licensor to copy, distribute or modify the Program subject to
                    745: these terms and conditions.  You may not impose any further
                    746: restrictions on the recipients' exercise of the rights granted herein.
                    747: You are not responsible for enforcing compliance by third parties to
                    748: this License.
                    749: 
                    750: @item
                    751: If, as a consequence of a court judgment or allegation of patent
                    752: infringement or for any other reason (not limited to patent issues),
                    753: conditions are imposed on you (whether by court order, agreement or
                    754: otherwise) that contradict the conditions of this License, they do not
                    755: excuse you from the conditions of this License.  If you cannot
                    756: distribute so as to satisfy simultaneously your obligations under this
                    757: License and any other pertinent obligations, then as a consequence you
                    758: may not distribute the Program at all.  For example, if a patent
                    759: license would not permit royalty-free redistribution of the Program by
                    760: all those who receive copies directly or indirectly through you, then
                    761: the only way you could satisfy both it and this License would be to
                    762: refrain entirely from distribution of the Program.
                    763: 
                    764: If any portion of this section is held invalid or unenforceable under
                    765: any particular circumstance, the balance of the section is intended to
                    766: apply and the section as a whole is intended to apply in other
                    767: circumstances.
                    768: 
                    769: It is not the purpose of this section to induce you to infringe any
                    770: patents or other property right claims or to contest validity of any
                    771: such claims; this section has the sole purpose of protecting the
                    772: integrity of the free software distribution system, which is
                    773: implemented by public license practices.  Many people have made
                    774: generous contributions to the wide range of software distributed
                    775: through that system in reliance on consistent application of that
                    776: system; it is up to the author/donor to decide if he or she is willing
                    777: to distribute software through any other system and a licensee cannot
                    778: impose that choice.
                    779: 
                    780: This section is intended to make thoroughly clear what is believed to
                    781: be a consequence of the rest of this License.
                    782: 
                    783: @item
                    784: If the distribution and/or use of the Program is restricted in
                    785: certain countries either by patents or by copyrighted interfaces, the
                    786: original copyright holder who places the Program under this License
                    787: may add an explicit geographical distribution limitation excluding
                    788: those countries, so that distribution is permitted only in or among
                    789: countries not thus excluded.  In such case, this License incorporates
                    790: the limitation as if written in the body of this License.
                    791: 
                    792: @item
                    793: The Free Software Foundation may publish revised and/or new versions
                    794: of the General Public License from time to time.  Such new versions will
                    795: be similar in spirit to the present version, but may differ in detail to
                    796: address new problems or concerns.
                    797: 
                    798: Each version is given a distinguishing version number.  If the Program
                    799: specifies a version number of this License which applies to it and ``any
                    800: later version'', you have the option of following the terms and conditions
                    801: either of that version or of any later version published by the Free
                    802: Software Foundation.  If the Program does not specify a version number of
                    803: this License, you may choose any version ever published by the Free Software
                    804: Foundation.
                    805: 
                    806: @item
                    807: If you wish to incorporate parts of the Program into other free
                    808: programs whose distribution conditions are different, write to the author
                    809: to ask for permission.  For software which is copyrighted by the Free
                    810: Software Foundation, write to the Free Software Foundation; we sometimes
                    811: make exceptions for this.  Our decision will be guided by the two goals
                    812: of preserving the free status of all derivatives of our free software and
                    813: of promoting the sharing and reuse of software generally.
                    814: 
                    815: @iftex
                    816: @heading NO WARRANTY
                    817: @end iftex
                    818: @ifinfo
                    819: @center NO WARRANTY
                    820: @end ifinfo
                    821: 
                    822: @item
                    823: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
                    824: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
                    825: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
                    826: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
                    827: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
                    828: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
                    829: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
                    830: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
                    831: REPAIR OR CORRECTION.
                    832: 
                    833: @item
                    834: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
                    835: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
                    836: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
                    837: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
                    838: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
                    839: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
                    840: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
                    841: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
                    842: POSSIBILITY OF SUCH DAMAGES.
                    843: @end enumerate
                    844: 
                    845: @iftex
                    846: @heading END OF TERMS AND CONDITIONS
                    847: @end iftex
                    848: @ifinfo
                    849: @center END OF TERMS AND CONDITIONS
                    850: @end ifinfo
                    851: 
                    852: @page
                    853: @unnumberedsec How to Apply These Terms to Your New Programs
                    854: 
                    855:   If you develop a new program, and you want it to be of the greatest
                    856: possible use to the public, the best way to achieve this is to make it
                    857: free software which everyone can redistribute and change under these terms.
                    858: 
                    859:   To do so, attach the following notices to the program.  It is safest
                    860: to attach them to the start of each source file to most effectively
                    861: convey the exclusion of warranty; and each file should have at least
                    862: the ``copyright'' line and a pointer to where the full notice is found.
                    863: 
                    864: @smallexample
                    865: @var{one line to give the program's name and a brief idea of what it does.}
                    866: Copyright (C) 19@var{yy}  @var{name of author}
                    867: 
                    868: This program is free software; you can redistribute it and/or modify 
                    869: it under the terms of the GNU General Public License as published by 
                    870: the Free Software Foundation; either version 2 of the License, or 
                    871: (at your option) any later version.
                    872: 
                    873: This program is distributed in the hope that it will be useful,
                    874: but WITHOUT ANY WARRANTY; without even the implied warranty of
                    875: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                    876: GNU General Public License for more details.
                    877: 
                    878: You should have received a copy of the GNU General Public License
                    879: along with this program; if not, write to the Free Software
                    880: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
                    881: @end smallexample
                    882: 
                    883: Also add information on how to contact you by electronic and paper mail.
                    884: 
                    885: If the program is interactive, make it output a short notice like this
                    886: when it starts in an interactive mode:
                    887: 
                    888: @smallexample
                    889: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
                    890: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
                    891: type `show w'.  
                    892: This is free software, and you are welcome to redistribute it 
                    893: under certain conditions; type `show c' for details.
                    894: @end smallexample
                    895: 
                    896: The hypothetical commands @samp{show w} and @samp{show c} should show
                    897: the appropriate parts of the General Public License.  Of course, the
                    898: commands you use may be called something other than @samp{show w} and
                    899: @samp{show c}; they could even be mouse-clicks or menu items---whatever
                    900: suits your program.
                    901: 
                    902: You should also get your employer (if you work as a programmer) or your
                    903: school, if any, to sign a ``copyright disclaimer'' for the program, if
                    904: necessary.  Here is a sample; alter the names:
                    905: 
                    906: @smallexample
                    907: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
                    908: `Gnomovision' (which makes passes at compilers) written by James Hacker.
                    909: 
                    910: @var{signature of Ty Coon}, 1 April 1989
                    911: Ty Coon, President of Vice
                    912: @end smallexample
                    913: 
                    914: This General Public License does not permit incorporating your program into
                    915: proprietary programs.  If your program is a subroutine library, you may
                    916: consider it more useful to permit linking proprietary applications with the
                    917: library.  If this is what you want to do, use the GNU Library General
                    918: Public License instead of this License.
                    919: 
                    920: @iftex
                    921: @unnumbered Preface
                    922: @cindex Preface
1.21      crook     923: This manual documents Gforth. Some introductory material is provided for
                    924: readers who are unfamiliar with Forth or who are migrating to Gforth
                    925: from other Forth compilers. However, this manual is primarily a
                    926: reference manual.
1.1       anton     927: @end iftex
                    928: 
1.28      crook     929: @comment TODO much more blurb here.
1.26      crook     930: 
                    931: @c ******************************************************************
1.29      crook     932: @node Goals, Gforth Environment, License, Top
1.26      crook     933: @comment node-name,     next,           previous, up
                    934: @chapter Goals of Gforth
                    935: @cindex goals of the Gforth project
                    936: The goal of the Gforth Project is to develop a standard model for
                    937: ANS Forth. This can be split into several subgoals:
                    938: 
                    939: @itemize @bullet
                    940: @item
                    941: Gforth should conform to the ANS Forth Standard.
                    942: @item
                    943: It should be a model, i.e. it should define all the
                    944: implementation-dependent things.
                    945: @item
                    946: It should become standard, i.e. widely accepted and used. This goal
                    947: is the most difficult one.
                    948: @end itemize
                    949: 
                    950: To achieve these goals Gforth should be
                    951: @itemize @bullet
                    952: @item
                    953: Similar to previous models (fig-Forth, F83)
                    954: @item
                    955: Powerful. It should provide for all the things that are considered
                    956: necessary today and even some that are not yet considered necessary.
                    957: @item
                    958: Efficient. It should not get the reputation of being exceptionally
                    959: slow.
                    960: @item
                    961: Free.
                    962: @item
                    963: Available on many machines/easy to port.
                    964: @end itemize
                    965: 
                    966: Have we achieved these goals? Gforth conforms to the ANS Forth
                    967: standard. It may be considered a model, but we have not yet documented
                    968: which parts of the model are stable and which parts we are likely to
                    969: change. It certainly has not yet become a de facto standard, but it
                    970: appears to be quite popular. It has some similarities to and some
                    971: differences from previous models. It has some powerful features, but not
                    972: yet everything that we envisioned. We certainly have achieved our
                    973: execution speed goals (@pxref{Performance}).  It is free and available
                    974: on many machines.
                    975: 
                    976: @menu
                    977: * Gforth Extensions Sinful?::
                    978: @end menu
                    979: 
1.48    ! anton     980: @node Gforth Extensions Sinful?,  , Goals, Goals
1.26      crook     981: @comment node-name,     next,           previous, up
                    982: @section Is it a Sin to use Gforth Extensions?
                    983: @cindex Gforth extensions
                    984: 
                    985: If you've been paying attention, you will have realised that there is an
                    986: ANS (American National Standard) for Forth. As you read through the rest
1.29      crook     987: of this manual, you will see documentation for @i{Standard} words, and
                    988: documentation for some appealing Gforth @i{extensions}. You might ask
                    989: yourself the question: @i{``Given that there is a standard, would I be
1.45      crook     990: committing a sin if I use (non-Standard) Gforth extensions?''}
1.26      crook     991: 
                    992: The answer to that question is somewhat pragmatic and somewhat
                    993: philosophical. Consider these points:
                    994: 
                    995: @itemize @bullet
                    996: @item
                    997: A number of the Gforth extensions can be implemented in ANS Forth using
                    998: files provided in the @file{compat/} directory. These are mentioned in
                    999: the text in passing.
                   1000: @item
                   1001: Forth has a rich historical precedent for programmers taking advantage
                   1002: of implementation-dependent features of their tools (for example,
                   1003: relying on a knowledge of the dictionary structure). Sometimes these
                   1004: techniques are necessary to extract every last bit of performance from
                   1005: the hardware, sometimes they are just a programming shorthand.
                   1006: @item
                   1007: The best way to break the rules is to know what the rules are. To learn
                   1008: the rules, there is no substitute for studying the text of the Standard
                   1009: itself. In particular, Appendix A of the Standard (@var{Rationale})
                   1010: provides a valuable insight into the thought processes of the technical
                   1011: committee.
                   1012: @item
                   1013: The best reason to break a rule is because you have to; because it's
                   1014: more productive to do that, because it makes your code run fast enough
                   1015: or because you can see no Standard way to achieve what you want to
                   1016: achieve.
                   1017: @end itemize
                   1018: 
                   1019: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
                   1020: analyse your program and determine what non-Standard definitions it
                   1021: relies upon.
                   1022: 
1.29      crook    1023: 
1.26      crook    1024: @c ******************************************************************
1.48    ! anton    1025: @node Gforth Environment, Tutorial, Goals, Top
1.29      crook    1026: @chapter Gforth Environment
                   1027: @cindex Gforth environment
1.21      crook    1028: 
1.45      crook    1029: Note: ultimately, the Gforth man page will be auto-generated from the
1.29      crook    1030: material in this chapter.
1.21      crook    1031: 
                   1032: @menu
1.29      crook    1033: * Invoking Gforth::             Getting in
                   1034: * Leaving Gforth::              Getting out
                   1035: * Command-line editing::        
1.48    ! anton    1036: * Upper and lower case::        
        !          1037: * Environment variables::       that affect how Gforth starts up
1.29      crook    1038: * Gforth Files::                What gets installed and where
1.48    ! anton    1039: * Startup speed::               When 35ms is not fast enough ...
1.21      crook    1040: @end menu
                   1041: 
1.30      anton    1042: @xref{Image Files} for related information about the creation of images.
1.29      crook    1043: 
1.21      crook    1044: @comment ----------------------------------------------
1.48    ! anton    1045: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29      crook    1046: @section Invoking Gforth
                   1047: @cindex invoking Gforth
                   1048: @cindex running Gforth
                   1049: @cindex command-line options
                   1050: @cindex options on the command line
                   1051: @cindex flags on the command line
1.21      crook    1052: 
1.30      anton    1053: Gforth is made up of two parts; an executable ``engine'' (named
                   1054: @file{gforth} or @file{gforth-fast}) and an image file. To start it, you
                   1055: will usually just say @code{gforth} -- this automatically loads the
                   1056: default image file @file{gforth.fi}. In many other cases the default
                   1057: Gforth image will be invoked like this:
1.21      crook    1058: @example
1.30      anton    1059: gforth [file | -e forth-code] ...
1.21      crook    1060: @end example
1.29      crook    1061: @noindent
                   1062: This interprets the contents of the files and the Forth code in the order they
                   1063: are given.
1.21      crook    1064: 
1.30      anton    1065: In addition to the @file{gforth} engine, there is also an engine called
                   1066: @file{gforth-fast}, which is faster, but gives less informative error
                   1067: messages (@pxref{Error messages}).
                   1068: 
1.29      crook    1069: In general, the command line looks like this:
1.21      crook    1070: 
                   1071: @example
1.30      anton    1072: gforth[-fast] [engine options] [image options]
1.21      crook    1073: @end example
                   1074: 
1.30      anton    1075: The engine options must come before the rest of the command
1.29      crook    1076: line. They are:
1.26      crook    1077: 
1.29      crook    1078: @table @code
                   1079: @cindex -i, command-line option
                   1080: @cindex --image-file, command-line option
                   1081: @item --image-file @i{file}
                   1082: @itemx -i @i{file}
                   1083: Loads the Forth image @i{file} instead of the default
                   1084: @file{gforth.fi} (@pxref{Image Files}).
1.21      crook    1085: 
1.39      anton    1086: @cindex --appl-image, command-line option
                   1087: @item --appl-image @i{file}
                   1088: Loads the image @i{file} and leaves all further command-line arguments
                   1089: to the image (instead of processing them as options).  This is useful
                   1090: for building executable application images on Unix, built with
                   1091: @code{gforthmi --application ...}.
                   1092: 
1.29      crook    1093: @cindex --path, command-line option
                   1094: @cindex -p, command-line option
                   1095: @item --path @i{path}
                   1096: @itemx -p @i{path}
                   1097: Uses @i{path} for searching the image file and Forth source code files
                   1098: instead of the default in the environment variable @code{GFORTHPATH} or
                   1099: the path specified at installation time (e.g.,
                   1100: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
                   1101: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21      crook    1102: 
1.29      crook    1103: @cindex --dictionary-size, command-line option
                   1104: @cindex -m, command-line option
                   1105: @cindex @i{size} parameters for command-line options
                   1106: @cindex size of the dictionary and the stacks
                   1107: @item --dictionary-size @i{size}
                   1108: @itemx -m @i{size}
                   1109: Allocate @i{size} space for the Forth dictionary space instead of
                   1110: using the default specified in the image (typically 256K). The
                   1111: @i{size} specification for this and subsequent options consists of
                   1112: an integer and a unit (e.g.,
                   1113: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
                   1114: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
                   1115: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
                   1116: @code{e} is used.
1.21      crook    1117: 
1.29      crook    1118: @cindex --data-stack-size, command-line option
                   1119: @cindex -d, command-line option
                   1120: @item --data-stack-size @i{size}
                   1121: @itemx -d @i{size}
                   1122: Allocate @i{size} space for the data stack instead of using the
                   1123: default specified in the image (typically 16K).
1.21      crook    1124: 
1.29      crook    1125: @cindex --return-stack-size, command-line option
                   1126: @cindex -r, command-line option
                   1127: @item --return-stack-size @i{size}
                   1128: @itemx -r @i{size}
                   1129: Allocate @i{size} space for the return stack instead of using the
                   1130: default specified in the image (typically 15K).
1.21      crook    1131: 
1.29      crook    1132: @cindex --fp-stack-size, command-line option
                   1133: @cindex -f, command-line option
                   1134: @item --fp-stack-size @i{size}
                   1135: @itemx -f @i{size}
                   1136: Allocate @i{size} space for the floating point stack instead of
                   1137: using the default specified in the image (typically 15.5K). In this case
                   1138: the unit specifier @code{e} refers to floating point numbers.
1.21      crook    1139: 
1.48    ! anton    1140: @cindex --locals-stack-size, command-line option
        !          1141: @cindex -l, command-line option
        !          1142: @item --locals-stack-size @i{size}
        !          1143: @itemx -l @i{size}
        !          1144: Allocate @i{size} space for the locals stack instead of using the
        !          1145: default specified in the image (typically 14.5K).
        !          1146: 
        !          1147: @cindex -h, command-line option
        !          1148: @cindex --help, command-line option
        !          1149: @item --help
        !          1150: @itemx -h
        !          1151: Print a message about the command-line options
        !          1152: 
        !          1153: @cindex -v, command-line option
        !          1154: @cindex --version, command-line option
        !          1155: @item --version
        !          1156: @itemx -v
        !          1157: Print version and exit
        !          1158: 
        !          1159: @cindex --debug, command-line option
        !          1160: @item --debug
        !          1161: Print some information useful for debugging on startup.
        !          1162: 
        !          1163: @cindex --offset-image, command-line option
        !          1164: @item --offset-image
        !          1165: Start the dictionary at a slightly different position than would be used
        !          1166: otherwise (useful for creating data-relocatable images,
        !          1167: @pxref{Data-Relocatable Image Files}).
        !          1168: 
        !          1169: @cindex --no-offset-im, command-line option
        !          1170: @item --no-offset-im
        !          1171: Start the dictionary at the normal position.
        !          1172: 
        !          1173: @cindex --clear-dictionary, command-line option
        !          1174: @item --clear-dictionary
        !          1175: Initialize all bytes in the dictionary to 0 before loading the image
        !          1176: (@pxref{Data-Relocatable Image Files}).
        !          1177: 
        !          1178: @cindex --die-on-signal, command-line-option
        !          1179: @item --die-on-signal
        !          1180: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
        !          1181: or the segmentation violation SIGSEGV) by translating it into a Forth
        !          1182: @code{THROW}. With this option, Gforth exits if it receives such a
        !          1183: signal. This option is useful when the engine and/or the image might be
        !          1184: severely broken (such that it causes another signal before recovering
        !          1185: from the first); this option avoids endless loops in such cases.
        !          1186: @end table
        !          1187: 
        !          1188: @cindex loading files at startup
        !          1189: @cindex executing code on startup
        !          1190: @cindex batch processing with Gforth
        !          1191: As explained above, the image-specific command-line arguments for the
        !          1192: default image @file{gforth.fi} consist of a sequence of filenames and
        !          1193: @code{-e @var{forth-code}} options that are interpreted in the sequence
        !          1194: in which they are given. The @code{-e @var{forth-code}} or
        !          1195: @code{--evaluate @var{forth-code}} option evaluates the Forth
        !          1196: code. This option takes only one argument; if you want to evaluate more
        !          1197: Forth words, you have to quote them or use @code{-e} several times. To exit
        !          1198: after processing the command line (instead of entering interactive mode)
        !          1199: append @code{-e bye} to the command line.
        !          1200: 
        !          1201: @cindex versions, invoking other versions of Gforth
        !          1202: If you have several versions of Gforth installed, @code{gforth} will
        !          1203: invoke the version that was installed last. @code{gforth-@i{version}}
        !          1204: invokes a specific version. If your environment contains the variable
        !          1205: @code{GFORTHPATH}, you may want to override it by using the
        !          1206: @code{--path} option.
        !          1207: 
        !          1208: Not yet implemented:
        !          1209: On startup the system first executes the system initialization file
        !          1210: (unless the option @code{--no-init-file} is given; note that the system
        !          1211: resulting from using this option may not be ANS Forth conformant). Then
        !          1212: the user initialization file @file{.gforth.fs} is executed, unless the
        !          1213: option @code{--no-rc} is given; this file is first searched in @file{.},
        !          1214: then in @file{~}, then in the normal path (see above).
        !          1215: 
        !          1216: 
        !          1217: 
        !          1218: @comment ----------------------------------------------
        !          1219: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
        !          1220: @section Leaving Gforth
        !          1221: @cindex Gforth - leaving
        !          1222: @cindex leaving Gforth
        !          1223: 
        !          1224: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
        !          1225: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
        !          1226: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
        !          1227: data are discarded. @xref{Image Files} for ways of saving the state of
        !          1228: the system before leaving Gforth.
        !          1229: 
        !          1230: doc-bye
        !          1231: 
        !          1232: 
        !          1233: @comment ----------------------------------------------
        !          1234: @node Command-line editing, Upper and lower case, Leaving Gforth, Gforth Environment
        !          1235: @section Command-line editing
        !          1236: @cindex command-line editing
        !          1237: 
        !          1238: Gforth maintains a history file that records every line that you type to
        !          1239: the text interpreter. This file is preserved between sessions, and is
        !          1240: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
        !          1241: repeatedly you can recall successively older commands from this (or
        !          1242: previous) session(s). The full list of command-line editing facilities is:
        !          1243: 
        !          1244: @itemize @bullet
        !          1245: @item
        !          1246: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
        !          1247: commands from the history buffer.
        !          1248: @item
        !          1249: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
        !          1250: from the history buffer.
        !          1251: @item
        !          1252: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
        !          1253: @item
        !          1254: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
        !          1255: @item
        !          1256: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
        !          1257: closing up the line.
        !          1258: @item
        !          1259: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
        !          1260: @item
        !          1261: @kbd{Ctrl-a} to move the cursor to the start of the line.
        !          1262: @item
        !          1263: @kbd{Ctrl-e} to move the cursor to the end of the line.
        !          1264: @item
        !          1265: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
        !          1266: line.
        !          1267: @item
        !          1268: @key{TAB} to step through all possible full-word completions of the word
        !          1269: currently being typed.
        !          1270: @item
        !          1271: @kbd{Ctrl-d} at the start of the line to terminate Gforth (gracefully,
        !          1272: using @code{bye}).
        !          1273: @end itemize
        !          1274: 
        !          1275: When editing, displayable characters are inserted to the left of the
        !          1276: cursor position; the line is always in ``insert'' (as opposed to
        !          1277: ``overstrike'') mode.
        !          1278: 
        !          1279: @cindex history file
        !          1280: @cindex @file{.gforth-history}
        !          1281: On Unix systems, the history file is @file{~/.gforth-history} by
        !          1282: default@footnote{i.e. it is stored in the user's home directory.}. You
        !          1283: can find out the name and location of your history file using:
        !          1284: 
        !          1285: @example 
        !          1286: history-file type \ Unix-class systems
        !          1287: 
        !          1288: history-file type \ Other systems
        !          1289: history-dir  type
        !          1290: @end example
        !          1291: 
        !          1292: If you enter long definitions by hand, you can use a text editor to
        !          1293: paste them out of the history file into a Forth source file for reuse at
        !          1294: a later time.
        !          1295: 
        !          1296: Gforth never trims the size of the history file, so you should do this
        !          1297: periodically, if necessary.
        !          1298: 
        !          1299: @comment this is all defined in history.fs
        !          1300: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
        !          1301: @comment chosen?
        !          1302: 
        !          1303: 
        !          1304: 
        !          1305: @comment ----------------------------------------------
        !          1306: @node Upper and lower case, Environment variables, Command-line editing, Gforth Environment
        !          1307: @section Upper and lower case
        !          1308: @cindex case-sensitivity
        !          1309: @cindex upper and lower case
        !          1310: 
        !          1311: Gforth is case-insensitive; you can enter definitions and invoke
        !          1312: Standard words using upper, lower or mixed case (however,
        !          1313: @pxref{core-idef, Implementation-defined options, Implementation-defined
        !          1314: options}).
        !          1315: 
        !          1316: ANS Forth only @i{requires} implementations to recognise Standard words
        !          1317: when they are typed entirely in upper case. Therefore, a Standard
        !          1318: program must use upper case for all Standard words. You can use whatever
        !          1319: case you like for words that you define, but in a standard program you
        !          1320: have to use the words in the same case that you defined them.
        !          1321: 
        !          1322: Gforth supports case sensitivity through @code{table}s (case-sensitive
        !          1323: wordlists, @pxref{Word Lists}).
        !          1324: 
        !          1325: Two people have asked how to convert Gforth to case sensitivity; while
        !          1326: we think this is a bad idea, you can change all wordlists into tables
        !          1327: like this:
        !          1328: 
        !          1329: @example
        !          1330: ' table-find forth-wordlist wordlist-map @ !
        !          1331: @end example
        !          1332: 
        !          1333: Note that you now have to type the predefined words in the same case
        !          1334: that we defined them, which are varying.  You may want to convert them
        !          1335: to your favourite case before doing this operation (I won't explain how,
        !          1336: because if you are even contemplating to do this, you'd better have
        !          1337: enough knowledge of Forth systems to know this already).
        !          1338: 
        !          1339: @comment ----------------------------------------------
        !          1340: @node Environment variables, Gforth Files, Upper and lower case, Gforth Environment
        !          1341: @section Environment variables
        !          1342: @cindex environment variables
        !          1343: 
        !          1344: Gforth uses these environment variables:
        !          1345: 
        !          1346: @itemize @bullet
        !          1347: @item
        !          1348: @cindex @code{GFORTHHIST} -- environment variable
        !          1349: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
        !          1350: open/create the history file, @file{.gforth-history}. Default:
        !          1351: @code{$HOME}.
        !          1352: 
        !          1353: @item
        !          1354: @cindex @code{GFORTHPATH} -- environment variable
        !          1355: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
        !          1356: for Forth source-code files.
        !          1357: 
        !          1358: @item
        !          1359: @cindex @code{GFORTH} -- environment variable
        !          1360: @code{GFORTH} -- used by @file{gforthmi} @xref{gforthmi}.
        !          1361: 
        !          1362: @item
        !          1363: @cindex @code{GFORTHD} -- environment variable
        !          1364: @code{GFORTHD} -- used by @file{gforthmi} @xref{gforthmi}.
        !          1365: 
        !          1366: @item
        !          1367: @cindex @code{TMP}, @code{TEMP} - environment variable
        !          1368: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
        !          1369: location for the history file.
        !          1370: @end itemize
        !          1371: 
        !          1372: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
        !          1373: @comment mentioning these.
        !          1374: 
        !          1375: All the Gforth environment variables default to sensible values if they
        !          1376: are not set.
        !          1377: 
        !          1378: 
        !          1379: @comment ----------------------------------------------
        !          1380: @node Gforth Files, Startup speed, Environment variables, Gforth Environment
        !          1381: @section Gforth files
        !          1382: @cindex Gforth files
        !          1383: 
        !          1384: When you install Gforth on a Unix system, it installs files in these
        !          1385: locations by default:
        !          1386: 
        !          1387: @itemize @bullet
        !          1388: @item
        !          1389: @file{/usr/local/bin/gforth}
        !          1390: @item
        !          1391: @file{/usr/local/bin/gforthmi}
        !          1392: @item
        !          1393: @file{/usr/local/man/man1/gforth.1} - man page.
        !          1394: @item
        !          1395: @file{/usr/local/info} - the Info version of this manual.
        !          1396: @item
        !          1397: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
        !          1398: @item
        !          1399: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
        !          1400: @item
        !          1401: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
        !          1402: @item
        !          1403: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
        !          1404: @end itemize
        !          1405: 
        !          1406: You can select different places for installation by using
        !          1407: @code{configure} options (listed with @code{configure --help}).
        !          1408: 
        !          1409: @comment ----------------------------------------------
        !          1410: @node Startup speed,  , Gforth Files, Gforth Environment
        !          1411: @section Startup speed
        !          1412: @cindex Startup speed
        !          1413: @cindex speed, startup
        !          1414: 
        !          1415: If Gforth is used for CGI scripts or in shell scripts, its startup
        !          1416: speed may become a problem.  On a 300MHz 21064a under Linux-2.2.13 with
        !          1417: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
        !          1418: system time.
        !          1419: 
        !          1420: If startup speed is a problem, you may consider the following ways to
        !          1421: improve it; or you may consider ways to reduce the number of startups
        !          1422: (e.g., Fast-CGI).
        !          1423: 
        !          1424: The first step to improve startup speed is to statically link Gforth, by
        !          1425: building it with @code{XLDFLAGS=-static}.  This requires more memory for
        !          1426: the code and will therefore slow down the first invocation, but
        !          1427: subsequent invocations avoid the dynamic linking overhead.  Another
        !          1428: disadvantage is that Gforth won't profit from library upgrades.  As a
        !          1429: result, @code{gforth-static -e bye} takes about 17.1ms user and
        !          1430: 8.2ms system time.
        !          1431: 
        !          1432: The next step to improve startup speed is to use a non-relocatable image
        !          1433: @ref{Non-Relocatable Image Files}.  You can create this image with
        !          1434: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
        !          1435: @code{gforth -i gforthnr.fi ...}.  This avoids the relocation overhead
        !          1436: and a part of the copy-on-write overhead.  The disadvantage is that the
        !          1437: nonrelocatable image does not work if the OS gives Gforth a different
        !          1438: address for the dictionary, for whatever reason; so you better provide a
        !          1439: fallback on a relocatable image.  @code{gforth-static -i gforthnr.fi -e
        !          1440: bye} takes about 15.3ms user and 7.5ms system time.
        !          1441: 
        !          1442: The final step is to disable dictionary hashing in Gforth.  Gforth
        !          1443: builds the hash table on startup, which takes much of the startup
        !          1444: overhead. You can do this by commenting out the @code{include hash.fs}
        !          1445: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
        !          1446: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
        !          1447: The disadvantages are that functionality like @code{table} and
        !          1448: @code{ekey} is missing and that text interpretation (e.g., compiling)
        !          1449: now takes much longer. So, you should only use this method if there is
        !          1450: no significant text interpretation to perform (the script should be
        !          1451: compiled into the image, among other things).  @code{gforth-static -i
        !          1452: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
        !          1453: 
        !          1454: @c ******************************************************************
        !          1455: @node Tutorial, Introduction, Gforth Environment, Top
        !          1456: @chapter Forth Tutorial
        !          1457: @cindex Tutorial
        !          1458: @cindex Forth Tutorial
        !          1459: 
        !          1460: This tutorial can be used with any ANS-compliant Forth; any places that
        !          1461: mention features specific to Gforth are marked as such and you can skip
        !          1462: them, if you work with another Forth.  This tutorial does not explain
        !          1463: all features of Forth, just enough to get you started and give you some
        !          1464: ideas about the facilities available in Forth.  Read the rest of the
        !          1465: manual and the standard when you are through this.
        !          1466: 
        !          1467: The intended way to use this tutorial is that you work through it while
        !          1468: sitting in front of the console, take a look at the examples and predict
        !          1469: what they will do, then try them out; if the outcome is not as expected,
        !          1470: find out why (e.g., by trying out variations of the example), so you
        !          1471: understand what's going on.  There are also some assignments that you
        !          1472: should solve.
        !          1473: 
        !          1474: This tutorial assumes that you have programmed before and know what,
        !          1475: e.g., a loop is.
        !          1476: 
        !          1477: @c !! explain compat library
        !          1478: 
        !          1479: @menu
        !          1480: * Starting Gforth Tutorial::    
        !          1481: * Syntax Tutorial::             
        !          1482: * Crash Course Tutorial::       
        !          1483: * Stack Tutorial::              
        !          1484: * Arithmetics Tutorial::        
        !          1485: * Stack Manipulation Tutorial::  
        !          1486: * Using files for Forth code Tutorial::  
        !          1487: * Comments Tutorial::           
        !          1488: * Colon Definitions Tutorial::  
        !          1489: * Decompilation Tutorial::      
        !          1490: * Stack-Effect Comments Tutorial::  
        !          1491: * Types Tutorial::              
        !          1492: * Factoring Tutorial::          
        !          1493: * Designing the stack effect Tutorial::  
        !          1494: * Local Variables Tutorial::    
        !          1495: * Conditional execution Tutorial::  
        !          1496: * Flags and Comparisons Tutorial::  
        !          1497: * General Loops Tutorial::      
        !          1498: * Counted loops Tutorial::      
        !          1499: * Recursion Tutorial::          
        !          1500: * Leaving definitions or loops Tutorial::  
        !          1501: * Return Stack Tutorial::       
        !          1502: * Memory Tutorial::             
        !          1503: * Characters and Strings Tutorial::  
        !          1504: * Alignment Tutorial::          
        !          1505: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
        !          1506: * Execution Tokens Tutorial::   
        !          1507: * Exceptions Tutorial::         
        !          1508: * Defining Words Tutorial::     
        !          1509: * Arrays and Records Tutorial::  
        !          1510: * POSTPONE Tutorial::           
        !          1511: * Literal Tutorial::            
        !          1512: * Advanced macros Tutorial::    
        !          1513: * Compilation Tokens Tutorial::  
        !          1514: * Wordlists and Search Order Tutorial::  
        !          1515: @end menu
        !          1516: 
        !          1517: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
        !          1518: @section Starting Gforth
        !          1519: 
        !          1520: You can start Gforth by typing its name:
        !          1521: 
        !          1522: @example
        !          1523: gforth
        !          1524: @end example
        !          1525: 
        !          1526: That puts you into interactive mode; you can leave Gforth by typing
        !          1527: @code{bye}.  While in Gforth, you can edit the command line and access
        !          1528: the command line history with cursor keys, similar to bash.
        !          1529: 
        !          1530: 
        !          1531: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
        !          1532: @section Syntax
        !          1533: 
        !          1534: A @dfn{word} is a sequence of arbitrary characters (expcept white
        !          1535: space).  Words are separated by white space.  E.g., each of the
        !          1536: following lines contains exactly one word:
        !          1537: 
        !          1538: @example
        !          1539: word
        !          1540: !@@#$%^&*()
        !          1541: 1234567890
        !          1542: 5!a
        !          1543: @end example
        !          1544: 
        !          1545: A frequent beginner's error is to leave away necessary white space,
        !          1546: resulting in an error like @samp{Undefined word}; so if you see such an
        !          1547: error, check if you have put spaces wherever necessary.
        !          1548: 
        !          1549: @example
        !          1550: ." hello, world" \ correct
        !          1551: ."hello, world"  \ gives an "Undefined word" error
        !          1552: @end example
        !          1553: 
        !          1554: Gforth and most other Forth systems ignores differences in case (it is
        !          1555: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
        !          1556: your system is case-sensitive, you may have to type all the examples
        !          1557: given here in upper case.
        !          1558: 
        !          1559: 
        !          1560: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
        !          1561: @section Crash Course
        !          1562: 
        !          1563: Type
        !          1564: 
        !          1565: @example
        !          1566: 0 0 !
        !          1567: here execute
        !          1568: ' catch >body 20 erase abort
        !          1569: ' (quit) >body 20 erase
        !          1570: @end example
        !          1571: 
        !          1572: The last two examples are guaranteed to destroy parts of Gforth (and
        !          1573: most other systems), so you better leave Gforth afterwards (if it has
        !          1574: not finished by itself).  On some systems you may have to kill gforth
        !          1575: from outside (e.g., in Unix with @code{kill}).
        !          1576: 
        !          1577: Now that you know how to produce crashes (and that there's not much to
        !          1578: them), let's learn how to produce meaningful programs.
        !          1579: 
        !          1580: 
        !          1581: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
        !          1582: @section Stack
        !          1583: 
        !          1584: The most obvious feature of Forth is the stack.  When you type in a
        !          1585: number, it is pushed on the stack.  You can display the content of the
        !          1586: stack with @code{.s}.
        !          1587: 
        !          1588: @example
        !          1589: 1 2 .s
        !          1590: 3 .s
        !          1591: @end example
        !          1592: 
        !          1593: @code{.s} displays the top-of-stack to the right, i.e., the numbers
        !          1594: appear in @code{.s} output as they appeared in the input.
        !          1595: 
        !          1596: You can print the top of stack element with @code{.}.
        !          1597: 
        !          1598: @example
        !          1599: 1 2 3 . . .
        !          1600: @end example
        !          1601: 
        !          1602: In general, words consume their stack arguments (@code{.s} is an
        !          1603: exception).
        !          1604: 
        !          1605: @assignment
        !          1606: What does the stack contain after @code{5 6 7 .}?
        !          1607: @endassignment
        !          1608: 
        !          1609: 
        !          1610: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
        !          1611: @section Arithmetics
        !          1612: 
        !          1613: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
        !          1614: operate on the top two stack items:
        !          1615: 
        !          1616: @example
        !          1617: 2 2 + .
        !          1618: 2 1 - .
        !          1619: 7 3 mod .
        !          1620: @end example
        !          1621: 
        !          1622: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
        !          1623: as in the corresponding infix expression (this is generally the case in
        !          1624: Forth).
        !          1625: 
        !          1626: Parentheses are superfluous (and not available), because the order of
        !          1627: the words unambiguously determines the order of evaluation and the
        !          1628: operands:
        !          1629: 
        !          1630: @example
        !          1631: 3 4 + 5 * .
        !          1632: 3 4 5 * + .
        !          1633: @end example
        !          1634: 
        !          1635: @assignment
        !          1636: What are the infix expressions corresponding to the Forth code above?
        !          1637: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
        !          1638: known as Postfix or RPN (Reverse Polish Notation).}.
        !          1639: @endassignment
        !          1640: 
        !          1641: To change the sign, use @code{negate}:
        !          1642: 
        !          1643: @example
        !          1644: 2 negate .
        !          1645: @end example
        !          1646: 
        !          1647: @assignment
        !          1648: Convert -(-3)*4-5 to Forth.
        !          1649: @endassignment
        !          1650: 
        !          1651: @code{/mod} performs both @code{/} and @code{mod}.
        !          1652: 
        !          1653: @example
        !          1654: 7 3 /mod . .
        !          1655: @end example
        !          1656: 
        !          1657: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
        !          1658: @section Stack Manipulation
        !          1659: 
        !          1660: Stack manipulation words rearrange the data on the stack.
        !          1661: 
        !          1662: @example
        !          1663: 1 .s drop .s
        !          1664: 1 .s dup .s drop drop .s
        !          1665: 1 2 .s over .s drop drop drop
        !          1666: 1 2 .s swap .s drop drop
        !          1667: 1 2 3 .s rot .s drop drop drop
        !          1668: @end example
        !          1669: 
        !          1670: These are the most important stack manipulation words.  There are also
        !          1671: variants that manipulate twice as many stack items:
        !          1672: 
        !          1673: @example
        !          1674: 1 2 3 4 .s 2swap .s 2drop 2drop
        !          1675: @end example
        !          1676: 
        !          1677: Two more stack manipulation words are:
        !          1678: 
        !          1679: @example
        !          1680: 1 2 .s nip .s drop
        !          1681: 1 2 .s tuck .s 2drop drop
        !          1682: @end example
        !          1683: 
        !          1684: @assignment
        !          1685: Replace @code{nip} and @code{tuck} with combinations of other stack
        !          1686: manipulation words.
        !          1687: 
        !          1688: @example
        !          1689: Given:          How do you get:
        !          1690: 1 2 3           3 2 1           
        !          1691: 1 2 3           1 2 3 2                 
        !          1692: 1 2 3           1 2 3 3                 
        !          1693: 1 2 3           1 3 3           
        !          1694: 1 2 3           2 1 3           
        !          1695: 1 2 3 4         4 3 2 1         
        !          1696: 1 2 3           1 2 3 1 2 3             
        !          1697: 1 2 3 4         1 2 3 4 1 2             
        !          1698: 1 2 3
        !          1699: 1 2 3           1 2 3 4                 
        !          1700: 1 2 3           1 3             
        !          1701: @end example
        !          1702: @endassignment
        !          1703: 
        !          1704: @example
        !          1705: 5 dup * .
        !          1706: @end example
        !          1707: 
        !          1708: @assignment
        !          1709: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
        !          1710: Write a piece of Forth code that expects two numbers on the stack
        !          1711: (@var{a} and @var{b}, with @var{b} on top) and computes
        !          1712: @code{(a-b)(a+1)}.
        !          1713: @endassignment
        !          1714: 
        !          1715: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
        !          1716: @section Using files for Forth code
        !          1717: 
        !          1718: While working at the Forth command line is convenient for one-line
        !          1719: examples and short one-off code, you probably want to store your source
        !          1720: code in files for convenient editing and persistence.  You can use your
        !          1721: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
        !          1722: Gforth}) to create @var{file} and use
        !          1723: 
        !          1724: @example
        !          1725: s" @var{file}" included
        !          1726: @end example
        !          1727: 
        !          1728: to load it into your Forth system.  The file name extension I use for
        !          1729: Forth files is @samp{.fs}.
        !          1730: 
        !          1731: You can easily start Gforth with some files loaded like this:
        !          1732: 
        !          1733: @example
        !          1734: gforth @var{file1} @var{file2}
        !          1735: @end example
        !          1736: 
        !          1737: If an error occurs during loading these files, Gforth terminates,
        !          1738: whereas an error during @code{INCLUDED} within Gforth usually gives you
        !          1739: a Gforth command line.  Starting the Forth system every time gives you a
        !          1740: clean start every time, without interference from the results of earlier
        !          1741: tries.
        !          1742: 
        !          1743: I often put all the tests in a file, then load the code and run the
        !          1744: tests with
        !          1745: 
        !          1746: @example
        !          1747: gforth @var{code} @var{tests} -e bye
        !          1748: @end example
        !          1749: 
        !          1750: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
        !          1751: @code{-e bye} ensures that Gforth terminates afterwards so that I can
        !          1752: restart this command without ado.
        !          1753: 
        !          1754: The advantage of this approach is that the tests can be repeated easily
        !          1755: every time the program ist changed, making it easy to catch bugs
        !          1756: introduced by the change.
        !          1757: 
        !          1758: 
        !          1759: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
        !          1760: @section Comments
        !          1761: 
        !          1762: @example
        !          1763: \ That's a comment; it ends at the end of the line
        !          1764: ( Another comment; it ends here: )  .s
        !          1765: @end example
        !          1766: 
        !          1767: @code{\} and @code{(} are ordinary Forth words and therefore have to be
        !          1768: separated with white space from the following text.
        !          1769: 
        !          1770: @example
        !          1771: \This gives an "Undefined word" error
        !          1772: @end example
        !          1773: 
        !          1774: The first @code{)} ends a comment started with @code{(}, so you cannot
        !          1775: nest @code{(}-comments; and you cannot comment out text containing a
        !          1776: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
        !          1777: avoid @code{)} in word names.}.
        !          1778: 
        !          1779: I use @code{\}-comments for descriptive text and for commenting out code
        !          1780: of one or more line; I use @code{(}-comments for describing the stack
        !          1781: effect, the stack contents, or for commenting out sub-line pieces of
        !          1782: code.
        !          1783: 
        !          1784: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
        !          1785: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
        !          1786: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
        !          1787: with @kbd{M-q}.
        !          1788: 
        !          1789: 
        !          1790: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
        !          1791: @section Colon Definitions
        !          1792: 
        !          1793: are similar to procedures and functions in other programming languages.
        !          1794: 
        !          1795: @example
        !          1796: : squared ( n -- n^2 )
        !          1797:    dup * ;
        !          1798: 5 squared .
        !          1799: 7 squared .
        !          1800: @end example
        !          1801: 
        !          1802: @code{:} starts the colon definition; its name is @code{squared}.  The
        !          1803: following comment describes its stack effect.  The words @code{dup *}
        !          1804: are not executed, but compiled into the definition.  @code{;} ends the
        !          1805: colon definition.
        !          1806: 
        !          1807: The newly-defined word can be used like any other word, including using
        !          1808: it in other definitions:
        !          1809: 
        !          1810: @example
        !          1811: : cubed ( n -- n^3 )
        !          1812:    dup squared * ;
        !          1813: -5 cubed .
        !          1814: : fourth-power ( n -- n^4 )
        !          1815:    squared squared ;
        !          1816: 3 fourth-power .
        !          1817: @end example
        !          1818: 
        !          1819: @assignment
        !          1820: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
        !          1821: @code{/mod} in terms of other Forth words, and check if they work (hint:
        !          1822: test your tests on the originals first).  Don't let the
        !          1823: @samp{redefined}-Messages spook you, they are just warnings.
        !          1824: @endassignment
        !          1825: 
        !          1826: 
        !          1827: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
        !          1828: @section Decompilation
        !          1829: 
        !          1830: You can decompile colon definitions with @code{see}:
        !          1831: 
        !          1832: @example
        !          1833: see squared
        !          1834: see cubed
        !          1835: @end example
        !          1836: 
        !          1837: In Gforth @code{see} shows you a reconstruction of the source code from
        !          1838: the executable code.  Informations that were present in the source, but
        !          1839: not in the executable code, are lost (e.g., comments).
        !          1840: 
        !          1841: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
        !          1842: @section Stack-Effect Comments
        !          1843: 
        !          1844: By convention the comment after the name of a definition describes the
        !          1845: stack effect: The part in from of the @samp{--} describes the state of
        !          1846: the stack before the execution of the definition, i.e., the parameters
        !          1847: that are passed into the colon definition; the part behind the @samp{--}
        !          1848: is the state of the stack after the execution of the definition, i.e.,
        !          1849: the results of the definition.  The stack comment only shows the top
        !          1850: stack items that the definition accesses and/or changes.
        !          1851: 
        !          1852: You should put a correct stack effect on every definition, even if it is
        !          1853: just @code{( -- )}.  You should also add some descriptive comment to
        !          1854: more complicated words (I usually do this in the lines following
        !          1855: @code{:}).  If you don't do this, your code becomes unreadable (because
        !          1856: you have to work through every definition before you can undertsand
        !          1857: any).
        !          1858: 
        !          1859: @assignment
        !          1860: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
        !          1861: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
        !          1862: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
        !          1863: are done, you can compare your stack effects to this in this manual
        !          1864: (@pxref{Word Index}).
        !          1865: @endassignment
        !          1866: 
        !          1867: Sometimes programmers put comments at various places in colon
        !          1868: definitions that describe the contents of the stack at that place (stack
        !          1869: comments); i.e., they are like the first part of a stack-effect
        !          1870: comment. E.g.,
        !          1871: 
        !          1872: @example
        !          1873: : cubed ( n -- n^3 )
        !          1874:    dup squared  ( n n^2 ) * ;
        !          1875: @end example
        !          1876: 
        !          1877: In this case the stack comment is pretty superfluous, because the word
        !          1878: is simple enough.  If you think it would be a good idea to add such a
        !          1879: comment to increase readability, you should also consider factoring the
        !          1880: word into several simpler words (@pxref{Factoring Tutorial,,
        !          1881: Factoring}), which typically eliminates the need for the stack effect;
        !          1882: however, if you decide not to refactor it, then having such a comment is
        !          1883: better than not having it.
        !          1884: 
        !          1885: The names of the stack items in stack-effect and stack comments in the
        !          1886: standard, in this manual, and in many programs specify the type through
        !          1887: a type prefix, similar to Fortran and Hungarian notation.  The most
        !          1888: frequent prefixes are:
        !          1889: 
        !          1890: @table @code
        !          1891: @item n
        !          1892: signed integer
        !          1893: @item u
        !          1894: unsigned integer
        !          1895: @item c
        !          1896: character
        !          1897: @item f
        !          1898: Boolean flags, i.e. @code{false} or @code{true}.
        !          1899: @item a-addr,a-
        !          1900: Cell-aligned address
        !          1901: @item c-addr,c-
        !          1902: Char-aligned address (note that a Char may have two bytes in Windows NT)
        !          1903: @item xt
        !          1904: Execution token, same size as Cell
        !          1905: @item w,x
        !          1906: Cell, can contain an integer or an address.  It usually takes 32, 64 or
        !          1907: 16 bits (depending on your platform and Forth system). A cell is more
        !          1908: commonly known as machine word, but the term @emph{word} already means
        !          1909: something different in Forth.
        !          1910: @item d
        !          1911: signed double-cell integer
        !          1912: @item ud
        !          1913: unsigned double-cell integer
        !          1914: @item r
        !          1915: Float (on the FP stack)
        !          1916: @end table
        !          1917: 
        !          1918: You can find a more complete list in @ref{Notation}.
        !          1919: 
        !          1920: @assignment
        !          1921: Write stack-effect comments for all definitions you have written up to
        !          1922: now.
        !          1923: @endassignment
        !          1924: 
        !          1925: 
        !          1926: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
        !          1927: @section Types
        !          1928: 
        !          1929: In Forth the names of the operations are not overloaded; so similar
        !          1930: operations on different types need different names; e.g., @code{+} adds
        !          1931: integers, and you have to use @code{f+} to add floating-point numbers.
        !          1932: The following prefixes are often used for related operations on
        !          1933: different types:
        !          1934: 
        !          1935: @table @code
        !          1936: @item (none)
        !          1937: signed integer
        !          1938: @item u
        !          1939: unsigned integer
        !          1940: @item c
        !          1941: character
        !          1942: @item d
        !          1943: signed double-cell integer
        !          1944: @item ud, du
        !          1945: unsigned double-cell integer
        !          1946: @item 2
        !          1947: two cells (not-necessarily double-cell numbers)
        !          1948: @item m, um
        !          1949: mixed single-cell and double-cell operations
        !          1950: @item f
        !          1951: floating-point (note that in stack comments @samp{f} represents flags,
        !          1952: and @samp{r} represents FP number).
        !          1953: @end table
        !          1954: 
        !          1955: If there are no differences between the signed and the unsigned variant
        !          1956: (e.g., for @code{+}), there is only the prefix-less variant.
        !          1957: 
        !          1958: Forth does not perform type checking, neither at compile time, nor at
        !          1959: run time.  If you use the wrong oeration, the data are interpreted
        !          1960: incorrectly:
        !          1961: 
        !          1962: @example
        !          1963: -1 u.
        !          1964: @end example
        !          1965: 
        !          1966: If you have only experience with type-checked languages until now, and
        !          1967: have heard how important type-checking is, don't panic!  In my
        !          1968: experience (and that of other Forthers), type errors in Forth code are
        !          1969: usually easy to find (once you get used to it), the increased vigilance
        !          1970: of the programmer tends to catch some harder errors in addition to most
        !          1971: type errors, and you never have to work around the type system, so in
        !          1972: most situations the lack of type-checking seems to be a win (projects to
        !          1973: add type checking to Forth have not caught on).
        !          1974: 
        !          1975: 
        !          1976: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
        !          1977: @section Factoring
        !          1978: 
        !          1979: If you try to write longer definitions, you will soon find it hard to
        !          1980: keep track of the stack contents.  Therefore, good Forth programmers
        !          1981: tend to write only short definitions (e.g., three lines).  The art of
        !          1982: finding meaningful short definitions is known as factoring (as in
        !          1983: factoring polynomials).
        !          1984: 
        !          1985: Well-factored programs offer additional advantages: smaller, more
        !          1986: general words, are easier to test and debug and can be reused more and
        !          1987: better than larger, specialized words.
        !          1988: 
        !          1989: So, if you run into difficulties with stack management, when writing
        !          1990: code, try to define meaningful factors for the word, and define the word
        !          1991: in terms of those.  Even if a factor contains only two words, it is
        !          1992: often helpful.
        !          1993: 
        !          1994: Good factoring is not easy, and even experienced Forth programmers often
        !          1995: don't find the right solution right away, but only when rewriting the
        !          1996: program.  So, if you don't come up with a good solution immediately,
        !          1997: keep trying, don't despair.
        !          1998: 
        !          1999: @c example !!
        !          2000: 
        !          2001: 
        !          2002: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
        !          2003: @section Designing the stack effect
        !          2004: 
        !          2005: In other languages you can use an arbitrary order of parameters for a
        !          2006: function; and since ther is only one result, you don't have to deal with
        !          2007: the order of results, either.
        !          2008: 
        !          2009: In Forth (and other stack-based languages, e.g., Postscript) the
        !          2010: parameter and result order of a definition is important and should be
        !          2011: designed well.  The general guideline is to design the stack effect such
        !          2012: that the word is simple to use in most cases, even if that complicates
        !          2013: the implementation of the word.  Some concrete rules are:
        !          2014: 
        !          2015: @itemize @bullet
        !          2016: 
        !          2017: @item
        !          2018: Words consume all of their parameters (e.g., @code{.}).
        !          2019: 
        !          2020: @item
        !          2021: If there is a convention on the order of parameters (e.g., from
        !          2022: mathematics or another programming language), stick with it (e.g.,
        !          2023: @code{-}).
        !          2024: 
        !          2025: @item
        !          2026: If one parameter usually requires only a short computation (e.g., it is
        !          2027: a constant), pass it on the top of the stack.  Conversely, parameters
        !          2028: that usually require a long sequence of code to compute should be passed
        !          2029: as the bottom (i.e., first) parameter.  This makes the code easier to
        !          2030: read, because reader does not need to keep track of the bottom item
        !          2031: through a long sequence of code (or, alternatively, through stack
        !          2032: manipulations). E.g., @code{!} (store, see @pxref{Memory}) expects the
        !          2033: address on top of the stack because it is usually simpler to compute
        !          2034: than the stored value (often the address is just a variable).
        !          2035: 
        !          2036: @item
        !          2037: Similarly, results that are usually consumed quickly should be returned
        !          2038: on the top of stack, whereas a result that is often used in long
        !          2039: computations should be passed as bottom result.  E.g., the file words
        !          2040: like @code{open-file} return the error code on the top of stack, because
        !          2041: it is usually consumed quickly by @code{throw}; moreover, the error code
        !          2042: has to be checked before doing anything with the other results.
        !          2043: 
        !          2044: @end itemize
        !          2045: 
        !          2046: These rules are just general guidelines, don't lose sight of the overall
        !          2047: goal to make the words easy to use.  E.g., if the convention rule
        !          2048: conflicts with the computation-length rule, you might decide in favour
        !          2049: of the convention if the word will be used rarely, and in favour of the
        !          2050: computation-length rule if the word will be used frequently (because
        !          2051: with frequent use the cost of breaking the computation-length rule would
        !          2052: be quite high, and frequent use makes it easier to remember an
        !          2053: unconventional order).
        !          2054: 
        !          2055: @c example !! structure package
        !          2056: 
        !          2057: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
        !          2058: @section Local Variables
        !          2059: 
        !          2060: You can define local variables (@emph{locals}) in a colon definition:
        !          2061: 
        !          2062: @example
        !          2063: : swap @{ a b -- b a @}
        !          2064:   b a ;
        !          2065: 1 2 swap .s 2drop
        !          2066: @end example
        !          2067: 
        !          2068: (If your Forth system does not support this syntax, include
        !          2069: @file{compat/anslocals.fs} first).
        !          2070: 
        !          2071: In this example @code{@{ a b -- b a @}} is the locals definition; it
        !          2072: takes two cells from the stack, puts the top of stack in @code{b} and
        !          2073: the next stack element in @code{a}.  @code{--} starts a comment ending
        !          2074: with @code{@}}.  After the locals definition, using the name of the
        !          2075: local will push its value on the stack.  You can leave the comment
        !          2076: part (@code{-- b a}) away:
        !          2077: 
        !          2078: @example
        !          2079: : swap ( x1 x2 -- x2 x1 )
        !          2080:   @{ a b @} b a ;
        !          2081: @end example
        !          2082: 
        !          2083: In Gforth you can have several locals definitions, anywhere in a colon
        !          2084: definition; in contrast, in a standard program you can have only one
        !          2085: locals definition per colon definition, and that locals definition must
        !          2086: be outside any controll structure.
        !          2087: 
        !          2088: With locals you can write slightly longer definitions without running
        !          2089: into stack trouble.  However, I recommend trying to write colon
        !          2090: definitions without locals for exercise purposes to help you gain the
        !          2091: essential factoring skills.
        !          2092: 
        !          2093: @assignment
        !          2094: Rewrite your definitions until now with locals
        !          2095: @endassignment
        !          2096: 
        !          2097: 
        !          2098: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
        !          2099: @section Conditional execution
        !          2100: 
        !          2101: In Forth you can use control structures only inside colon definitions.
        !          2102: An @code{if}-structure looks like this:
        !          2103: 
        !          2104: @example
        !          2105: : abs ( n1 -- +n2 )
        !          2106:     dup 0 < if
        !          2107:         negate
        !          2108:     endif ;
        !          2109: 5 abs .
        !          2110: -5 abs .
        !          2111: @end example
        !          2112: 
        !          2113: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
        !          2114: the following code is performed, otherwise execution continues after the
        !          2115: @code{endif} (or @code{else}).  @code{<} combares the top two stack
        !          2116: elements and prioduces a flag:
        !          2117: 
        !          2118: @example
        !          2119: 1 2 < .
        !          2120: 2 1 < .
        !          2121: 1 1 < .
        !          2122: @end example
        !          2123: 
        !          2124: Actually the standard name for @code{endif} is @code{then}.  This
        !          2125: tutorial presents the examples using @code{endif}, because this is often
        !          2126: less confusing for people familiar with other programming languages
        !          2127: where @code{then} has a different meaning.  If your system does not have
        !          2128: @code{endif}, define it with
        !          2129: 
        !          2130: @example
        !          2131: : endif postpone then ; immediate
        !          2132: @end example
        !          2133: 
        !          2134: You can optionally use an @code{else}-part:
        !          2135: 
        !          2136: @example
        !          2137: : min ( n1 n2 -- n )
        !          2138:   2dup < if
        !          2139:     drop
        !          2140:   else
        !          2141:     nip
        !          2142:   endif ;
        !          2143: 2 3 min .
        !          2144: 3 2 min .
        !          2145: @end example
        !          2146: 
        !          2147: @assignment
        !          2148: Write @code{min} without @code{else}-part (hint: what's the definition
        !          2149: of @code{nip}?).
        !          2150: @endassignment
        !          2151: 
        !          2152: 
        !          2153: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
        !          2154: @section Flags and Comparisons
        !          2155: 
        !          2156: In a false-flag all bits are clear (0 when interpreted as integer).  In
        !          2157: a canonical true-flag all bits are set (-1 as a twos-complement signed
        !          2158: integer); in many contexts (e.g., @code{if}) any non-zero value is
        !          2159: treated as true flag.
        !          2160: 
        !          2161: @example
        !          2162: false .
        !          2163: true .
        !          2164: true hex u. decimal
        !          2165: @end example
        !          2166: 
        !          2167: Comparison words produce canonical flags:
        !          2168: 
        !          2169: @example
        !          2170: 1 1 = .
        !          2171: 1 0= .
        !          2172: 0 1 < .
        !          2173: 0 0 < .
        !          2174: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
        !          2175: -1 1 < .
        !          2176: @end example
        !          2177: 
        !          2178: Gforth supports all combinations of the prefixes @code{0 u d d0 du} (or
        !          2179: none) and the comparisons @code{= <> < > <= >=}.  Only a part of these
        !          2180: combinations are standard (see the standard or !! the glossary for
        !          2181: details).
        !          2182: 
        !          2183: You can use @code{and or xor invert} can be used as operations on
        !          2184: canonical flags.  Actually they are bitwise operations:
        !          2185: 
        !          2186: @example
        !          2187: 1 2 and .
        !          2188: 1 2 or .
        !          2189: 1 3 xor .
        !          2190: 1 invert .
        !          2191: @end example
        !          2192: 
        !          2193: You can convert a zero/non-zero flag into a canonical flag with
        !          2194: @code{0<>} (and complement it on the way with @code{0=}).
        !          2195: 
        !          2196: @example
        !          2197: 1 0= .
        !          2198: 1 0<> .
        !          2199: @end example
        !          2200: 
        !          2201: You can use the all-bits-set feature of canonicasl flags and the bitwise
        !          2202: operation of the Boolean operations to avoid @code{if}s:
        !          2203: 
        !          2204: @example
        !          2205: : foo ( n1 -- n2 )
        !          2206:   0= if
        !          2207:     14
        !          2208:   else
        !          2209:     0
        !          2210:   endif ;
        !          2211: 0 foo .
        !          2212: 1 foo .
        !          2213: 
        !          2214: : foo ( n1 -- n2 )
        !          2215:   0= 14 and ;
        !          2216: 0 foo .
        !          2217: 1 foo .
        !          2218: @end example
        !          2219: 
        !          2220: @assignment
        !          2221: Write @code{min} without @code{if}.
        !          2222: @endassignment
        !          2223: 
        !          2224: 
        !          2225: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
        !          2226: @section General Loops
        !          2227: 
        !          2228: The endless loop is the most simple one:
        !          2229: 
        !          2230: @example
        !          2231: : endless ( -- )
        !          2232:   0 begin
        !          2233:     dup . 1+
        !          2234:   again ;
        !          2235: endless
        !          2236: @end example
        !          2237: 
        !          2238: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
        !          2239: does nothing at run-time, @code{again} jumps back to @code{begin}.
        !          2240: 
        !          2241: A loop with one exit at any place looks like this:
        !          2242: 
        !          2243: @example
        !          2244: : log2 ( +n1 -- n2 )
        !          2245: \ logarithmus dualis of n1>0, rounded down to the next integer
        !          2246:   assert( dup 0> )
        !          2247:   2/ 0 begin
        !          2248:     over 0> while
        !          2249:       1+ swap 2/ swap
        !          2250:   repeat
        !          2251:   nip ;
        !          2252: 7 log2 .
        !          2253: 8 log2 .
        !          2254: @end example
        !          2255: 
        !          2256: At run-time @code{while} consumes a flag; if it is 0, execution
        !          2257: continues behind the @code{repeat}; if the falg is non-zero, execution
        !          2258: continues behind the @code{while}.  @code{Repeat} jumps back to
        !          2259: @code{begin}, just like @code{again}.
        !          2260: 
        !          2261: In Forth there are many combinations/abbreviations, like @code{1+}.
        !          2262: However, @code{2/} is not one of them; it shifts it's argument right by
        !          2263: one bit (arithmetic shift right):
        !          2264: 
        !          2265: @example
        !          2266: -5 2 / .
        !          2267: -5 2/ .
        !          2268: @end example
        !          2269: 
        !          2270: @code{assert(} is no standard word, but you can get it on systems other
        !          2271: then Gforth by including @file{compat/assert.fs}.  You can see what it
        !          2272: does by trying
        !          2273: 
        !          2274: @example
        !          2275: 0 log2 .
        !          2276: @end example
        !          2277: 
        !          2278: Here's a loop with an exit at the end:
        !          2279: 
        !          2280: @example
        !          2281: : log2 ( +n1 -- n2 )
        !          2282: \ logarithmus dualis of n1>0, rounded down to the next integer
        !          2283:   assert( dup 0 > )
        !          2284:   -1 begin
        !          2285:     1+ swap 2/ swap
        !          2286:     over 0 <=
        !          2287:   until
        !          2288:   nip ;
        !          2289: @end example
        !          2290: 
        !          2291: @code{Until} consumes a flag; if it is non-zero, execution continues at
        !          2292: the @code{begin}, otherwise after the @code{until}.
        !          2293: 
        !          2294: @assignment
        !          2295: Write a definition for computing the greatest common divisor.
        !          2296: @endassignment
        !          2297: 
        !          2298: 
        !          2299: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
        !          2300: @section Counted loops
        !          2301: 
        !          2302: @example
        !          2303: : ^ ( n1 u -- n )
        !          2304: \ n = the uth power of u1
        !          2305:   1 swap 0 u+do
        !          2306:     over *
        !          2307:   loop
        !          2308:   nip ;
        !          2309: 3 2 ^ .
        !          2310: 4 3 ^ .
        !          2311: @end example
        !          2312: 
        !          2313: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
        !          2314: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
        !          2315: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
        !          2316: times (or not at all, if @code{u3-u4<0}).
        !          2317: 
        !          2318: You can see the stack effect design rules at work in the stack effect of
        !          2319: the loop start words: Since the start value of the loop is more
        !          2320: frequently constant than the end value, the start value is passed on
        !          2321: the top-of-stack.
        !          2322: 
        !          2323: You can access the counter of a counted loop with @code{i}:
        !          2324: 
        !          2325: @example
        !          2326: : fac ( u -- u! )
        !          2327:   1 swap 1+ 1 u+do
        !          2328:     i *
        !          2329:   loop ;
        !          2330: 5 fac .
        !          2331: 7 fac .
        !          2332: @end example
        !          2333: 
        !          2334: There is also @code{+do}, which expects signed numbers (important for
        !          2335: deciding whether to enter the loop).
        !          2336: 
        !          2337: @assignment
        !          2338: Write a definition for computing the nth Fibonacci number.
        !          2339: @endassignment
        !          2340: 
        !          2341: !! +DO...+LOOP
        !          2342: !! -DO...-LOOP
        !          2343: 
        !          2344: 
        !          2345: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
        !          2346: @section Recursion
        !          2347: 
        !          2348: Usually the name of a definition is not visible in the definition; but
        !          2349: earlier definitions are usually visible:
        !          2350: 
        !          2351: @example
        !          2352: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
        !          2353: : / ( n1 n2 -- n )
        !          2354:   dup 0= if
        !          2355:     -10 throw \ report division by zero
        !          2356:   endif
        !          2357:   /           \ old version
        !          2358: ;
        !          2359: 1 0 /
        !          2360: @end example
        !          2361: 
        !          2362: For recursive definitions you can use @code{recursive} (non-standard) or
        !          2363: @code{recurse}:
        !          2364: 
        !          2365: @example
        !          2366: : fac1 ( n -- n! ) recursive
        !          2367:  dup 0> if
        !          2368:    dup 1- fac1 *
        !          2369:  else
        !          2370:    drop 1
        !          2371:  endif ;
        !          2372: 7 fac1 .
        !          2373: 
        !          2374: : fac2 ( n -- n! )
        !          2375:  dup 0> if
        !          2376:    dup 1- recurse *
        !          2377:  else
        !          2378:    drop 1
        !          2379:  endif ;
        !          2380: 8 fac2 .
        !          2381: @end example
        !          2382: 
        !          2383: @assignment
        !          2384: Write a recursive definition for computing the nth Fibonacci number.
        !          2385: @endassignment
        !          2386: 
        !          2387: 
        !          2388: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
        !          2389: @section Leaving definitions or loops
        !          2390: 
        !          2391: @code{EXIT} exits the current definition right away.  For every counted
        !          2392: loop that is left in this way, an @code{UNLOOP} has to be performed
        !          2393: before the @code{EXIT}:
        !          2394: 
        !          2395: @c !! real examples
        !          2396: @example
        !          2397: : ...
        !          2398:  ... u+do
        !          2399:    ... if
        !          2400:      ... unloop exit
        !          2401:    endif
        !          2402:    ...
        !          2403:  loop
        !          2404:  ... ;
        !          2405: @end example
        !          2406: 
        !          2407: @code{LEAVE} leaves the innermost counted loop right away:
        !          2408: 
        !          2409: @example
        !          2410: : ...
        !          2411:  ... u+do
        !          2412:    ... if
        !          2413:      ... leave
        !          2414:    endif
        !          2415:    ...
        !          2416:  loop
        !          2417:  ... ;
        !          2418: @end example
        !          2419: 
        !          2420: 
        !          2421: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
        !          2422: @section Return Stack
        !          2423: 
        !          2424: In addition to the data stack Forth also has a second stack, the return
        !          2425: stack; most Forth systems store the return addresses of procedure calls
        !          2426: there (thus its name).  Programmers can also use this stack:
        !          2427: 
        !          2428: @example
        !          2429: : foo ( n1 n2 -- )
        !          2430:  .s
        !          2431:  >r .s
        !          2432:  r@ .
        !          2433:  >r .s
        !          2434:  r@ .
        !          2435:  r> .
        !          2436:  r@ .
        !          2437:  r> . ;
        !          2438: 1 2 foo
        !          2439: @end example
        !          2440: 
        !          2441: @code{>r} takes an element from the data stack and pushes it onto the
        !          2442: return stack; conversely, @code{r>} moves an elementm from the return to
        !          2443: the data stack; @code{r@@} pushes a copy of the top of the return stack
        !          2444: on the return stack.
        !          2445: 
        !          2446: Forth programmers usually use the return stack for storing data
        !          2447: temporarily, if using the data stack alone would be too complex, and
        !          2448: factoring and locals are not an option:
        !          2449: 
        !          2450: @example
        !          2451: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
        !          2452:  rot >r rot r> ;
        !          2453: @end example
        !          2454: 
        !          2455: The return address of the definition and the loop control parameters of
        !          2456: counted loops usually reside on the return stack, so you have to take
        !          2457: all items, that you have pushed on the return stack in a colon
        !          2458: definition or counted loop, from the return stack before the definition
        !          2459: or loop ends.  You cannot access items that you pushed on the return
        !          2460: stack outside some definition or loop within the definition of loop.
        !          2461: 
        !          2462: If you miscount the return stack items, this usually ends in a crash:
        !          2463: 
        !          2464: @example
        !          2465: : crash ( n -- )
        !          2466:   >r ;
        !          2467: 5 crash
        !          2468: @end example
        !          2469: 
        !          2470: You cannot mix using locals and using the return stack (according to the
        !          2471: standard; Gforth has no problem).  However, they solve the same
        !          2472: problems, so this shouldn't be an issue.
        !          2473: 
        !          2474: @assignment
        !          2475: Can you rewrite any of the definitions you wrote until now in a better
        !          2476: way using the return stack?
        !          2477: @endassignment
        !          2478: 
        !          2479: 
        !          2480: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
        !          2481: @section Memory
        !          2482: 
        !          2483: You can create a global variable @code{v} with
        !          2484: 
        !          2485: @example
        !          2486: variable v ( -- addr )
        !          2487: @end example
        !          2488: 
        !          2489: @code{v} pushes the address of a cell in memory on the stack.  This cell
        !          2490: was reserved by @code{variable}.  You can use @code{!} (store) to store
        !          2491: values into this cell and @code{@@} (fetch) to load the value from the
        !          2492: stack into memory:
        !          2493: 
        !          2494: @example
        !          2495: v .
        !          2496: 5 v ! .s
        !          2497: v @ .
        !          2498: @end example
        !          2499: 
        !          2500: You can also reserve more memory:
        !          2501: 
        !          2502: @example
        !          2503: create v2 20 cells allot
        !          2504: @end example
        !          2505: 
        !          2506: creates a word @code{v2} and reserves 20 cells; the address pushed by
        !          2507: @code{v2} points to the start of these 20 cells.  You can use address
        !          2508: arithmetic to access these cells:
        !          2509: 
        !          2510: @example
        !          2511: 3 v2 5 cells + !
        !          2512: @end example
        !          2513: 
        !          2514: You can reserve and initialize memory with @code{,}:
        !          2515: 
        !          2516: @example
        !          2517: create v3
        !          2518:   5 , 4 , 3 , 2 , 1 ,
        !          2519: v3 @ .
        !          2520: v3 cell+ @ .
        !          2521: v3 2 cells + @ .
        !          2522: @end example
        !          2523: 
        !          2524: @assignment
        !          2525: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
        !          2526: @code{u} cells, with the first of these cells at @code{addr}, the next
        !          2527: one at @code{addr cell+} etc.
        !          2528: @endassignment
        !          2529: 
        !          2530: You can also reserve memory without creating a new word:
        !          2531: 
        !          2532: @example
        !          2533: here 10 cells allot
        !          2534: .s
        !          2535: @end example
        !          2536: 
        !          2537: @code{Here} pushes the start address of the memory area.  You should
        !          2538: store it somewhere, or you will have a hard time finding the memory area
        !          2539: again.
        !          2540: 
        !          2541: @code{Allot} manages dictionary memory.  The dictionary memory contains
        !          2542: the system's data structures for words etc. on Gforth and most other
        !          2543: Forth systems.  It is managed like a stack: You can free the memory that
        !          2544: you have just @code{allot}ed with
        !          2545: 
        !          2546: @example
        !          2547: -10 cells allot
        !          2548: @end example
        !          2549: 
        !          2550: Note that you cannot do this if you have created a new word in the
        !          2551: meantime (because then your @code{allot}ed memory is no longer on the
        !          2552: top of the dictionary ``stack'').
        !          2553: 
        !          2554: Alternatively, you can use @code{allocate} and @code{free} which allow
        !          2555: freeing memory in any order:
        !          2556: 
        !          2557: @example
        !          2558: 10 cells allocate throw .s
        !          2559: 20 cells allocate throw .s
        !          2560: swap
        !          2561: free throw
        !          2562: free throw
        !          2563: @end example
        !          2564: 
        !          2565: The @code{throw}s deal with errors (e.g., out of memory).
        !          2566: 
        !          2567: And there is also a garbage collector @url{!!}, which eliminates the
        !          2568: need to @code{free} memory explicitly.
        !          2569: 
        !          2570: 
        !          2571: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
        !          2572: @section Characters and Strings
        !          2573: 
        !          2574: On the stack characters take up a cell, like numbers.  In memory they
        !          2575: have their own size (one 8-bit byte on most systems), and therefore
        !          2576: require their own words for memory access:
        !          2577: 
        !          2578: @example
        !          2579: create v4 
        !          2580:   104 c, 97 c, 108 c, 108 c, 111 c,
        !          2581: v4 4 chars + c@ .
        !          2582: @end example
        !          2583: 
        !          2584: The preferred representation of strings on the stack is @code{addr
        !          2585: u-count}, where @code{addr} is the address of the first character and
        !          2586: @code{u-count} is the number of characters in the string.
        !          2587: 
        !          2588: @example
        !          2589: v4 5 type
        !          2590: @end example
        !          2591: 
        !          2592: You get a string constant with
        !          2593: 
        !          2594: @example
        !          2595: s" hello, world" .s
        !          2596: type
        !          2597: @end example
        !          2598: 
        !          2599: Make sure you have a space between @code{s"} and the string; @code{s"}
        !          2600: is a normal Forth word and must be delimited with white space (try what
        !          2601: happens when you remove the space).
        !          2602: 
        !          2603: However, this interpretive use of @code{s"} is quite restricted: the
        !          2604: string exists only until the next call of @code{s"} (some Forth systems
        !          2605: keep more than one of these strings, but usually they still have a
        !          2606: limited lifetime.
        !          2607: 
        !          2608: @example
        !          2609: s" hello," s" world" .s
        !          2610: type
        !          2611: type
        !          2612: @end example
        !          2613: 
        !          2614: However, you can also use @code{s"} in a definition, and the resulting
        !          2615: strings then live forever (well, as long as the definition):
        !          2616: 
        !          2617: @example
        !          2618: : foo s" hello," s" world" ;
        !          2619: foo .s
        !          2620: type
        !          2621: type
        !          2622: @end example
        !          2623: 
        !          2624: @assignment
        !          2625: @code{Emit ( c -- )} types @code{c} as character (not a number).
        !          2626: Implement @code{type ( addr u -- )}.
        !          2627: @endassignment
        !          2628: 
        !          2629: @node Alignment Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Characters and Strings Tutorial, Tutorial
        !          2630: @section Alignment
        !          2631: 
        !          2632: On many processors cells have to be aligned in memory, if you want to
        !          2633: access them with @code{@@} and @code{!} (and even if the processor does
        !          2634: not require alignment, access to aligned cells are faster).
        !          2635: 
        !          2636: @code{Create} aligns @code{here} (i.e., the place where the next
        !          2637: allocation will occur, and that the @code{create}d word points to).
        !          2638: Likewise, the memory produced by @code{allocate} starts at an aligned
        !          2639: address.  Adding a number of @code{cells} to an aligned address produces
        !          2640: another aligned address.
        !          2641: 
        !          2642: However, address arithmetic involving @code{char+} and @code{chars} can
        !          2643: create an address that is not cell-aligned.  @code{Aligned ( addr --
        !          2644: a-addr )} produces the next aligned address:
        !          2645: 
        !          2646: @example
        !          2647: v3 char+ aligned .s @ .
        !          2648: v3 char+ .s @ .
        !          2649: @end example
        !          2650: 
        !          2651: Similarly, @code{align} advances @code{here} to the next aligned
        !          2652: address:
        !          2653: 
        !          2654: @example
        !          2655: create v5 97 c,
        !          2656: here .
        !          2657: align here .
        !          2658: 1000 ,
        !          2659: @end example
        !          2660: 
        !          2661: Note that you should use aligned addresses even if your processor does
        !          2662: not require them, if you want your program to be portable.
        !          2663: 
        !          2664: 
        !          2665: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Alignment Tutorial, Tutorial
        !          2666: @section Interpretation and Compilation Semantics and Immediacy
        !          2667: 
        !          2668: When a word is compiled, it behaves differently from being interpreted.
        !          2669: E.g., consider @code{+}:
        !          2670: 
        !          2671: @example
        !          2672: 1 2 + .
        !          2673: : foo + ;
        !          2674: @end example
        !          2675: 
        !          2676: These two behaviours are known as compilation and interpretation
        !          2677: semantics.  For normal words (e.g., @code{+}), the compilation semantics
        !          2678: is to append the interpretation semantics to the currently defined word
        !          2679: (@code{foo} in the example above).  I.e., when @code{foo} is executed
        !          2680: later, the interpretation semantics of @code{+} (i.e., adding two
        !          2681: numbers) will be performed.
        !          2682: 
        !          2683: However, there are words with non-default compilation semantics, e.g.,
        !          2684: the control-flow words like @code{if}.  You can use @code{immediate} to
        !          2685: change the compilation semantics of the last defined word to be equal to
        !          2686: the interpretation semantics:
        !          2687: 
        !          2688: @example
        !          2689: : [FOO] ( -- )
        !          2690:  5 . ; immediate
        !          2691: 
        !          2692: [FOO]
        !          2693: : bar ( -- )
        !          2694:   [FOO] ;
        !          2695: bar
        !          2696: see bar
        !          2697: @end example
        !          2698: 
        !          2699: Two conventions to mark words with non-default compilation semnatics are
        !          2700: names with brackets (more frequently used) and to write them all in
        !          2701: upper case (less frequently used).
        !          2702: 
        !          2703: In Gforth (and many other systems) you can also remove the
        !          2704: interpretation semantics with @code{compile-only} (the compilation
        !          2705: semantics is derived from the original interpretation semantics):
        !          2706: 
        !          2707: @example
        !          2708: : flip ( -- )
        !          2709:  6 . ; compile-only \ but not immediate
        !          2710: flip
        !          2711: 
        !          2712: : flop ( -- )
        !          2713:  flip ;
        !          2714: flop
        !          2715: @end example
        !          2716: 
        !          2717: In this example the interpretation semantics of @code{flop} is equal to
        !          2718: the original interpretation semantics of @code{flip}.
        !          2719: 
        !          2720: The text interpreter has two states: in interpret state, it performs the
        !          2721: interpretation semantics of words it encounters; in compile state, it
        !          2722: performs the compilation semantics of these words.
        !          2723: 
        !          2724: Among other things, @code{:} switches into compile state, and @code{;}
        !          2725: switches back to interpret state.  They contain the factors @code{]}
        !          2726: (switch to compile state) and @code{[} (switch to interpret state), that
        !          2727: do nothing but switch the state.
        !          2728: 
        !          2729: @example
        !          2730: : xxx ( -- )
        !          2731:   [ 5 . ]
        !          2732: ;
        !          2733: 
        !          2734: xxx
        !          2735: see xxx
        !          2736: @end example
        !          2737: 
        !          2738: These brackets are also the source of the naming convention mentioned
        !          2739: above.
        !          2740: 
        !          2741: 
        !          2742: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
        !          2743: @section Execution Tokens
        !          2744: 
        !          2745: @code{' word} gives you the execution token (XT) of a word.  The XT is a
        !          2746: cell representing the interpretation semantics of a word.  You can
        !          2747: execute this semantics with @code{execute}:
        !          2748: 
        !          2749: @example
        !          2750: ' + .s
        !          2751: 1 2 rot execute .
        !          2752: @end example
        !          2753: 
        !          2754: The XT is similar to a function pointer in C.  However, parameter
        !          2755: passing through the stack makes it a little more flexible:
        !          2756: 
        !          2757: @example
        !          2758: : map-array ( ... addr u xt -- ... )
        !          2759: \ führt xt ( ... x -- ... ) für jedes Element des Arrays aus,
        !          2760: \ das bei addr beginnt und u Elemente enthält
        !          2761:   @{ xt @}
        !          2762:   cells over + swap ?do
        !          2763:     i @ xt execute
        !          2764:   1 cells +loop ;
        !          2765: 
        !          2766: create a 3 , 4 , 2 , -1 , 4 ,
        !          2767: a 5 ' . map-array .s
        !          2768: 0 a 5 ' + map-array .
        !          2769: s" max-n" environment? drop .s
        !          2770: a 5 ' min map-array .
        !          2771: @end example
        !          2772: 
        !          2773: You can use map-array with the XTs of words that consume one element
        !          2774: more than they produce.  In theory you can also use it with other XTs,
        !          2775: but the stack effect then depends on the size of the array, which is
        !          2776: hard to understand.
        !          2777: 
        !          2778: Since arrays are cell-sized, you can store them in memory and manipulate
        !          2779: them on the stack like other cells.  You can also compile the xt into a
        !          2780: word with @code{compile,}:
        !          2781: 
        !          2782: @example
        !          2783: : foo1 ( n1 n2 -- n )
        !          2784:    [ ' + compile, ] ;
        !          2785: see foo
        !          2786: @end example
        !          2787: 
        !          2788: This is non-standard, because @code{compile,} has no compilation
        !          2789: semantics in the standard, but it works in good Forth systems.  For the
        !          2790: broken ones, use
        !          2791: 
        !          2792: @example
        !          2793: : [compile,] compile, ; immediate
        !          2794: 
        !          2795: : foo1 ( n1 n2 -- n )
        !          2796:    [ ' + ] [compile,] ;
        !          2797: see foo
        !          2798: @end example
        !          2799: 
        !          2800: @code{'} is a word with default compilation semantics; it parses the
        !          2801: next word when its interpretation semantics are executed, not during
        !          2802: compilation:
        !          2803: 
        !          2804: @example
        !          2805: : foo ( -- xt )
        !          2806:   ' ;
        !          2807: see foo
        !          2808: : bar ( ... "word" -- ... )
        !          2809:   ' execute ;
        !          2810: see bar
        !          2811: 1 2 bar +
        !          2812: @end example
        !          2813: 
        !          2814: You often want to parse a word during compilation and compile its XT so
        !          2815: it will be pushed on the stack at run-time.  @code{[']} does this:
        !          2816: 
        !          2817: @example
        !          2818: : xt-+ ( -- xt )
        !          2819:   ['] + ;
        !          2820: see xt-+
        !          2821: 1 2 xt-+ execute .
        !          2822: @end example
        !          2823: 
        !          2824: Many programmers tend to see @code{'} and the word it parses as one
        !          2825: unit, and expect it to behave like @code{[']} when compiled, and are
        !          2826: confused by the actual behaviour.  If you are, just remember that the
        !          2827: Forth system just takes @code{'} as one unit and has no idea that it is
        !          2828: a parsing word (attempts to convenience programmers in this issue have
        !          2829: usually resulted in even worse pitfalls, see
        !          2830: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz}).
        !          2831: 
        !          2832: Note that the state of the interpreter does not come into play when
        !          2833: creating and executing xts.  I.e., even when you execute @code{'} in
        !          2834: compile state, it still gives you the interpretation semantics.  And
        !          2835: whatever that state is, @code{execute} performs the semantics
        !          2836: represented by the xt (i.e., the interpretation semantics).
        !          2837: 
        !          2838: 
        !          2839: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
        !          2840: @section Exceptions
        !          2841: 
        !          2842: @code{throw ( n -- )} causes an exception unless n is zero.
        !          2843: 
        !          2844: @example
        !          2845: 100 throw .s
        !          2846: 0 throw .s
        !          2847: @end example
        !          2848: 
        !          2849: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
        !          2850: it catches exceptions and pushes the number of the exception on the
        !          2851: stack (or 0, if the xt executed without exception).  If there was an
        !          2852: exception, the stacks have the same depth as when entering @code{catch}:
        !          2853: 
        !          2854: @example
        !          2855: .s
        !          2856: 3 0 ' / catch .s
        !          2857: 3 2 ' / catch .s
        !          2858: @end example
        !          2859: 
        !          2860: @assignment
        !          2861: Try the same with @code{execute} instead of @code{catch}.
        !          2862: @endassignment
        !          2863: 
        !          2864: @code{Throw} always jumps to the dynamically next enclosing
        !          2865: @code{catch}, even if it has to leave several call levels to achieve
        !          2866: this:
        !          2867: 
        !          2868: @example
        !          2869: : foo 100 throw ;
        !          2870: : foo1 foo ." after foo" ;
        !          2871: : bar ' foo1 catch ;
        !          2872: bar
        !          2873: @end example
        !          2874: 
        !          2875: It is often important to restore a value upon leaving a definition, even
        !          2876: if the definition is left through an exception.  You can ensure this
        !          2877: like this:
        !          2878: 
        !          2879: @example
        !          2880: : ...
        !          2881:    save-x
        !          2882:    ' word-changing-x catch ( ... n )
        !          2883:    restore-x
        !          2884:    ( ... n ) throw ;
        !          2885: @end example
        !          2886: 
        !          2887: Gforth provides an alternative syntax in addition to @code{cacth}:
        !          2888: @code{try ... recover ... endtry}.  If the code between @code{try} and
        !          2889: @code{recover} has an exception, the stack depths are restored, the
        !          2890: exception number is pushed on the stack, and the code between
        !          2891: @code{recover} and @code{endtry} is performed.  E.g., the definition for
        !          2892: @code{catch} is
        !          2893: 
        !          2894: @example
        !          2895: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
        !          2896:   try
        !          2897:     execute 0
        !          2898:   recover
        !          2899:     nip
        !          2900:   endtry ;
        !          2901: @end example
        !          2902: 
        !          2903: The equivalent to the restoration code above is
        !          2904: 
        !          2905: @example
        !          2906: : ...
        !          2907:   save-x
        !          2908:   try
        !          2909:     word-changing-x
        !          2910:   end-try
        !          2911:   restore-x
        !          2912:   throw ;
        !          2913: @end example
        !          2914: 
        !          2915: As you can see, the @code{recover} part is optional.
        !          2916: 
        !          2917: 
        !          2918: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
        !          2919: @section Defining Words
        !          2920: 
        !          2921: @code{:}, @code{create}, and @code{variable} are definition words: They
        !          2922: define other words.  @code{Constant} is another definition word:
        !          2923: 
        !          2924: @example
        !          2925: 5 constant foo
        !          2926: foo .
        !          2927: @end example
        !          2928: 
        !          2929: You can also use the prefixes @code{2} (double-cell) and @code{f}
        !          2930: (floating point) with @code{variable} and @code{constant}.
        !          2931: 
        !          2932: You can also define your own defining words.  E.g.:
        !          2933: 
        !          2934: @example
        !          2935: : variable ( "name" -- )
        !          2936:   create 0 , ;
        !          2937: @end example
        !          2938: 
        !          2939: You can also define defining words that create words that do something
        !          2940: other than just producing their address:
        !          2941: 
        !          2942: @example
        !          2943: : constant ( n "name" -- )
        !          2944:   create ,
        !          2945: does> ( -- n )
        !          2946:   ( addr ) @ ;
        !          2947: 
        !          2948: 5 constant foo
        !          2949: foo .
        !          2950: @end example
        !          2951: 
        !          2952: The definition of @code{constant} above ends at the @code{does>}; i.e.,
        !          2953: @code{does>} replaces @code{;}, but it also does something else: It
        !          2954: changes the last defined word such that it pushes the address of the
        !          2955: body of the word and then performs the code after the @code{does>}
        !          2956: whenever it is called.
        !          2957: 
        !          2958: In the example above, @code{constant} uses @code{,} to store 5 into the
        !          2959: body of @code{foo}.  When @code{foo} executes, it pushes the address of
        !          2960: the body onto the stack, then (in the code after the @code{does>})
        !          2961: fetches the 5 from there.
        !          2962: 
        !          2963: The stack comment near the @code{does>} reflects the stack effect of the
        !          2964: defined word, not the stack effect of the code after the @code{does>}
        !          2965: (the difference is that the code expects the address of the body that
        !          2966: the stack comment does not show).
        !          2967: 
        !          2968: You can use these definition words to do factoring in cases that involve
        !          2969: (other) definition words.  E.g., a field offset is always added to an
        !          2970: address.  Instead of defining
        !          2971: 
        !          2972: @example
        !          2973: 2 cells constant offset-field1
        !          2974: @end example
        !          2975: 
        !          2976: and using this like
        !          2977: 
        !          2978: @example
        !          2979: ( addr ) offset-field1 +
        !          2980: @end example
        !          2981: 
        !          2982: you can define a definition word
        !          2983: 
        !          2984: @example
        !          2985: : simple-field ( n "name" -- )
        !          2986:   create ,
        !          2987: does> ( n1 -- n1+n )
        !          2988:   ( addr ) @ + ;
        !          2989: @end example
1.21      crook    2990: 
1.48    ! anton    2991: Definition and use of field offsets now look like this:
1.21      crook    2992: 
1.48    ! anton    2993: @example
        !          2994: 2 cells simple-field field1
        !          2995: ( addr ) field1
        !          2996: @end example
1.21      crook    2997: 
1.48    ! anton    2998: If you want to do something with the word without performing the code
        !          2999: after the @code{does>}, you can access the body of a @code{create}d word
        !          3000: with @code{>body ( xt -- addr )}:
1.21      crook    3001: 
1.48    ! anton    3002: @example
        !          3003: : value ( n "name" -- )
        !          3004:   create ,
        !          3005: does> ( -- n1 )
        !          3006:   @ ;
        !          3007: : to ( n "name" -- )
        !          3008:   ' >body ! ;
1.21      crook    3009: 
1.48    ! anton    3010: 5 value foo
        !          3011: foo .
        !          3012: 7 to foo
        !          3013: foo .
        !          3014: @end example
1.21      crook    3015: 
1.48    ! anton    3016: @assignment
        !          3017: Define @code{defer ( "name" -- )}, which creates a word that stores an
        !          3018: XT (at the start the XT of @code{abort}), and upon execution
        !          3019: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
        !          3020: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
        !          3021: recursion is one application of @code{defer}.
        !          3022: @endassignment
1.29      crook    3023: 
1.48    ! anton    3024: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
        !          3025: @section Arrays and Records
1.29      crook    3026: 
1.48    ! anton    3027: Forth has no standard words for defining data structures such as arrays
        !          3028: and records (structs in C terminology), but you can build them yourself
        !          3029: based on address arithmetic.  You can also define words for defining
        !          3030: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29      crook    3031: 
1.48    ! anton    3032: One of the first projects a Forth newcomer sets out upon when learning
        !          3033: about defining words is an array defining word (possibly for
        !          3034: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
        !          3035: learn something from it.  However, don't be disappointed when you later
        !          3036: learn that you have little use for these words (inappropriate use would
        !          3037: be even worse).  I have not yet found a set of useful array words yet;
        !          3038: the needs are just too diverse, and named, global arrays (the result of
        !          3039: naive use of defining words) are often not flexible enough (e.g.,
        !          3040: consider how to pass them as parameters).
1.29      crook    3041: 
1.48    ! anton    3042: On the other hand, there is a useful set of record words, and it has
        !          3043: been defined in @file{compat/struct.fs}; these words are predefined in
        !          3044: Gforth.  They are explained in depth elsewhere in this manual (see
        !          3045: @pxref{Structures}).  The @code{simple-field} example above is
        !          3046: simplified variant of fields in this package.
1.21      crook    3047: 
                   3048: 
1.48    ! anton    3049: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
        !          3050: @section @code{POSTPONE}
1.21      crook    3051: 
1.48    ! anton    3052: You can compile the compilation semantics (instead of compiling the
        !          3053: interpretation semantics) of a word with @code{POSTPONE}:
1.21      crook    3054: 
1.48    ! anton    3055: @example
        !          3056: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
        !          3057:  POSTPONE + ; immediate compile-only
        !          3058: : foo ( n1 n2 -- n )
        !          3059:  MY-+ ;
        !          3060: 1 2 foo .
        !          3061: see foo
        !          3062: @end example
1.21      crook    3063: 
1.48    ! anton    3064: During the definition of @code{foo} the text interpreter performs the
        !          3065: compilation semantics of @code{MY-+}, which performs the compilation
        !          3066: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
        !          3067: 
        !          3068: This example also displays separate stack comments for the compilation
        !          3069: semantics and for the stack effect of the compiled code.  For words with
        !          3070: default compilation semantics these stack effects are usually not
        !          3071: displayed; the stack effect of the compilation semantics is always
        !          3072: @code{( -- )} for these words, the stack effect for the compiled code is
        !          3073: the stack effect of the interpretation semantics.
        !          3074: 
        !          3075: Note that the state of the interpreter does not come into play when
        !          3076: performing the compilation semantics in this way.  You can also perform
        !          3077: it interpretively, e.g.:
        !          3078: 
        !          3079: @example
        !          3080: : foo2 ( n1 n2 -- n )
        !          3081:  [ MY-+ ] ;
        !          3082: 1 2 foo .
        !          3083: see foo
        !          3084: @end example
1.21      crook    3085: 
1.48    ! anton    3086: However, there are some broken Forth systems where this does not always
        !          3087: work, and therefore this practice has been declared non-standard in
        !          3088: 1999.
        !          3089: @c !! repair.fs
        !          3090: 
        !          3091: Here is another example for using @code{POSTPONE}:
1.44      crook    3092: 
1.48    ! anton    3093: @example
        !          3094: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
        !          3095:  POSTPONE negate POSTPONE + ; immediate compile-only
        !          3096: : bar ( n1 n2 -- n )
        !          3097:   MY-- ;
        !          3098: 2 1 bar .
        !          3099: see bar
        !          3100: @end example
1.21      crook    3101: 
1.48    ! anton    3102: You can define @code{ENDIF} in this way:
1.21      crook    3103: 
1.48    ! anton    3104: @example
        !          3105: : ENDIF ( Compilation: orig -- )
        !          3106:   POSTPONE then ; immediate
        !          3107: @end example
1.21      crook    3108: 
1.48    ! anton    3109: @assignment
        !          3110: Write @code{MY-2DUP} that has compilation semantics equivalent to
        !          3111: @code{2dup}, but compiles @code{over over}.
        !          3112: @endassignment
1.29      crook    3113: 
1.48    ! anton    3114: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
        !          3115: @section @code{Literal}
1.29      crook    3116: 
1.48    ! anton    3117: You cannot @code{POSTPONE} numbers:
1.21      crook    3118: 
1.48    ! anton    3119: @example
        !          3120: : [FOO] POSTPONE 500 ; immediate
1.21      crook    3121: @end example
                   3122: 
1.48    ! anton    3123: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29      crook    3124: 
1.48    ! anton    3125: @example
        !          3126: : [FOO] ( compilation: --; run-time: -- n )
        !          3127:   500 POSTPONE literal ; immediate
1.29      crook    3128: 
1.48    ! anton    3129: : flip foo ;
        !          3130: flip .
        !          3131: see flip
        !          3132: @end example
1.29      crook    3133: 
1.48    ! anton    3134: @code{LITERAL} consumes a number at compile-time (when it's compilation
        !          3135: semantics are executed) and pushes it at run-time (when the code it
        !          3136: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
        !          3137: number computed at compile time into the current word:
1.29      crook    3138: 
1.48    ! anton    3139: @example
        !          3140: : bar ( -- n )
        !          3141:   [ 2 2 + ] literal ;
        !          3142: see bar
        !          3143: @end example
1.29      crook    3144: 
1.48    ! anton    3145: @assignment
        !          3146: Write @code{]L} which allows writing the example above as @code{: bar (
        !          3147: -- n ) [ 2 2 + ]L ;}
        !          3148: @endassignment
        !          3149: 
        !          3150: 
        !          3151: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
        !          3152: @section Advanced macros
        !          3153: 
        !          3154: Reconsider @code{map-array} from @ref{Execution Tokens
        !          3155: Tutorial,, Execution Tokens}.  It frequently performs @code{execute}, a
        !          3156: relatively expensive operation in some implementations.  You can use
        !          3157: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
        !          3158: and produce a word that contains the word to be performed directly:
        !          3159: 
        !          3160: @c use ]] ... [[
        !          3161: @example
        !          3162: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
        !          3163: \ at run-time, execute xt ( ... x -- ... ) for each element of the
        !          3164: \ array beginning at addr and containing u elements
        !          3165:   @{ xt @}
        !          3166:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
        !          3167:     POSTPONE i POSTPONE @ xt compile,
        !          3168:   1 cells POSTPONE literal POSTPONE +loop ;
        !          3169: 
        !          3170: : sum-array ( addr u -- n )
        !          3171:  0 rot rot [ ' + compile-map-array ] ;
        !          3172: see sum-array
        !          3173: a 5 sum-array .
        !          3174: @end example
        !          3175: 
        !          3176: You can use the full power of Forth for generating the code; here's an
        !          3177: example where the code is generated in a loop:
        !          3178: 
        !          3179: @example
        !          3180: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
        !          3181: \ n2=n1+(addr1)*n, addr2=addr1+cell
        !          3182:   POSTPONE tuck POSTPONE @
        !          3183:   POSTPONE literal POSTPONE * POSTPONE +
        !          3184:   POSTPONE swap POSTPONE cell+ ;
        !          3185: 
        !          3186: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
        !          3187: \ n=v1*v2 (inneres Produkt), wobei die v_i als addr_i u repräsentiert sind
        !          3188:   0 postpone literal postpone swap
        !          3189:   [ ' compile-vmul-step compile-map-array ]
        !          3190:   postpone drop ;
        !          3191: see compile-vmul
        !          3192: 
        !          3193: : a-vmul ( addr -- n )
        !          3194: \ n=a*v, wobei v ein Vektor ist, der so lang ist wie a und bei addr anfängt
        !          3195:  [ a 5 compile-vmul ] ;
        !          3196: see a-vmul
        !          3197: a a-vmul .
        !          3198: @end example
        !          3199: 
        !          3200: This example uses @code{compile-map-array} to show off, but you could
        !          3201: also use @code{map-array} instead (try it now).
        !          3202: 
        !          3203: You can use this technique for efficient multiplication of large
        !          3204: matrices.  In matrix multiplication, you multiply every line of one
        !          3205: matrix with every column of the other matrix.  You can generate the code
        !          3206: for one line once, and use it for every column.  The only downside of
        !          3207: this technique is that it is cumbersome to recover the memory consumed
        !          3208: by the generated code when you are done (and in more complicated cases
        !          3209: it is not possible portably).
        !          3210: 
        !          3211: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
        !          3212: @section Compilation Tokens
        !          3213: 
        !          3214: This section is Gforth-specific.  You can skip it.
        !          3215: 
        !          3216: @code{' word compile,} compiles the interpretation semantics.  For words
        !          3217: with default compilation semantics this is the same as performing the
        !          3218: compilation semantics.  To represent the compilation semantics of other
        !          3219: words (e.g., words like @code{if} that have no interpretation
        !          3220: semantics), Gforth has the concept of a compilation token (CT,
        !          3221: consisting of two cells), and words @code{comp'} and @code{[comp']}.
        !          3222: You can perform the compilation semantics represented by a CT with
        !          3223: @code{execute}:
1.29      crook    3224: 
1.48    ! anton    3225: @example
        !          3226: : foo2 ( n1 n2 -- n )
        !          3227:    [ comp' + execute ] ;
        !          3228: see foo
        !          3229: @end example
1.29      crook    3230: 
1.48    ! anton    3231: You can compile the compilation semantics represented by a CT with
        !          3232: @code{postpone,}:
1.30      anton    3233: 
1.48    ! anton    3234: @example
        !          3235: : foo3 ( -- )
        !          3236:   [ comp' + postpone, ] ;
        !          3237: see foo3
        !          3238: @end example
1.30      anton    3239: 
1.48    ! anton    3240: @code{[ comp' wort postpone, ]} is equivalent to @code{POSTPONE word}.
        !          3241: @code{comp'} is particularly useful for words that have no
        !          3242: interpretation semantics:
1.29      crook    3243: 
1.30      anton    3244: @example
1.48    ! anton    3245: ' if
        !          3246: comp' if .s
1.30      anton    3247: @end example
                   3248: 
1.29      crook    3249: 
1.48    ! anton    3250: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
        !          3251: @section Wordlists and Search Order
        !          3252: 
        !          3253: The dictionary is not just a memory area that allows you to allocate
        !          3254: memory with @code{allot}, it also contains the Forth words, arranged in
        !          3255: several wordlists.  When searching for a word in a wordlist,
        !          3256: conceptually you start searching at the youngest and proceed towards
        !          3257: older words (in reality most systems nowadays use hash-tables); i.e., if
        !          3258: you define a word with the same name as an older word, the new word
        !          3259: shadows the older word.
        !          3260: 
        !          3261: Which wordlists are searched in which order is determined by the search
        !          3262: order.  You can display the search order with @code{order}.  It displays
        !          3263: first the search order, starting with the wordlist searched first, then
        !          3264: it displays the wordlist that will contain newly defined words.
1.21      crook    3265: 
1.48    ! anton    3266: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21      crook    3267: 
1.48    ! anton    3268: @example
        !          3269: wordlist constant mywords
        !          3270: @end example
1.21      crook    3271: 
1.48    ! anton    3272: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
        !          3273: defined words (the @emph{current} wordlist):
1.21      crook    3274: 
1.48    ! anton    3275: @example
        !          3276: mywords set-current
        !          3277: order
        !          3278: @end example
1.26      crook    3279: 
1.48    ! anton    3280: Gforth does not display a name for the wordlist in @code{mywords}
        !          3281: because this wordlist was created anonymously with @code{wordlist}.
1.21      crook    3282: 
1.48    ! anton    3283: You can get the current wordlist with @code{get-current ( -- wid)}.  If
        !          3284: you want to put something into a specific wordlist without overall
        !          3285: effect on the current wordlist, this typically looks like this:
1.21      crook    3286: 
1.48    ! anton    3287: @example
        !          3288: get-current mywords set-current ( wid )
        !          3289: create someword
        !          3290: ( wid ) set-current
        !          3291: @end example
1.21      crook    3292: 
1.48    ! anton    3293: You can write the search order with @code{set-order ( wid1 .. widn n --
        !          3294: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
        !          3295: searched wordlist is topmost.
1.21      crook    3296: 
1.48    ! anton    3297: @example
        !          3298: get-order mywords swap 1+ set-order
        !          3299: order
        !          3300: @end example
1.21      crook    3301: 
1.48    ! anton    3302: Yes, the order of wordlists in the output of @code{order} is reversed
        !          3303: from stack comments and the output of @code{.s} and thus unintuitive.
1.21      crook    3304: 
1.48    ! anton    3305: @assignment
        !          3306: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
        !          3307: wordlist to the search order.  Define @code{previous ( -- )}, which
        !          3308: removes the first searched wordlist from the search order.  Experiment
        !          3309: with boundary conditions (you will see some crashes or situations that
        !          3310: are hard or impossible to leave).
        !          3311: @endassignment
1.21      crook    3312: 
1.48    ! anton    3313: The search order is a powerful foundation for providing features similar
        !          3314: to Modula-2 modules and C++ namespaces.  However, trying to modularize
        !          3315: programs in this way has disadvantages for debugging and reuse/factoring
        !          3316: that overcome the advantages in my experience (I don't do huge projects,
        !          3317: though).  These disadvanategs are not so clear in other
        !          3318: languages/programming environments, because these langauges are not so
        !          3319: strong in debugging and reuse.
1.21      crook    3320: 
                   3321: 
1.29      crook    3322: @c ******************************************************************
1.48    ! anton    3323: @node Introduction, Words, Tutorial, Top
1.29      crook    3324: @comment node-name,     next,           previous, up
                   3325: @chapter An Introduction to ANS Forth
                   3326: @cindex Forth - an introduction
1.21      crook    3327: 
1.29      crook    3328: The primary purpose of this manual is to document Gforth. However, since
                   3329: Forth is not a widely-known language and there is a lack of up-to-date
                   3330: teaching material, it seems worthwhile to provide some introductory
                   3331: material. @xref{Forth-related information} for other sources of Forth-related
                   3332: information.
1.21      crook    3333: 
1.29      crook    3334: The examples in this section should work on any ANS Forth; the
                   3335: output shown was produced using Gforth. Each example attempts to
                   3336: reproduce the exact output that Gforth produces. If you try out the
                   3337: examples (and you should), what you should type is shown @kbd{like this}
                   3338: and Gforth's response is shown @code{like this}. The single exception is
1.30      anton    3339: that, where the example shows @key{RET} it means that you should
1.29      crook    3340: press the ``carriage return'' key. Unfortunately, some output formats for
                   3341: this manual cannot show the difference between @kbd{this} and
                   3342: @code{this} which will make trying out the examples harder (but not
                   3343: impossible).
1.21      crook    3344: 
1.29      crook    3345: Forth is an unusual language. It provides an interactive development
                   3346: environment which includes both an interpreter and compiler. Forth
                   3347: programming style encourages you to break a problem down into many
                   3348: @cindex factoring
                   3349: small fragments (@dfn{factoring}), and then to develop and test each
                   3350: fragment interactively. Forth advocates assert that breaking the
                   3351: edit-compile-test cycle used by conventional programming languages can
                   3352: lead to great productivity improvements.
1.21      crook    3353: 
1.29      crook    3354: @menu
                   3355: * Introducing the Text Interpreter::
                   3356: * Stacks and Postfix notation::
                   3357: * Your first definition::
                   3358: * How does that work?::
                   3359: * Forth is written in Forth::
                   3360: * Review - elements of a Forth system::
                   3361: * Where to go next::
                   3362: * Exercises::
                   3363: @end menu
1.21      crook    3364: 
1.29      crook    3365: @comment ----------------------------------------------
                   3366: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
                   3367: @section Introducing the Text Interpreter
                   3368: @cindex text interpreter
                   3369: @cindex outer interpreter
1.21      crook    3370: 
1.30      anton    3371: @c IMO this is too detailed and the pace is too slow for
                   3372: @c an introduction.  If you know German, take a look at
                   3373: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
                   3374: @c to see how I do it - anton 
                   3375: 
1.44      crook    3376: @c nac-> Where I have accepted your comments 100% and modified the text
                   3377: @c accordingly, I have deleted your comments. Elsewhere I have added a
                   3378: @c response like this to attempt to rationalise what I have done. Of
                   3379: @c course, this is a very clumsy mechanism for something that would be
                   3380: @c done far more efficiently over a beer. Please delete any dialogue
                   3381: @c you consider closed.
                   3382: 
1.29      crook    3383: When you invoke the Forth image, you will see a startup banner printed
                   3384: and nothing else (if you have Gforth installed on your system, try
1.30      anton    3385: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29      crook    3386: its command line interpreter, which is called the @dfn{Text Interpreter}
                   3387: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
1.30      anton    3388: about the text interpreter as you read through this chapter, but
                   3389: @pxref{The Text Interpreter} for more detail).
1.21      crook    3390: 
1.29      crook    3391: Although it's not obvious, Forth is actually waiting for your
1.30      anton    3392: input. Type a number and press the @key{RET} key:
1.21      crook    3393: 
1.26      crook    3394: @example
1.30      anton    3395: @kbd{45@key{RET}}  ok
1.26      crook    3396: @end example
1.21      crook    3397: 
1.29      crook    3398: Rather than give you a prompt to invite you to input something, the text
                   3399: interpreter prints a status message @i{after} it has processed a line
                   3400: of input. The status message in this case (``@code{ ok}'' followed by
                   3401: carriage-return) indicates that the text interpreter was able to process
                   3402: all of your input successfully. Now type something illegal:
                   3403: 
                   3404: @example
1.30      anton    3405: @kbd{qwer341@key{RET}}
1.29      crook    3406: :1: Undefined word
                   3407: qwer341
                   3408: ^^^^^^^
                   3409: $400D2BA8 Bounce
                   3410: $400DBDA8 no.extensions
                   3411: @end example
1.23      crook    3412: 
1.29      crook    3413: The exact text, other than the ``Undefined word'' may differ slightly on
                   3414: your system, but the effect is the same; when the text interpreter
                   3415: detects an error, it discards any remaining text on a line, resets
1.30      anton    3416: certain internal state and prints an error message. @xref{Error
                   3417: messages} for a detailed description of error messages.
1.23      crook    3418: 
1.29      crook    3419: The text interpreter waits for you to press carriage-return, and then
                   3420: processes your input line. Starting at the beginning of the line, it
                   3421: breaks the line into groups of characters separated by spaces. For each
                   3422: group of characters in turn, it makes two attempts to do something:
1.23      crook    3423: 
1.29      crook    3424: @itemize @bullet
                   3425: @item
1.44      crook    3426: @cindex name dictionary
1.29      crook    3427: It tries to treat it as a command. It does this by searching a @dfn{name
                   3428: dictionary}. If the group of characters matches an entry in the name
                   3429: dictionary, the name dictionary provides the text interpreter with
                   3430: information that allows the text interpreter perform some actions. In
                   3431: Forth jargon, we say that the group
                   3432: @cindex word
                   3433: @cindex definition
                   3434: @cindex execution token
                   3435: @cindex xt
                   3436: of characters names a @dfn{word}, that the dictionary search returns an
                   3437: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
                   3438: word, and that the text interpreter executes the xt. Often, the terms
                   3439: @dfn{word} and @dfn{definition} are used interchangeably.
                   3440: @item
                   3441: If the text interpreter fails to find a match in the name dictionary, it
                   3442: tries to treat the group of characters as a number in the current number
                   3443: base (when you start up Forth, the current number base is base 10). If
                   3444: the group of characters legitimately represents a number, the text
                   3445: interpreter pushes the number onto a stack (we'll learn more about that
                   3446: in the next section).
                   3447: @end itemize
1.23      crook    3448: 
1.29      crook    3449: If the text interpreter is unable to do either of these things with any
                   3450: group of characters, it discards the group of characters and the rest of
                   3451: the line, then prints an error message. If the text interpreter reaches
                   3452: the end of the line without error, it prints the status message ``@code{ ok}''
                   3453: followed by carriage-return.
1.21      crook    3454: 
1.29      crook    3455: This is the simplest command we can give to the text interpreter:
1.23      crook    3456: 
                   3457: @example
1.30      anton    3458: @key{RET}  ok
1.23      crook    3459: @end example
1.21      crook    3460: 
1.29      crook    3461: The text interpreter did everything we asked it to do (nothing) without
                   3462: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
                   3463: command:
1.21      crook    3464: 
1.23      crook    3465: @example
1.30      anton    3466: @kbd{12 dup fred dup@key{RET}}
1.29      crook    3467: :1: Undefined word
                   3468: 12 dup fred dup
                   3469:        ^^^^
                   3470: $400D2BA8 Bounce
                   3471: $400DBDA8 no.extensions
1.23      crook    3472: @end example
1.21      crook    3473: 
1.29      crook    3474: When you press the carriage-return key, the text interpreter starts to
                   3475: work its way along the line:
1.21      crook    3476: 
1.29      crook    3477: @itemize @bullet
                   3478: @item
                   3479: When it gets to the space after the @code{2}, it takes the group of
                   3480: characters @code{12} and looks them up in the name
                   3481: dictionary@footnote{We can't tell if it found them or not, but assume
                   3482: for now that it did not}. There is no match for this group of characters
                   3483: in the name dictionary, so it tries to treat them as a number. It is
                   3484: able to do this successfully, so it puts the number, 12, ``on the stack''
                   3485: (whatever that means).
                   3486: @item
                   3487: The text interpreter resumes scanning the line and gets the next group
                   3488: of characters, @code{dup}. It looks it up in the name dictionary and
                   3489: (you'll have to take my word for this) finds it, and executes the word
                   3490: @code{dup} (whatever that means).
                   3491: @item
                   3492: Once again, the text interpreter resumes scanning the line and gets the
                   3493: group of characters @code{fred}. It looks them up in the name
                   3494: dictionary, but can't find them. It tries to treat them as a number, but
                   3495: they don't represent any legal number.
                   3496: @end itemize
1.21      crook    3497: 
1.29      crook    3498: At this point, the text interpreter gives up and prints an error
                   3499: message. The error message shows exactly how far the text interpreter
                   3500: got in processing the line. In particular, it shows that the text
                   3501: interpreter made no attempt to do anything with the final character
                   3502: group, @code{dup}, even though we have good reason to believe that the
                   3503: text interpreter would have no problem looking that word up and
                   3504: executing it a second time.
1.21      crook    3505: 
                   3506: 
1.29      crook    3507: @comment ----------------------------------------------
                   3508: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
                   3509: @section Stacks, postfix notation and parameter passing
                   3510: @cindex text interpreter
                   3511: @cindex outer interpreter
1.21      crook    3512: 
1.29      crook    3513: In procedural programming languages (like C and Pascal), the
                   3514: building-block of programs is the @dfn{function} or @dfn{procedure}. These
                   3515: functions or procedures are called with @dfn{explicit parameters}. For
                   3516: example, in C we might write:
1.21      crook    3517: 
1.23      crook    3518: @example
1.29      crook    3519: total = total + new_volume(length,height,depth);
1.23      crook    3520: @end example
1.21      crook    3521: 
1.23      crook    3522: @noindent
1.29      crook    3523: where new_volume is a function-call to another piece of code, and total,
                   3524: length, height and depth are all variables. length, height and depth are
                   3525: parameters to the function-call.
1.21      crook    3526: 
1.29      crook    3527: In Forth, the equivalent of the function or procedure is the
                   3528: @dfn{definition} and parameters are implicitly passed between
                   3529: definitions using a shared stack that is visible to the
                   3530: programmer. Although Forth does support variables, the existence of the
                   3531: stack means that they are used far less often than in most other
                   3532: programming languages. When the text interpreter encounters a number, it
                   3533: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30      anton    3534: actual number is implementation-dependent ...) and the particular stack
1.29      crook    3535: used for any operation is implied unambiguously by the operation being
                   3536: performed. The stack used for all integer operations is called the @dfn{data
                   3537: stack} and, since this is the stack used most commonly, references to
                   3538: ``the data stack'' are often abbreviated to ``the stack''.
1.21      crook    3539: 
1.29      crook    3540: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21      crook    3541: 
1.23      crook    3542: @example
1.30      anton    3543: @kbd{1 2 3@key{RET}}  ok
1.23      crook    3544: @end example
1.21      crook    3545: 
1.29      crook    3546: Then this instructs the text interpreter to placed three numbers on the
                   3547: (data) stack. An analogy for the behaviour of the stack is to take a
                   3548: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
                   3549: the table. The 3 was the last card onto the pile (``last-in'') and if
                   3550: you take a card off the pile then, unless you're prepared to fiddle a
                   3551: bit, the card that you take off will be the 3 (``first-out''). The
                   3552: number that will be first-out of the stack is called the @dfn{top of
                   3553: stack}, which
                   3554: @cindex TOS definition
                   3555: is often abbreviated to @dfn{TOS}.
1.21      crook    3556: 
1.29      crook    3557: To understand how parameters are passed in Forth, consider the
                   3558: behaviour of the definition @code{+} (pronounced ``plus''). You will not
                   3559: be surprised to learn that this definition performs addition. More
                   3560: precisely, it adds two number together and produces a result. Where does
                   3561: it get the two numbers from? It takes the top two numbers off the
                   3562: stack. Where does it place the result? On the stack. You can act-out the
                   3563: behaviour of @code{+} with your playing cards like this:
1.21      crook    3564: 
                   3565: @itemize @bullet
                   3566: @item
1.29      crook    3567: Pick up two cards from the stack on the table
1.21      crook    3568: @item
1.29      crook    3569: Stare at them intently and ask yourself ``what @i{is} the sum of these two
                   3570: numbers''
1.21      crook    3571: @item
1.29      crook    3572: Decide that the answer is 5
1.21      crook    3573: @item
1.29      crook    3574: Shuffle the two cards back into the pack and find a 5
1.21      crook    3575: @item
1.29      crook    3576: Put a 5 on the remaining ace that's on the table.
1.21      crook    3577: @end itemize
                   3578: 
1.29      crook    3579: If you don't have a pack of cards handy but you do have Forth running,
                   3580: you can use the definition @code{.s} to show the current state of the stack,
                   3581: without affecting the stack. Type:
1.21      crook    3582: 
                   3583: @example
1.30      anton    3584: @kbd{clearstack 1 2 3@key{RET}} ok
                   3585: @kbd{.s@key{RET}} <3> 1 2 3  ok
1.23      crook    3586: @end example
                   3587: 
1.29      crook    3588: The text interpreter looks up the word @code{clearstack} and executes
                   3589: it; it tidies up the stack and removes any entries that may have been
                   3590: left on it by earlier examples. The text interpreter pushes each of the
                   3591: three numbers in turn onto the stack. Finally, the text interpreter
                   3592: looks up the word @code{.s} and executes it. The effect of executing
                   3593: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
                   3594: followed by a list of all the items on the stack; the item on the far
                   3595: right-hand side is the TOS.
1.21      crook    3596: 
1.29      crook    3597: You can now type:
1.21      crook    3598: 
1.29      crook    3599: @example
1.30      anton    3600: @kbd{+ .s@key{RET}} <2> 1 5  ok
1.29      crook    3601: @end example
1.21      crook    3602: 
1.29      crook    3603: @noindent
                   3604: which is correct; there are now 2 items on the stack and the result of
                   3605: the addition is 5.
1.23      crook    3606: 
1.29      crook    3607: If you're playing with cards, try doing a second addition: pick up the
                   3608: two cards, work out that their sum is 6, shuffle them into the pack,
                   3609: look for a 6 and place that on the table. You now have just one item on
                   3610: the stack. What happens if you try to do a third addition? Pick up the
                   3611: first card, pick up the second card -- ah! There is no second card. This
                   3612: is called a @dfn{stack underflow} and consitutes an error. If you try to
                   3613: do the same thing with Forth it will report an error (probably a Stack
                   3614: Underflow or an Invalid Memory Address error).
1.23      crook    3615: 
1.29      crook    3616: The opposite situation to a stack underflow is a @dfn{stack overflow},
                   3617: which simply accepts that there is a finite amount of storage space
                   3618: reserved for the stack. To stretch the playing card analogy, if you had
                   3619: enough packs of cards and you piled the cards up on the table, you would
                   3620: eventually be unable to add another card; you'd hit the ceiling. Gforth
                   3621: allows you to set the maximum size of the stacks. In general, the only
                   3622: time that you will get a stack overflow is because a definition has a
                   3623: bug in it and is generating data on the stack uncontrollably.
1.23      crook    3624: 
1.29      crook    3625: There's one final use for the playing card analogy. If you model your
                   3626: stack using a pack of playing cards, the maximum number of items on
                   3627: your stack will be 52 (I assume you didn't use the Joker). The maximum
                   3628: @i{value} of any item on the stack is 13 (the King). In fact, the only
                   3629: possible numbers are positive integer numbers 1 through 13; you can't
                   3630: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
                   3631: think about some of the cards, you can accommodate different
                   3632: numbers. For example, you could think of the Jack as representing 0,
                   3633: the Queen as representing -1 and the King as representing -2. Your
1.45      crook    3634: @i{range} remains unchanged (you can still only represent a total of 13
1.29      crook    3635: numbers) but the numbers that you can represent are -2 through 10.
1.28      crook    3636: 
1.29      crook    3637: In that analogy, the limit was the amount of information that a single
                   3638: stack entry could hold, and Forth has a similar limit. In Forth, the
                   3639: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
                   3640: implementation dependent and affects the maximum value that a stack
                   3641: entry can hold. A Standard Forth provides a cell size of at least
                   3642: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21      crook    3643: 
1.29      crook    3644: Forth does not do any type checking for you, so you are free to
                   3645: manipulate and combine stack items in any way you wish. A convenient way
                   3646: of treating stack items is as 2's complement signed integers, and that
                   3647: is what Standard words like @code{+} do. Therefore you can type:
1.21      crook    3648: 
1.29      crook    3649: @example
1.30      anton    3650: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
1.29      crook    3651: @end example
1.21      crook    3652: 
1.29      crook    3653: If you use numbers and definitions like @code{+} in order to turn Forth
                   3654: into a great big pocket calculator, you will realise that it's rather
                   3655: different from a normal calculator. Rather than typing 2 + 3 = you had
                   3656: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
                   3657: result). The terminology used to describe this difference is to say that
                   3658: your calculator uses @dfn{Infix Notation} (parameters and operators are
                   3659: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
                   3660: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21      crook    3661: 
1.29      crook    3662: Whilst postfix notation might look confusing to begin with, it has
                   3663: several important advantages:
1.21      crook    3664: 
1.23      crook    3665: @itemize @bullet
                   3666: @item
1.29      crook    3667: it is unambiguous
1.23      crook    3668: @item
1.29      crook    3669: it is more concise
1.23      crook    3670: @item
1.29      crook    3671: it fits naturally with a stack-based system
1.23      crook    3672: @end itemize
1.21      crook    3673: 
1.29      crook    3674: To examine these claims in more detail, consider these sums:
1.21      crook    3675: 
1.29      crook    3676: @example
                   3677: 6 + 5 * 4 =
                   3678: 4 * 5 + 6 =
                   3679: @end example
1.21      crook    3680: 
1.29      crook    3681: If you're just learning maths or your maths is very rusty, you will
                   3682: probably come up with the answer 44 for the first and 26 for the
                   3683: second. If you are a bit of a whizz at maths you will remember the
                   3684: @i{convention} that multiplication takes precendence over addition, and
                   3685: you'd come up with the answer 26 both times. To explain the answer 26
                   3686: to someone who got the answer 44, you'd probably rewrite the first sum
                   3687: like this:
1.21      crook    3688: 
1.29      crook    3689: @example
                   3690: 6 + (5 * 4) =
                   3691: @end example
1.21      crook    3692: 
1.29      crook    3693: If what you really wanted was to perform the addition before the
                   3694: multiplication, you would have to use parentheses to force it.
1.21      crook    3695: 
1.29      crook    3696: If you did the first two sums on a pocket calculator you would probably
                   3697: get the right answers, unless you were very cautious and entered them using
                   3698: these keystroke sequences:
1.21      crook    3699: 
1.29      crook    3700: 6 + 5 = * 4 =
                   3701: 4 * 5 = + 6 =
1.21      crook    3702: 
1.29      crook    3703: Postfix notation is unambiguous because the order that the operators
                   3704: are applied is always explicit; that also means that parentheses are
                   3705: never required. The operators are @i{active} (the act of quoting the
                   3706: operator makes the operation occur) which removes the need for ``=''.
1.28      crook    3707: 
1.29      crook    3708: The sum 6 + 5 * 4 can be written (in postfix notation) in two
                   3709: equivalent ways:
1.26      crook    3710: 
                   3711: @example
1.29      crook    3712: 6 5 4 * +      or:
                   3713: 5 4 * 6 +
1.26      crook    3714: @end example
1.23      crook    3715: 
1.29      crook    3716: An important thing that you should notice about this notation is that
                   3717: the @i{order} of the numbers does not change; if you want to subtract
                   3718: 2 from 10 you type @code{10 2 -}.
1.1       anton    3719: 
1.29      crook    3720: The reason that Forth uses postfix notation is very simple to explain: it
                   3721: makes the implementation extremely simple, and it follows naturally from
                   3722: using the stack as a mechanism for passing parameters. Another way of
                   3723: thinking about this is to realise that all Forth definitions are
                   3724: @i{active}; they execute as they are encountered by the text
                   3725: interpreter. The result of this is that the syntax of Forth is trivially
                   3726: simple.
1.1       anton    3727: 
                   3728: 
                   3729: 
1.29      crook    3730: @comment ----------------------------------------------
                   3731: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
                   3732: @section Your first Forth definition
                   3733: @cindex first definition
1.1       anton    3734: 
1.29      crook    3735: Until now, the examples we've seen have been trivial; we've just been
                   3736: using Forth as a bigger-than-pocket calculator. Also, each calculation
                   3737: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
                   3738: again@footnote{That's not quite true. If you press the up-arrow key on
                   3739: your keyboard you should be able to scroll back to any earlier command,
                   3740: edit it and re-enter it.} In this section we'll see how to add new
                   3741: words to Forth's vocabulary.
1.1       anton    3742: 
1.29      crook    3743: The easiest way to create a new word is to use a @dfn{colon
                   3744: definition}. We'll define a few and try them out before worrying too
                   3745: much about how they work. Try typing in these examples; be careful to
                   3746: copy the spaces accurately:
1.1       anton    3747: 
1.29      crook    3748: @example
                   3749: : add-two 2 + . ;
                   3750: : greet ." Hello and welcome" ;
                   3751: : demo 5 add-two ;
                   3752: @end example
1.1       anton    3753: 
1.29      crook    3754: @noindent
                   3755: Now try them out:
1.1       anton    3756: 
1.29      crook    3757: @example
1.30      anton    3758: @kbd{greet@key{RET}} Hello and welcome  ok
                   3759: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
                   3760: @kbd{4 add-two@key{RET}} 6  ok
                   3761: @kbd{demo@key{RET}} 7  ok
                   3762: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
1.29      crook    3763: @end example
1.1       anton    3764: 
1.29      crook    3765: The first new thing that we've introduced here is the pair of words
                   3766: @code{:} and @code{;}. These are used to start and terminate a new
                   3767: definition, respectively. The first word after the @code{:} is the name
                   3768: for the new definition.
1.1       anton    3769: 
1.29      crook    3770: As you can see from the examples, a definition is built up of words that
                   3771: have already been defined; Forth makes no distinction between
                   3772: definitions that existed when you started the system up, and those that
                   3773: you define yourself.
1.1       anton    3774: 
1.29      crook    3775: The examples also introduce the words @code{.} (dot), @code{."}
                   3776: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
                   3777: the stack and displays it. It's like @code{.s} except that it only
                   3778: displays the top item of the stack and it is destructive; after it has
                   3779: executed, the number is no longer on the stack. There is always one
                   3780: space printed after the number, and no spaces before it. Dot-quote
                   3781: defines a string (a sequence of characters) that will be printed when
                   3782: the word is executed. The string can contain any printable characters
                   3783: except @code{"}. A @code{"} has a special function; it is not a Forth
                   3784: word but it acts as a delimiter (the way that delimiters work is
                   3785: described in the next section). Finally, @code{dup} duplicates the value
                   3786: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1       anton    3787: 
1.29      crook    3788: We already know that the text interpreter searches through the
                   3789: dictionary to locate names. If you've followed the examples earlier, you
                   3790: will already have a definition called @code{add-two}. Lets try modifying
                   3791: it by typing in a new definition:
1.1       anton    3792: 
1.29      crook    3793: @example
1.30      anton    3794: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
1.29      crook    3795: @end example
1.5       anton    3796: 
1.29      crook    3797: Forth recognised that we were defining a word that already exists, and
                   3798: printed a message to warn us of that fact. Let's try out the new
                   3799: definition:
1.5       anton    3800: 
1.29      crook    3801: @example
1.30      anton    3802: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
1.29      crook    3803: @end example
1.1       anton    3804: 
1.29      crook    3805: @noindent
                   3806: All that we've actually done here, though, is to create a new
                   3807: definition, with a particular name. The fact that there was already a
                   3808: definition with the same name did not make any difference to the way
                   3809: that the new definition was created (except that Forth printed a warning
                   3810: message). The old definition of add-two still exists (try @code{demo}
                   3811: again to see that this is true). Any new definition will use the new
                   3812: definition of @code{add-two}, but old definitions continue to use the
                   3813: version that already existed at the time that they were @code{compiled}.
1.1       anton    3814: 
1.29      crook    3815: Before you go on to the next section, try defining and redefining some
                   3816: words of your own.
1.1       anton    3817: 
1.29      crook    3818: @comment ----------------------------------------------
                   3819: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
                   3820: @section How does that work?
                   3821: @cindex parsing words
1.1       anton    3822: 
1.30      anton    3823: @c That's pretty deep (IMO way too deep) for an introduction. - anton
                   3824: 
                   3825: @c Is it a good idea to talk about the interpretation semantics of a
                   3826: @c number? We don't have an xt to go along with it. - anton
                   3827: 
                   3828: @c Now that I have eliminated execution semantics, I wonder if it would not
                   3829: @c be better to keep them (or add run-time semantics), to make it easier to
                   3830: @c explain what compilation semantics usually does. - anton
                   3831: 
1.44      crook    3832: @c nac-> I removed the term ``default compilation sematics'' from the
                   3833: @c introductory chapter. Removing ``execution semantics'' was making
                   3834: @c everything simpler to explain, then I think the use of this term made
                   3835: @c everything more complex again. I replaced it with ``default
                   3836: @c semantics'' (which is used elsewhere in the manual) by which I mean
                   3837: @c ``a definition that has neither the immediate nor the compile-only
                   3838: @c flag set''. I reworded big chunks of the ``how does that work''
                   3839: @c section (and, unusually for me, I think I even made it shorter!).  See
                   3840: @c what you think -- I know I have not addressed your primary concern
                   3841: @c that it is too heavy-going for an introduction. From what I understood
                   3842: @c of your course notes it looks as though they might be a good framework. 
                   3843: @c Things that I've tried to capture here are some things that came as a
                   3844: @c great revelation here when I first understood them. Also, I like the
                   3845: @c fact that a very simple code example shows up almost all of the issues
                   3846: @c that you need to understand to see how Forth works. That's unique and
                   3847: @c worthwhile to emphasise.
                   3848: 
1.29      crook    3849: Now we're going to take another look at the definition of @code{add-two}
                   3850: from the previous section. From our knowledge of the way that the text
                   3851: interpreter works, we would have expected this result when we tried to
                   3852: define @code{add-two}:
1.21      crook    3853: 
1.29      crook    3854: @example
1.44      crook    3855: @kbd{: add-two 2 + . ;@key{RET}}
1.29      crook    3856:   ^^^^^^^
                   3857: Error: Undefined word
                   3858: @end example
1.28      crook    3859: 
1.29      crook    3860: The reason that this didn't happen is bound up in the way that @code{:}
                   3861: works. The word @code{:} does two special things. The first special
                   3862: thing that it does prevents the text interpreter from ever seeing the
                   3863: characters @code{add-two}. The text interpreter uses a variable called
                   3864: @cindex modifying >IN
1.44      crook    3865: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29      crook    3866: input line. When it encounters the word @code{:} it behaves in exactly
                   3867: the same way as it does for any other word; it looks it up in the name
                   3868: dictionary, finds its xt and executes it. When @code{:} executes, it
                   3869: looks at the input buffer, finds the word @code{add-two} and advances the
                   3870: value of @code{>IN} to point past it. It then does some other stuff
                   3871: associated with creating the new definition (including creating an entry
                   3872: for @code{add-two} in the name dictionary). When the execution of @code{:}
                   3873: completes, control returns to the text interpreter, which is oblivious
                   3874: to the fact that it has been tricked into ignoring part of the input
                   3875: line.
1.21      crook    3876: 
1.29      crook    3877: @cindex parsing words
                   3878: Words like @code{:} -- words that advance the value of @code{>IN} and so
                   3879: prevent the text interpreter from acting on the whole of the input line
                   3880: -- are called @dfn{parsing words}.
1.21      crook    3881: 
1.29      crook    3882: @cindex @code{state} - effect on the text interpreter
                   3883: @cindex text interpreter - effect of state
                   3884: The second special thing that @code{:} does is change the value of a
                   3885: variable called @code{state}, which affects the way that the text
                   3886: interpreter behaves. When Gforth starts up, @code{state} has the value
                   3887: 0, and the text interpreter is said to be @dfn{interpreting}. During a
                   3888: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44      crook    3889: the text interpreter is said to be @dfn{compiling}.
                   3890: 
                   3891: In this example, the text interpreter is compiling when it processes the
                   3892: string ``@code{2 + . ;}''. It still breaks the string down into
                   3893: character sequences in the same way. However, instead of pushing the
                   3894: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
                   3895: into the definition of @code{add-two} that will make the number @code{2} get
                   3896: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
                   3897: the behaviours of @code{+} and @code{.} are also compiled into the
                   3898: definition.
                   3899: 
                   3900: One category of words don't get compiled. These so-called @dfn{immediate
                   3901: words} get executed (performed @i{now}) regardless of whether the text
                   3902: interpreter is interpreting or compiling. The word @code{;} is an
                   3903: immediate word. Rather than being compiled into the definition, it
                   3904: executes. Its effect is to terminate the current definition, which
                   3905: includes changing the value of @code{state} back to 0.
                   3906: 
                   3907: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
                   3908: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
                   3909: definition.
1.28      crook    3910: 
1.30      anton    3911: In Forth, every word or number can be described in terms of two
1.29      crook    3912: properties:
1.28      crook    3913: 
                   3914: @itemize @bullet
                   3915: @item
1.29      crook    3916: @cindex interpretation semantics
1.44      crook    3917: Its @dfn{interpretation semantics} describe how it will behave when the
                   3918: text interpreter encounters it in @dfn{interpret} state. The
                   3919: interpretation semantics of a word are represented by an @dfn{execution
                   3920: token}.
1.28      crook    3921: @item
1.29      crook    3922: @cindex compilation semantics
1.44      crook    3923: Its @dfn{compilation semantics} describe how it will behave when the
                   3924: text interpreter encounters it in @dfn{compile} state. The compilation
                   3925: semantics of a word are represented in an implementation-dependent way;
                   3926: Gforth uses a @dfn{compilation token}.
1.29      crook    3927: @end itemize
                   3928: 
                   3929: @noindent
                   3930: Numbers are always treated in a fixed way:
                   3931: 
                   3932: @itemize @bullet
1.28      crook    3933: @item
1.44      crook    3934: When the number is @dfn{interpreted}, its behaviour is to push the
                   3935: number onto the stack.
1.28      crook    3936: @item
1.30      anton    3937: When the number is @dfn{compiled}, a piece of code is appended to the
                   3938: current definition that pushes the number when it runs. (In other words,
                   3939: the compilation semantics of a number are to postpone its interpretation
                   3940: semantics until the run-time of the definition that it is being compiled
                   3941: into.)
1.29      crook    3942: @end itemize
                   3943: 
1.44      crook    3944: Words don't behave in such a regular way, but most have @i{default
                   3945: semantics} which means that they behave like this:
1.29      crook    3946: 
                   3947: @itemize @bullet
1.28      crook    3948: @item
1.30      anton    3949: The @dfn{interpretation semantics} of the word are to do something useful.
                   3950: @item
1.29      crook    3951: The @dfn{compilation semantics} of the word are to append its
1.30      anton    3952: @dfn{interpretation semantics} to the current definition (so that its
                   3953: run-time behaviour is to do something useful).
1.28      crook    3954: @end itemize
                   3955: 
1.30      anton    3956: @cindex immediate words
1.44      crook    3957: The actual behaviour of any particular word can be controlled by using
                   3958: the words @code{immediate} and @code{compile-only} when the word is
                   3959: defined. These words set flags in the name dictionary entry of the most
                   3960: recently defined word, and these flags are retrieved by the text
                   3961: interpreter when it finds the word in the name dictionary.
                   3962: 
                   3963: A word that is marked as @dfn{immediate} has compilation semantics that
                   3964: are identical to its interpretation semantics. In other words, it
                   3965: behaves like this:
1.29      crook    3966: 
                   3967: @itemize @bullet
                   3968: @item
1.30      anton    3969: The @dfn{interpretation semantics} of the word are to do something useful.
1.29      crook    3970: @item
1.30      anton    3971: The @dfn{compilation semantics} of the word are to do something useful
                   3972: (and actually the same thing); i.e., it is executed during compilation.
1.29      crook    3973: @end itemize
1.28      crook    3974: 
1.44      crook    3975: Marking a word as @dfn{compile-only} prohibits the text interpreter from
                   3976: performing the interpretation semantics of the word directly; an attempt
                   3977: to do so will generate an error. It is never necessary to use
                   3978: @code{compile-only} (and it is not even part of ANS Forth, though it is
                   3979: provided by many implementations) but it is good etiquette to apply it
                   3980: to a word that will not behave correctly (and might have unexpected
                   3981: side-effects) in interpret state. For example, it is only legal to use
                   3982: the conditional word @code{IF} within a definition. If you forget this
                   3983: and try to use it elsewhere, the fact that (in Gforth) it is marked as
                   3984: @code{compile-only} allows the text interpreter to generate a helpful
                   3985: error message rather than subjecting you to the consequences of your
                   3986: folly.
                   3987: 
1.29      crook    3988: This example shows the difference between an immediate and a
                   3989: non-immediate word:
1.28      crook    3990: 
1.29      crook    3991: @example
                   3992: : show-state state @@ . ;
                   3993: : show-state-now show-state ; immediate
                   3994: : word1 show-state ;
                   3995: : word2 show-state-now ;
1.28      crook    3996: @end example
1.23      crook    3997: 
1.29      crook    3998: The word @code{immediate} after the definition of @code{show-state-now}
                   3999: makes that word an immediate word. These definitions introduce a new
                   4000: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
                   4001: variable, and leaves it on the stack. Therefore, the behaviour of
                   4002: @code{show-state} is to print a number that represents the current value
                   4003: of @code{state}.
1.28      crook    4004: 
1.29      crook    4005: When you execute @code{word1}, it prints the number 0, indicating that
                   4006: the system is interpreting. When the text interpreter compiled the
                   4007: definition of @code{word1}, it encountered @code{show-state} whose
1.30      anton    4008: compilation semantics are to append its interpretation semantics to the
1.29      crook    4009: current definition. When you execute @code{word1}, it performs the
1.30      anton    4010: interpretation semantics of @code{show-state}.  At the time that @code{word1}
1.29      crook    4011: (and therefore @code{show-state}) are executed, the system is
                   4012: interpreting.
1.28      crook    4013: 
1.30      anton    4014: When you pressed @key{RET} after entering the definition of @code{word2},
1.29      crook    4015: you should have seen the number -1 printed, followed by ``@code{
                   4016: ok}''. When the text interpreter compiled the definition of
                   4017: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30      anton    4018: whose compilation semantics are therefore to perform its interpretation
1.29      crook    4019: semantics. It is executed straight away (even before the text
                   4020: interpreter has moved on to process another group of characters; the
                   4021: @code{;} in this example). The effect of executing it are to display the
                   4022: value of @code{state} @i{at the time that the definition of}
                   4023: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
                   4024: system is compiling at this time. If you execute @code{word2} it does
                   4025: nothing at all.
1.28      crook    4026: 
1.29      crook    4027: @cindex @code{."}, how it works
                   4028: Before leaving the subject of immediate words, consider the behaviour of
                   4029: @code{."} in the definition of @code{greet}, in the previous
                   4030: section. This word is both a parsing word and an immediate word. Notice
                   4031: that there is a space between @code{."} and the start of the text
                   4032: @code{Hello and welcome}, but that there is no space between the last
                   4033: letter of @code{welcome} and the @code{"} character. The reason for this
                   4034: is that @code{."} is a Forth word; it must have a space after it so that
                   4035: the text interpreter can identify it. The @code{"} is not a Forth word;
                   4036: it is a @dfn{delimiter}. The examples earlier show that, when the string
                   4037: is displayed, there is neither a space before the @code{H} nor after the
                   4038: @code{e}. Since @code{."} is an immediate word, it executes at the time
                   4039: that @code{greet} is defined. When it executes, its behaviour is to
                   4040: search forward in the input line looking for the delimiter. When it
                   4041: finds the delimiter, it updates @code{>IN} to point past the
                   4042: delimiter. It also compiles some magic code into the definition of
                   4043: @code{greet}; the xt of a run-time routine that prints a text string. It
                   4044: compiles the string @code{Hello and welcome} into memory so that it is
                   4045: available to be printed later. When the text interpreter gains control,
                   4046: the next word it finds in the input stream is @code{;} and so it
                   4047: terminates the definition of @code{greet}.
1.28      crook    4048: 
                   4049: 
                   4050: @comment ----------------------------------------------
1.29      crook    4051: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
                   4052: @section Forth is written in Forth
                   4053: @cindex structure of Forth programs
                   4054: 
                   4055: When you start up a Forth compiler, a large number of definitions
                   4056: already exist. In Forth, you develop a new application using bottom-up
                   4057: programming techniques to create new definitions that are defined in
                   4058: terms of existing definitions. As you create each definition you can
                   4059: test and debug it interactively.
                   4060: 
                   4061: If you have tried out the examples in this section, you will probably
                   4062: have typed them in by hand; when you leave Gforth, your definitions will
                   4063: be lost. You can avoid this by using a text editor to enter Forth source
                   4064: code into a file, and then loading code from the file using
                   4065: @code{include} (@xref{Forth source files}). A Forth source file is
                   4066: processed by the text interpreter, just as though you had typed it in by
                   4067: hand@footnote{Actually, there are some subtle differences -- see
                   4068: @ref{The Text Interpreter}.}.
                   4069: 
                   4070: Gforth also supports the traditional Forth alternative to using text
                   4071: files for program entry (@xref{Blocks}).
1.28      crook    4072: 
1.29      crook    4073: In common with many, if not most, Forth compilers, most of Gforth is
                   4074: actually written in Forth. All of the @file{.fs} files in the
                   4075: installation directory@footnote{For example,
1.30      anton    4076: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29      crook    4077: study to see examples of Forth programming.
1.28      crook    4078: 
1.29      crook    4079: Gforth maintains a history file that records every line that you type to
                   4080: the text interpreter. This file is preserved between sessions, and is
                   4081: used to provide a command-line recall facility. If you enter long
                   4082: definitions by hand, you can use a text editor to paste them out of the
                   4083: history file into a Forth source file for reuse at a later time
                   4084: (@pxref{Command-line editing} for more information).
1.28      crook    4085: 
                   4086: 
                   4087: @comment ----------------------------------------------
1.29      crook    4088: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
                   4089: @section Review - elements of a Forth system
                   4090: @cindex elements of a Forth system
1.28      crook    4091: 
1.29      crook    4092: To summarise this chapter:
1.28      crook    4093: 
                   4094: @itemize @bullet
                   4095: @item
1.29      crook    4096: Forth programs use @dfn{factoring} to break a problem down into small
                   4097: fragments called @dfn{words} or @dfn{definitions}.
                   4098: @item
                   4099: Forth program development is an interactive process.
                   4100: @item
                   4101: The main command loop that accepts input, and controls both
                   4102: interpretation and compilation, is called the @dfn{text interpreter}
                   4103: (also known as the @dfn{outer interpreter}).
                   4104: @item
                   4105: Forth has a very simple syntax, consisting of words and numbers
                   4106: separated by spaces or carriage-return characters. Any additional syntax
                   4107: is imposed by @dfn{parsing words}.
                   4108: @item
                   4109: Forth uses a stack to pass parameters between words. As a result, it
                   4110: uses postfix notation.
                   4111: @item
                   4112: To use a word that has previously been defined, the text interpreter
                   4113: searches for the word in the @dfn{name dictionary}.
                   4114: @item
1.30      anton    4115: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28      crook    4116: @item
1.29      crook    4117: The text interpreter uses the value of @code{state} to select between
                   4118: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
                   4119: semantics} of a word that it encounters.
1.28      crook    4120: @item
1.30      anton    4121: The relationship between the @dfn{interpretation semantics} and
                   4122: @dfn{compilation semantics} for a word
1.29      crook    4123: depend upon the way in which the word was defined (for example, whether
                   4124: it is an @dfn{immediate} word).
1.28      crook    4125: @item
1.29      crook    4126: Forth definitions can be implemented in Forth (called @dfn{high-level
                   4127: definitions}) or in some other way (usually a lower-level language and
                   4128: as a result often called @dfn{low-level definitions}, @dfn{code
                   4129: definitions} or @dfn{primitives}).
1.28      crook    4130: @item
1.29      crook    4131: Many Forth systems are implemented mainly in Forth.
1.28      crook    4132: @end itemize
                   4133: 
                   4134: 
1.29      crook    4135: @comment ----------------------------------------------
1.48    ! anton    4136: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29      crook    4137: @section Where To Go Next
                   4138: @cindex where to go next
1.28      crook    4139: 
1.29      crook    4140: Amazing as it may seem, if you have read (and understood) this far, you
                   4141: know almost all the fundamentals about the inner workings of a Forth
                   4142: system. You certainly know enough to be able to read and understand the
                   4143: rest of this manual and the ANS Forth document, to learn more about the
                   4144: facilities that Forth in general and Gforth in particular provide. Even
                   4145: scarier, you know almost enough to implement your own Forth system.
1.30      anton    4146: However, that's not a good idea just yet... better to try writing some
1.29      crook    4147: programs in Gforth.
1.28      crook    4148: 
1.29      crook    4149: Forth has such a rich vocabulary that it can be hard to know where to
                   4150: start in learning it. This section suggests a few sets of words that are
                   4151: enough to write small but useful programs. Use the word index in this
                   4152: document to learn more about each word, then try it out and try to write
                   4153: small definitions using it. Start by experimenting with these words:
1.28      crook    4154: 
                   4155: @itemize @bullet
                   4156: @item
1.29      crook    4157: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
                   4158: @item
                   4159: Comparison: @code{MIN MAX =}
                   4160: @item
                   4161: Logic: @code{AND OR XOR NOT}
                   4162: @item
                   4163: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28      crook    4164: @item
1.29      crook    4165: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28      crook    4166: @item
1.29      crook    4167: Input/Output: @code{. ." EMIT CR KEY}
1.28      crook    4168: @item
1.29      crook    4169: Defining words: @code{: ; CREATE}
1.28      crook    4170: @item
1.29      crook    4171: Memory allocation words: @code{ALLOT ,}
1.28      crook    4172: @item
1.29      crook    4173: Tools: @code{SEE WORDS .S MARKER}
                   4174: @end itemize
                   4175: 
                   4176: When you have mastered those, go on to:
                   4177: 
                   4178: @itemize @bullet
1.28      crook    4179: @item
1.29      crook    4180: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28      crook    4181: @item
1.29      crook    4182: Memory access: @code{@@ !}
1.28      crook    4183: @end itemize
1.23      crook    4184: 
1.29      crook    4185: When you have mastered these, there's nothing for it but to read through
                   4186: the whole of this manual and find out what you've missed.
                   4187: 
                   4188: @comment ----------------------------------------------
1.48    ! anton    4189: @node Exercises,  , Where to go next, Introduction
1.29      crook    4190: @section Exercises
                   4191: @cindex exercises
                   4192: 
                   4193: TODO: provide a set of programming excercises linked into the stuff done
                   4194: already and into other sections of the manual. Provide solutions to all
                   4195: the exercises in a .fs file in the distribution.
                   4196: 
                   4197: @c Get some inspiration from Starting Forth and Kelly&Spies.
                   4198: 
                   4199: @c excercises:
                   4200: @c 1. take inches and convert to feet and inches.
                   4201: @c 2. take temperature and convert from fahrenheight to celcius;
                   4202: @c    may need to care about symmetric vs floored??
                   4203: @c 3. take input line and do character substitution
                   4204: @c    to encipher or decipher
                   4205: @c 4. as above but work on a file for in and out
                   4206: @c 5. take input line and convert to pig-latin 
                   4207: @c
                   4208: @c thing of sets of things to exercise then come up with
                   4209: @c problems that need those things.
                   4210: 
                   4211: 
1.26      crook    4212: @c ******************************************************************
1.29      crook    4213: @node Words, Error messages, Introduction, Top
1.1       anton    4214: @chapter Forth Words
1.26      crook    4215: @cindex words
1.1       anton    4216: 
                   4217: @menu
                   4218: * Notation::                    
1.21      crook    4219: * Comments::
                   4220: * Boolean Flags::
1.1       anton    4221: * Arithmetic::                  
                   4222: * Stack Manipulation::          
1.5       anton    4223: * Memory::                      
1.1       anton    4224: * Control Structures::          
                   4225: * Defining Words::              
1.47      crook    4226: * Interpretation and Compilation Semantics::
                   4227: * Tokens for Words::            
1.21      crook    4228: * The Text Interpreter::
                   4229: * Word Lists::                   
                   4230: * Environmental Queries::
1.12      anton    4231: * Files::                       
                   4232: * Blocks::                      
                   4233: * Other I/O::                   
                   4234: * Programming Tools::           
                   4235: * Assembler and Code Words::    
                   4236: * Threading Words::             
1.26      crook    4237: * Locals::                      
                   4238: * Structures::                  
                   4239: * Object-oriented Forth::       
1.21      crook    4240: * Passing Commands to the OS::
1.47      crook    4241: * Keeping track of Time::
1.21      crook    4242: * Miscellaneous Words::
1.1       anton    4243: @end menu
                   4244: 
1.21      crook    4245: @node Notation, Comments, Words, Words
1.1       anton    4246: @section Notation
                   4247: @cindex notation of glossary entries
                   4248: @cindex format of glossary entries
                   4249: @cindex glossary notation format
                   4250: @cindex word glossary entry format
                   4251: 
                   4252: The Forth words are described in this section in the glossary notation
                   4253: that has become a de-facto standard for Forth texts, i.e.,
                   4254: 
                   4255: @format
1.29      crook    4256: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
1.1       anton    4257: @end format
1.29      crook    4258: @i{Description}
1.1       anton    4259: 
                   4260: @table @var
                   4261: @item word
1.28      crook    4262: The name of the word.
1.1       anton    4263: 
                   4264: @item Stack effect
                   4265: @cindex stack effect
1.29      crook    4266: The stack effect is written in the notation @code{@i{before} --
                   4267: @i{after}}, where @i{before} and @i{after} describe the top of
1.1       anton    4268: stack entries before and after the execution of the word. The rest of
                   4269: the stack is not touched by the word. The top of stack is rightmost,
                   4270: i.e., a stack sequence is written as it is typed in. Note that Gforth
                   4271: uses a separate floating point stack, but a unified stack
1.29      crook    4272: notation. Also, return stack effects are not shown in @i{stack
                   4273: effect}, but in @i{Description}. The name of a stack item describes
1.1       anton    4274: the type and/or the function of the item. See below for a discussion of
                   4275: the types.
                   4276: 
                   4277: All words have two stack effects: A compile-time stack effect and a
                   4278: run-time stack effect. The compile-time stack-effect of most words is
1.29      crook    4279: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1       anton    4280: this standard behaviour, or the word does other unusual things at
                   4281: compile time, both stack effects are shown; otherwise only the run-time
                   4282: stack effect is shown.
                   4283: 
                   4284: @cindex pronounciation of words
                   4285: @item pronunciation
                   4286: How the word is pronounced.
                   4287: 
                   4288: @cindex wordset
                   4289: @item wordset
1.21      crook    4290: The ANS Forth standard is divided into several word sets. A standard
                   4291: system need not support all of them. Therefore, in theory, the fewer
                   4292: word sets your program uses the more portable it will be. However, we
                   4293: suspect that most ANS Forth systems on personal machines will feature
1.26      crook    4294: all word sets. Words that are not defined in ANS Forth have
1.21      crook    4295: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1       anton    4296: describes words that will work in future releases of Gforth;
                   4297: @code{gforth-internal} words are more volatile. Environmental query
                   4298: strings are also displayed like words; you can recognize them by the
1.21      crook    4299: @code{environment} in the word set field.
1.1       anton    4300: 
                   4301: @item Description
                   4302: A description of the behaviour of the word.
                   4303: @end table
                   4304: 
                   4305: @cindex types of stack items
                   4306: @cindex stack item types
                   4307: The type of a stack item is specified by the character(s) the name
                   4308: starts with:
                   4309: 
                   4310: @table @code
                   4311: @item f
                   4312: @cindex @code{f}, stack item type
                   4313: Boolean flags, i.e. @code{false} or @code{true}.
                   4314: @item c
                   4315: @cindex @code{c}, stack item type
                   4316: Char
                   4317: @item w
                   4318: @cindex @code{w}, stack item type
                   4319: Cell, can contain an integer or an address
                   4320: @item n
                   4321: @cindex @code{n}, stack item type
                   4322: signed integer
                   4323: @item u
                   4324: @cindex @code{u}, stack item type
                   4325: unsigned integer
                   4326: @item d
                   4327: @cindex @code{d}, stack item type
                   4328: double sized signed integer
                   4329: @item ud
                   4330: @cindex @code{ud}, stack item type
                   4331: double sized unsigned integer
                   4332: @item r
                   4333: @cindex @code{r}, stack item type
                   4334: Float (on the FP stack)
1.21      crook    4335: @item a-
1.1       anton    4336: @cindex @code{a_}, stack item type
                   4337: Cell-aligned address
1.21      crook    4338: @item c-
1.1       anton    4339: @cindex @code{c_}, stack item type
                   4340: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21      crook    4341: @item f-
1.1       anton    4342: @cindex @code{f_}, stack item type
                   4343: Float-aligned address
1.21      crook    4344: @item df-
1.1       anton    4345: @cindex @code{df_}, stack item type
                   4346: Address aligned for IEEE double precision float
1.21      crook    4347: @item sf-
1.1       anton    4348: @cindex @code{sf_}, stack item type
                   4349: Address aligned for IEEE single precision float
                   4350: @item xt
                   4351: @cindex @code{xt}, stack item type
                   4352: Execution token, same size as Cell
                   4353: @item wid
                   4354: @cindex @code{wid}, stack item type
1.21      crook    4355: Word list ID, same size as Cell
1.1       anton    4356: @item f83name
                   4357: @cindex @code{f83name}, stack item type
                   4358: Pointer to a name structure
                   4359: @item "
                   4360: @cindex @code{"}, stack item type
1.12      anton    4361: string in the input stream (not on the stack). The terminating character
                   4362: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1       anton    4363: quotes.
                   4364: @end table
                   4365: 
1.21      crook    4366: @node Comments, Boolean Flags, Notation, Words
                   4367: @section Comments
1.26      crook    4368: @cindex comments
1.21      crook    4369: 
1.29      crook    4370: Forth supports two styles of comment; the traditional @i{in-line} comment,
                   4371: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21      crook    4372: 
1.44      crook    4373: 
1.23      crook    4374: doc-(
1.21      crook    4375: doc-\
1.23      crook    4376: doc-\G
1.21      crook    4377: 
1.44      crook    4378: 
1.21      crook    4379: @node Boolean Flags, Arithmetic, Comments, Words
                   4380: @section Boolean Flags
1.26      crook    4381: @cindex Boolean flags
1.21      crook    4382: 
                   4383: A Boolean flag is cell-sized. A cell with all bits clear represents the
                   4384: flag @code{false} and a flag with all bits set represents the flag
1.26      crook    4385: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29      crook    4386: a cell that has @i{any} bit set as @code{true}.
1.21      crook    4387: 
1.44      crook    4388: 
1.21      crook    4389: doc-true
                   4390: doc-false
1.29      crook    4391: doc-on
                   4392: doc-off
1.21      crook    4393: 
1.44      crook    4394: 
1.21      crook    4395: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1       anton    4396: @section Arithmetic
                   4397: @cindex arithmetic words
                   4398: 
                   4399: @cindex division with potentially negative operands
                   4400: Forth arithmetic is not checked, i.e., you will not hear about integer
                   4401: overflow on addition or multiplication, you may hear about division by
                   4402: zero if you are lucky. The operator is written after the operands, but
                   4403: the operands are still in the original order. I.e., the infix @code{2-1}
                   4404: corresponds to @code{2 1 -}. Forth offers a variety of division
                   4405: operators. If you perform division with potentially negative operands,
                   4406: you do not want to use @code{/} or @code{/mod} with its undefined
                   4407: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
                   4408: former, @pxref{Mixed precision}).
1.26      crook    4409: @comment TODO discuss the different division forms and the std approach
1.1       anton    4410: 
                   4411: @menu
                   4412: * Single precision::            
                   4413: * Bitwise operations::          
1.21      crook    4414: * Double precision::            Double-cell integer arithmetic
                   4415: * Numeric comparison::
1.29      crook    4416: * Mixed precision::             Operations with single and double-cell integers
1.1       anton    4417: * Floating Point::              
                   4418: @end menu
                   4419: 
                   4420: @node Single precision, Bitwise operations, Arithmetic, Arithmetic
                   4421: @subsection Single precision
                   4422: @cindex single precision arithmetic words
                   4423: 
1.21      crook    4424: By default, numbers in Forth are single-precision integers that are 1
1.26      crook    4425: cell in size. They can be signed or unsigned, depending upon how you
1.21      crook    4426: treat them. @xref{Number Conversion} for the rules used by the text
                   4427: interpreter for recognising single-precision integers.
                   4428: 
1.44      crook    4429: 
1.1       anton    4430: doc-+
1.21      crook    4431: doc-1+
1.1       anton    4432: doc--
1.21      crook    4433: doc-1-
1.1       anton    4434: doc-*
                   4435: doc-/
                   4436: doc-mod
                   4437: doc-/mod
                   4438: doc-negate
                   4439: doc-abs
                   4440: doc-min
                   4441: doc-max
1.21      crook    4442: doc-d>s
1.27      crook    4443: doc-floored
1.1       anton    4444: 
1.44      crook    4445: 
1.21      crook    4446: @node Bitwise operations, Double precision, Single precision, Arithmetic
1.1       anton    4447: @subsection Bitwise operations
                   4448: @cindex bitwise operation words
                   4449: 
1.44      crook    4450: 
1.1       anton    4451: doc-and
                   4452: doc-or
                   4453: doc-xor
                   4454: doc-invert
1.21      crook    4455: doc-lshift
                   4456: doc-rshift
1.1       anton    4457: doc-2*
1.21      crook    4458: doc-d2*
1.1       anton    4459: doc-2/
1.21      crook    4460: doc-d2/
                   4461: 
1.44      crook    4462: 
1.21      crook    4463: @node Double precision, Numeric comparison, Bitwise operations, Arithmetic
                   4464: @subsection Double precision
                   4465: @cindex double precision arithmetic words
                   4466: 
                   4467: @xref{Number Conversion} for the rules used by the text interpreter for
                   4468: recognising double-precision integers.
                   4469: 
                   4470: A double precision number is represented by a cell pair, with the most
1.31      anton    4471: significant cell at the TOS. It is trivial to convert an unsigned
1.26      crook    4472: single to an (unsigned) double; simply push a @code{0} onto the
                   4473: TOS. Since numbers are represented by Gforth using 2's complement
                   4474: arithmetic, converting a signed single to a (signed) double requires
1.31      anton    4475: sign-extension across the most significant cell. This can be achieved
1.26      crook    4476: using @code{s>d}. The moral of the story is that you cannot convert a
                   4477: number without knowing whether it represents an unsigned or a
                   4478: signed number.
1.21      crook    4479: 
1.44      crook    4480: 
1.21      crook    4481: doc-s>d
                   4482: doc-d+
                   4483: doc-d-
                   4484: doc-dnegate
                   4485: doc-dabs
                   4486: doc-dmin
                   4487: doc-dmax
                   4488: 
1.44      crook    4489: 
1.21      crook    4490: @node Numeric comparison, Mixed precision, Double precision, Arithmetic
                   4491: @subsection Numeric comparison
                   4492: @cindex numeric comparison words
                   4493: 
1.44      crook    4494: 
1.28      crook    4495: doc-<
                   4496: doc-<=
                   4497: doc-<>
                   4498: doc-=
                   4499: doc->
                   4500: doc->=
                   4501: 
1.21      crook    4502: doc-0<
1.23      crook    4503: doc-0<=
1.21      crook    4504: doc-0<>
                   4505: doc-0=
1.23      crook    4506: doc-0>
                   4507: doc-0>=
1.28      crook    4508: 
                   4509: doc-u<
                   4510: doc-u<=
1.44      crook    4511: @c u<> and u= exist but are the same as <> and =
1.31      anton    4512: @c doc-u<>
                   4513: @c doc-u=
1.28      crook    4514: doc-u>
                   4515: doc-u>=
                   4516: 
                   4517: doc-within
                   4518: 
                   4519: doc-d<
                   4520: doc-d<=
                   4521: doc-d<>
                   4522: doc-d=
                   4523: doc-d>
                   4524: doc-d>=
1.23      crook    4525: 
1.21      crook    4526: doc-d0<
1.23      crook    4527: doc-d0<=
                   4528: doc-d0<>
1.21      crook    4529: doc-d0=
1.23      crook    4530: doc-d0>
                   4531: doc-d0>=
                   4532: 
1.21      crook    4533: doc-du<
1.28      crook    4534: doc-du<=
1.44      crook    4535: @c du<> and du= exist but are the same as d<> and d=
1.31      anton    4536: @c doc-du<>
                   4537: @c doc-du=
1.28      crook    4538: doc-du>
                   4539: doc-du>=
1.1       anton    4540: 
1.44      crook    4541: 
1.21      crook    4542: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1       anton    4543: @subsection Mixed precision
                   4544: @cindex mixed precision arithmetic words
                   4545: 
1.44      crook    4546: 
1.1       anton    4547: doc-m+
                   4548: doc-*/
                   4549: doc-*/mod
                   4550: doc-m*
                   4551: doc-um*
                   4552: doc-m*/
                   4553: doc-um/mod
                   4554: doc-fm/mod
                   4555: doc-sm/rem
                   4556: 
1.44      crook    4557: 
1.21      crook    4558: @node Floating Point,  , Mixed precision, Arithmetic
1.1       anton    4559: @subsection Floating Point
                   4560: @cindex floating point arithmetic words
                   4561: 
1.21      crook    4562: @xref{Number Conversion} for the rules used by the text interpreter for
                   4563: recognising floating-point numbers.
1.1       anton    4564: 
1.32      anton    4565: Gforth has a separate floating point
1.26      crook    4566: stack, but the documentation uses the unified notation.
1.1       anton    4567: 
                   4568: @cindex floating-point arithmetic, pitfalls
                   4569: Floating point numbers have a number of unpleasant surprises for the
                   4570: unwary (e.g., floating point addition is not associative) and even a few
                   4571: for the wary. You should not use them unless you know what you are doing
                   4572: or you don't care that the results you get are totally bogus. If you
                   4573: want to learn about the problems of floating point numbers (and how to
                   4574: avoid them), you might start with @cite{David Goldberg, What Every
                   4575: Computer Scientist Should Know About Floating-Point Arithmetic, ACM
1.17      anton    4576: Computing Surveys 23(1):5@minus{}48, March 1991}
1.47      crook    4577: (@uref{http://www.validgh.com/goldberg/paper.ps}).
1.1       anton    4578: 
1.44      crook    4579: 
1.21      crook    4580: doc-d>f
                   4581: doc-f>d
1.1       anton    4582: doc-f+
                   4583: doc-f-
                   4584: doc-f*
                   4585: doc-f/
                   4586: doc-fnegate
                   4587: doc-fabs
                   4588: doc-fmax
                   4589: doc-fmin
                   4590: doc-floor
                   4591: doc-fround
                   4592: doc-f**
                   4593: doc-fsqrt
                   4594: doc-fexp
                   4595: doc-fexpm1
                   4596: doc-fln
                   4597: doc-flnp1
                   4598: doc-flog
                   4599: doc-falog
1.32      anton    4600: doc-f2*
                   4601: doc-f2/
                   4602: doc-1/f
                   4603: doc-precision
                   4604: doc-set-precision
                   4605: 
                   4606: @cindex angles in trigonometric operations
                   4607: @cindex trigonometric operations
                   4608: Angles in floating point operations are given in radians (a full circle
                   4609: has 2 pi radians).
                   4610: 
1.1       anton    4611: doc-fsin
                   4612: doc-fcos
                   4613: doc-fsincos
                   4614: doc-ftan
                   4615: doc-fasin
                   4616: doc-facos
                   4617: doc-fatan
                   4618: doc-fatan2
                   4619: doc-fsinh
                   4620: doc-fcosh
                   4621: doc-ftanh
                   4622: doc-fasinh
                   4623: doc-facosh
                   4624: doc-fatanh
1.21      crook    4625: doc-pi
1.28      crook    4626: 
1.32      anton    4627: @cindex equality of floats
                   4628: @cindex floating-point comparisons
1.31      anton    4629: One particular problem with floating-point arithmetic is that comparison
                   4630: for equality often fails when you would expect it to succeed.  For this
                   4631: reason approximate equality is often preferred (but you still have to
                   4632: know what you are doing).  The comparison words are:
                   4633: 
                   4634: doc-f~rel
                   4635: doc-f~abs
                   4636: doc-f=
                   4637: doc-f~
                   4638: doc-f<>
                   4639: 
                   4640: doc-f<
                   4641: doc-f<=
                   4642: doc-f>
                   4643: doc-f>=
                   4644: 
1.21      crook    4645: doc-f0<
1.28      crook    4646: doc-f0<=
                   4647: doc-f0<>
1.21      crook    4648: doc-f0=
1.28      crook    4649: doc-f0>
                   4650: doc-f0>=
                   4651: 
1.1       anton    4652: 
                   4653: @node Stack Manipulation, Memory, Arithmetic, Words
                   4654: @section Stack Manipulation
                   4655: @cindex stack manipulation words
                   4656: 
                   4657: @cindex floating-point stack in the standard
1.21      crook    4658: Gforth maintains a number of separate stacks:
                   4659: 
1.29      crook    4660: @cindex data stack
                   4661: @cindex parameter stack
1.21      crook    4662: @itemize @bullet
                   4663: @item
1.29      crook    4664: A data stack (also known as the @dfn{parameter stack}) -- for
                   4665: characters, cells, addresses, and double cells.
1.21      crook    4666: 
1.29      crook    4667: @cindex floating-point stack
1.21      crook    4668: @item
1.44      crook    4669: A floating point stack -- for holding floating point (FP) numbers.
1.21      crook    4670: 
1.29      crook    4671: @cindex return stack
1.21      crook    4672: @item
1.44      crook    4673: A return stack -- for holding the return addresses of colon
1.32      anton    4674: definitions and other (non-FP) data.
1.21      crook    4675: 
1.29      crook    4676: @cindex locals stack
1.21      crook    4677: @item
1.44      crook    4678: A locals stack -- for holding local variables.
1.21      crook    4679: @end itemize
                   4680: 
1.1       anton    4681: @menu
                   4682: * Data stack::                  
                   4683: * Floating point stack::        
                   4684: * Return stack::                
                   4685: * Locals stack::                
                   4686: * Stack pointer manipulation::  
                   4687: @end menu
                   4688: 
                   4689: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
                   4690: @subsection Data stack
                   4691: @cindex data stack manipulation words
                   4692: @cindex stack manipulations words, data stack
                   4693: 
1.44      crook    4694: 
1.1       anton    4695: doc-drop
                   4696: doc-nip
                   4697: doc-dup
                   4698: doc-over
                   4699: doc-tuck
                   4700: doc-swap
1.21      crook    4701: doc-pick
1.1       anton    4702: doc-rot
                   4703: doc--rot
                   4704: doc-?dup
                   4705: doc-roll
                   4706: doc-2drop
                   4707: doc-2nip
                   4708: doc-2dup
                   4709: doc-2over
                   4710: doc-2tuck
                   4711: doc-2swap
                   4712: doc-2rot
                   4713: 
1.44      crook    4714: 
1.1       anton    4715: @node Floating point stack, Return stack, Data stack, Stack Manipulation
                   4716: @subsection Floating point stack
                   4717: @cindex floating-point stack manipulation words
                   4718: @cindex stack manipulation words, floating-point stack
                   4719: 
1.32      anton    4720: Whilst every sane Forth has a separate floating-point stack, it is not
                   4721: strictly required; an ANS Forth system could theoretically keep
                   4722: floating-point numbers on the data stack. As an additional difficulty,
                   4723: you don't know how many cells a floating-point number takes. It is
                   4724: reportedly possible to write words in a way that they work also for a
                   4725: unified stack model, but we do not recommend trying it. Instead, just
                   4726: say that your program has an environmental dependency on a separate
                   4727: floating-point stack.
                   4728: 
                   4729: doc-floating-stack
                   4730: 
1.1       anton    4731: doc-fdrop
                   4732: doc-fnip
                   4733: doc-fdup
                   4734: doc-fover
                   4735: doc-ftuck
                   4736: doc-fswap
1.21      crook    4737: doc-fpick
1.1       anton    4738: doc-frot
                   4739: 
1.44      crook    4740: 
1.1       anton    4741: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
                   4742: @subsection Return stack
                   4743: @cindex return stack manipulation words
                   4744: @cindex stack manipulation words, return stack
                   4745: 
1.32      anton    4746: @cindex return stack and locals
                   4747: @cindex locals and return stack
                   4748: A Forth system is allowed to keep local variables on the
                   4749: return stack. This is reasonable, as local variables usually eliminate
                   4750: the need to use the return stack explicitly. So, if you want to produce
                   4751: a standard compliant program and you are using local variables in a
                   4752: word, forget about return stack manipulations in that word (refer to the
                   4753: standard document for the exact rules).
                   4754: 
1.1       anton    4755: doc->r
                   4756: doc-r>
                   4757: doc-r@
                   4758: doc-rdrop
                   4759: doc-2>r
                   4760: doc-2r>
                   4761: doc-2r@
                   4762: doc-2rdrop
                   4763: 
1.44      crook    4764: 
1.1       anton    4765: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
                   4766: @subsection Locals stack
                   4767: 
1.47      crook    4768: Gforth uses an extra locals stack. It is described, along with the
                   4769: reasons for its existence, in @ref{Implementation,Implementation of locals}.
1.21      crook    4770: 
1.1       anton    4771: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
                   4772: @subsection Stack pointer manipulation
                   4773: @cindex stack pointer manipulation words
                   4774: 
1.44      crook    4775: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21      crook    4776: doc-sp0
1.1       anton    4777: doc-sp@
                   4778: doc-sp!
1.21      crook    4779: doc-fp0
1.1       anton    4780: doc-fp@
                   4781: doc-fp!
1.21      crook    4782: doc-rp0
1.1       anton    4783: doc-rp@
                   4784: doc-rp!
1.21      crook    4785: doc-lp0
1.1       anton    4786: doc-lp@
                   4787: doc-lp!
                   4788: 
1.44      crook    4789: 
1.1       anton    4790: @node Memory, Control Structures, Stack Manipulation, Words
                   4791: @section Memory
1.26      crook    4792: @cindex memory words
1.1       anton    4793: 
1.32      anton    4794: @menu
                   4795: * Memory model::                
                   4796: * Dictionary allocation::       
                   4797: * Heap Allocation::             
                   4798: * Memory Access::               
                   4799: * Address arithmetic::          
                   4800: * Memory Blocks::               
                   4801: @end menu
                   4802: 
                   4803: @node Memory model, Dictionary allocation, Memory, Memory
                   4804: @subsection ANS Forth and Gforth memory models
                   4805: 
                   4806: @c The ANS Forth description is a mess (e.g., is the heap part of
                   4807: @c the dictionary?), so let's not stick to closely with it.
                   4808: 
                   4809: ANS Forth considers a Forth system as consisting of several memories, of
                   4810: which only @dfn{data space} is managed and accessible with the memory
                   4811: words.  Memory not necessarily in data space includes the stacks, the
                   4812: code (called code space) and the headers (called name space). In Gforth
                   4813: everything is in data space, but the code for the primitives is usually
                   4814: read-only.
                   4815: 
                   4816: Data space is divided into a number of areas: The (data space portion of
                   4817: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
                   4818: refer to the search data structure embodied in word lists and headers,
                   4819: because it is used for looking up names, just as you would in a
                   4820: conventional dictionary.}, the heap, and a number of system-allocated
                   4821: buffers.
                   4822: 
                   4823: In ANS Forth data space is also divided into contiguous regions.  You
                   4824: can only use address arithmetic within a contiguous region, not between
                   4825: them.  Usually each allocation gives you one contiguous region, but the
1.33      anton    4826: dictionary allocation words have additional rules (@pxref{Dictionary
1.32      anton    4827: allocation}).
                   4828: 
                   4829: Gforth provides one big address space, and address arithmetic can be
                   4830: performed between any addresses. However, in the dictionary headers or
                   4831: code are interleaved with data, so almost the only contiguous data space
                   4832: regions there are those described by ANS Forth as contiguous; but you
                   4833: can be sure that the dictionary is allocated towards increasing
                   4834: addresses even between contiguous regions.  The memory order of
                   4835: allocations in the heap is platform-dependent (and possibly different
                   4836: from one run to the next).
                   4837: 
                   4838: @subsubsection ANS Forth dictionary details
                   4839: 
                   4840: This section is just informative, you can skip it if you are in a hurry.
1.27      crook    4841: 
1.29      crook    4842: When you create a colon definition, the text interpreter compiles the
1.32      anton    4843: code for the definition into the code space and compiles the name
                   4844: of the definition into the header space, together with other
1.27      crook    4845: information about the definition (such as its execution token).
                   4846: 
1.44      crook    4847: When you create a variable, the execution of @code{Variable} will
1.32      anton    4848: compile some code, assign one cell in data space, and compile the name
                   4849: of the variable into the header space.
1.27      crook    4850: 
                   4851: @cindex memory regions - relationship between them
                   4852: ANS Forth does not specify the relationship between the three memory
                   4853: regions, and specifies that a Standard program must not access code or
                   4854: data space directly -- it may only access data space directly. In
                   4855: addition, the Standard defines what relationships you may and may not
                   4856: rely on when allocating regions in data space. These constraints are
                   4857: simply a reflection of the many diverse techniques that are used to
                   4858: implement Forth systems; understanding and following the requirements of
                   4859: the Standard allows you to write portable programs -- programs that run
                   4860: in the same way on any of these diverse systems. Another way of looking
                   4861: at this is to say that ANS Forth was designed to permit compliant Forth
                   4862: systems to be implemented in many diverse ways.
                   4863: 
                   4864: @cindex memory regions - how they are assigned
1.29      crook    4865: Here are some examples of ways in which name, code and data spaces
                   4866: might be assigned in different Forth implementations:
1.27      crook    4867: 
                   4868: @itemize @bullet
                   4869: @item
                   4870: For a Forth system that runs from RAM under a general-purpose operating
                   4871: system, it can be convenient to interleave name, code and data spaces in
                   4872: a single contiguous memory region. This organisation can be
                   4873: memory-efficient (for example, because the relationship between the name
1.32      anton    4874: dictionary entry and the associated code space entry can be
1.27      crook    4875: implicit, rather than requiring an explicit memory pointer to reference
1.32      anton    4876: from the header space and the code space). This is the
1.27      crook    4877: organisation used by Gforth, as this example@footnote{The addresses
                   4878: in the example have been truncated to fit it onto the page, and the
                   4879: addresses and data shown will not match the output from your system} shows:
                   4880: @example
                   4881: hex
                   4882: variable fred 123456 fred !
                   4883: variable jim abcd jim !
                   4884: : foo + / - ;
                   4885: ' fred 10 - 50 dump 
                   4886: ..80: 5C 46 0E 40  84 66 72 65 - 64 20 20 20  20 20 20 20  \F.@.fred       
                   4887: ..90: D0 9B 04 08  00 00 00 00 - 56 34 12 00  80 46 0E 40  ........V4...F.@
                   4888: ..A0: 83 6A 69 6D  20 20 20 20 - D0 9B 04 08  00 00 00 00  .jim    ........
                   4889: ..B0: CD AB 00 00  9C 46 0E 40 - 83 66 6F 6F  20 20 20 20  .....F.@.foo    
                   4890: ..C0: 80 9B 04 08  00 00 00 00 - E4 2E 05 08  0C 2F 05 08  ............./..
                   4891: @end example
                   4892: 
                   4893: @item
                   4894: For a high-performance system running on a modern RISC processor with a
                   4895: modified Harvard architecture (one that has a unified main memory but
                   4896: separate instruction and data caches), it is desirable to separate
                   4897: processor instructions from processor data. This encourages a high cache
1.32      anton    4898: density and therefore a high cache hit rate. The Forth code space
1.27      crook    4899: is not necessarily made up entirely of processor instructions; its
                   4900: nature is dependent upon the Forth implementation. 
                   4901: 
                   4902: @item
                   4903: A Forth compiler that runs on a segmented 8086 processor could be
                   4904: designed to interleave the name, code and data spaces within a single
                   4905: 64Kbyte segment. A more common implementation choice is to use a
                   4906: separate 64Kbyte segment for each region, which provides more memory
                   4907: overall but provides an address map in which only the data space is
                   4908: accessible.
                   4909: 
                   4910: @item
                   4911: Microprocessors exist that run Forth (or many of the primitives required
                   4912: to implement the Forth virtual machine efficiently) directly. On these
                   4913: processors, the relationship between name, code and data spaces may be
1.32      anton    4914: imposed as a side-effect of the architecture of the processor.
1.27      crook    4915: 
                   4916: @item
                   4917: A Forth compiler that executes from ROM on an embedded system needs its
                   4918: data space separated from the name and code spaces so that the data
                   4919: space can be mapped to a RAM area.
                   4920: 
                   4921: @item 
                   4922: A Forth compiler that runs on an embedded system may have a requirement
                   4923: for a small memory footprint. On such a system it can be useful to
1.32      anton    4924: separate the header space from the data and code spaces; once the
                   4925: application has been compiled, the header space is no longer
1.27      crook    4926: required@footnote{more strictly speaking, most applications can be
1.32      anton    4927: designed so that this is the case}. The header space can be deleted
1.29      crook    4928: entirely, or could be stored in memory on a remote @i{host} system for
1.27      crook    4929: debug and development purposes. In the latter case, the compiler running
1.29      crook    4930: on the @i{target} system could implement a protocol across a
1.32      anton    4931: communication link that would allow it to interrogate the header space.
1.27      crook    4932: @end itemize
                   4933: 
1.32      anton    4934: @node Dictionary allocation, Heap Allocation, Memory model, Memory
                   4935: @subsection Dictionary allocation
1.27      crook    4936: @cindex reserving data space
                   4937: @cindex data space - reserving some
                   4938: 
1.32      anton    4939: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
                   4940: you want to deallocate X, you also deallocate everything
                   4941: allocated after X.
                   4942: 
                   4943: The allocations using the words below are contiguous and grow the region
                   4944: towards increasing addresses.  Other words that allocate dictionary
                   4945: memory of any kind (i.e., defining words including @code{:noname}) end
                   4946: the contiguous region and start a new one.
                   4947: 
                   4948: In ANS Forth only @code{create}d words are guaranteed to produce an
                   4949: address that is the start of the following contiguous region.  In
                   4950: particular, the cell allocated by @code{variable} is not guaranteed to
                   4951: be contiguous with following @code{allot}ed memory.
                   4952: 
                   4953: You can deallocate memory by using @code{allot} with a negative argument
                   4954: (with some restrictions, see @code{allot}). For larger deallocations use
                   4955: @code{marker}.
1.27      crook    4956: 
1.29      crook    4957: 
1.27      crook    4958: doc-here
                   4959: doc-unused
                   4960: doc-allot
                   4961: doc-c,
1.29      crook    4962: doc-f,
1.27      crook    4963: doc-,
                   4964: doc-2,
1.29      crook    4965: @cindex user space
                   4966: doc-udp
                   4967: doc-uallot
1.27      crook    4968: 
1.32      anton    4969: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
                   4970: course you should allocate memory in an aligned way, too. I.e., before
                   4971: allocating allocating a cell, @code{here} must be cell-aligned, etc.
                   4972: The words below align @code{here} if it is not already.  Basically it is
                   4973: only already aligned for a type, if the last allocation was a multiple
                   4974: of the size of this type and if @code{here} was aligned for this type
                   4975: before.
                   4976: 
                   4977: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
                   4978: ANS Forth (@code{maxalign}ed in Gforth).
                   4979: 
                   4980: doc-align
                   4981: doc-falign
                   4982: doc-sfalign
                   4983: doc-dfalign
                   4984: doc-maxalign
                   4985: doc-cfalign
                   4986: 
                   4987: 
                   4988: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
                   4989: @subsection Heap allocation
                   4990: @cindex heap allocation
                   4991: @cindex dynamic allocation of memory
                   4992: @cindex memory-allocation word set
                   4993: 
                   4994: Heap allocation supports deallocation of allocated memory in any
                   4995: order. Dictionary allocation is not affected by it (i.e., it does not
                   4996: end a contiguous region). In Gforth, these words are implemented using
                   4997: the standard C library calls malloc(), free() and resize().
                   4998: 
                   4999: doc-allocate
                   5000: doc-free
                   5001: doc-resize
                   5002: 
1.27      crook    5003: 
1.32      anton    5004: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1       anton    5005: @subsection Memory Access
                   5006: @cindex memory access words
                   5007: 
1.44      crook    5008: 
1.1       anton    5009: doc-@
                   5010: doc-!
                   5011: doc-+!
                   5012: doc-c@
                   5013: doc-c!
                   5014: doc-2@
                   5015: doc-2!
                   5016: doc-f@
                   5017: doc-f!
                   5018: doc-sf@
                   5019: doc-sf!
                   5020: doc-df@
                   5021: doc-df!
                   5022: 
1.32      anton    5023: @node Address arithmetic, Memory Blocks, Memory Access, Memory
                   5024: @subsection Address arithmetic
1.1       anton    5025: @cindex address arithmetic words
                   5026: 
1.32      anton    5027: Address arithmetic is the foundation on which data structures like
                   5028: arrays, records (@pxref{Structures}) and objects (@pxref{Object-oriented
                   5029: Forth}) are built.
                   5030: 
1.1       anton    5031: ANS Forth does not specify the sizes of the data types. Instead, it
                   5032: offers a number of words for computing sizes and doing address
1.29      crook    5033: arithmetic. Address arithmetic is performed in terms of address units
                   5034: (aus); on most systems the address unit is one byte. Note that a
                   5035: character may have more than one au, so @code{chars} is no noop (on
                   5036: systems where it is a noop, it compiles to nothing).
1.1       anton    5037: 
                   5038: @cindex alignment of addresses for types
                   5039: ANS Forth also defines words for aligning addresses for specific
                   5040: types. Many computers require that accesses to specific data types
                   5041: must only occur at specific addresses; e.g., that cells may only be
                   5042: accessed at addresses divisible by 4. Even if a machine allows unaligned
                   5043: accesses, it can usually perform aligned accesses faster. 
                   5044: 
                   5045: For the performance-conscious: alignment operations are usually only
                   5046: necessary during the definition of a data structure, not during the
                   5047: (more frequent) accesses to it.
                   5048: 
                   5049: ANS Forth defines no words for character-aligning addresses. This is not
                   5050: an oversight, but reflects the fact that addresses that are not
                   5051: char-aligned have no use in the standard and therefore will not be
                   5052: created.
                   5053: 
                   5054: @cindex @code{CREATE} and alignment
1.29      crook    5055: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1       anton    5056: are cell-aligned; in addition, Gforth guarantees that these addresses
                   5057: are aligned for all purposes.
                   5058: 
1.26      crook    5059: Note that the ANS Forth word @code{char} has nothing to do with address
                   5060: arithmetic.
1.1       anton    5061: 
1.44      crook    5062: 
1.1       anton    5063: doc-chars
                   5064: doc-char+
                   5065: doc-cells
                   5066: doc-cell+
                   5067: doc-cell
                   5068: doc-aligned
                   5069: doc-floats
                   5070: doc-float+
                   5071: doc-float
                   5072: doc-faligned
                   5073: doc-sfloats
                   5074: doc-sfloat+
                   5075: doc-sfaligned
                   5076: doc-dfloats
                   5077: doc-dfloat+
                   5078: doc-dfaligned
                   5079: doc-maxaligned
                   5080: doc-cfaligned
                   5081: doc-address-unit-bits
                   5082: 
1.44      crook    5083: 
1.32      anton    5084: @node Memory Blocks,  , Address arithmetic, Memory
1.1       anton    5085: @subsection Memory Blocks
                   5086: @cindex memory block words
1.27      crook    5087: @cindex character strings - moving and copying
                   5088: 
                   5089: Memory blocks often represent character strings; @xref{String Formats}
                   5090: for ways of storing character strings in memory. @xref{Displaying
                   5091: characters and strings} for other string-processing words.
1.1       anton    5092: 
1.32      anton    5093: Some of these words work on address units. Others work on character
                   5094: units (increments of @code{CHAR}), and expect a @code{CHAR}-aligned
                   5095: address. Choose the correct operation depending upon your data type.
1.21      crook    5096: 
                   5097: When copying characters between overlapping memory regions, choose
                   5098: carefully between @code{cmove} and @code{cmove>}.
                   5099: 
1.29      crook    5100: You can only use any of these words @i{portably} to access data space.
1.21      crook    5101: 
1.27      crook    5102: @comment TODO - think the naming of the arguments is wrong for move
1.29      crook    5103: @comment well, really it seems to be the Standard that's wrong; it
                   5104: @comment describes MOVE as a word that requires a CELL-aligned source
                   5105: @comment and destination address but a xtranfer count that need not
                   5106: @comment be a multiple of CELL.
1.44      crook    5107: 
1.1       anton    5108: doc-move
                   5109: doc-erase
                   5110: doc-cmove
                   5111: doc-cmove>
                   5112: doc-fill
                   5113: doc-blank
1.21      crook    5114: doc-compare
                   5115: doc-search
1.27      crook    5116: doc--trailing
                   5117: doc-/string
                   5118: 
1.44      crook    5119: 
1.27      crook    5120: @comment TODO examples
                   5121: 
1.1       anton    5122: 
1.26      crook    5123: @node Control Structures, Defining Words, Memory, Words
1.1       anton    5124: @section Control Structures
                   5125: @cindex control structures
                   5126: 
1.33      anton    5127: Control structures in Forth cannot be used interpretively, only in a
                   5128: colon definition@footnote{To be precise, they have no interpretation
                   5129: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
                   5130: not like this limitation, but have not seen a satisfying way around it
                   5131: yet, although many schemes have been proposed.
1.1       anton    5132: 
                   5133: @menu
1.33      anton    5134: * Selection::                   IF ... ELSE ... ENDIF
                   5135: * Simple Loops::                BEGIN ...
1.29      crook    5136: * Counted Loops::               DO
                   5137: * Arbitrary control structures::
                   5138: * Calls and returns::
1.1       anton    5139: * Exception Handling::          
                   5140: @end menu
                   5141: 
                   5142: @node Selection, Simple Loops, Control Structures, Control Structures
                   5143: @subsection Selection
                   5144: @cindex selection control structures
                   5145: @cindex control structures for selection
                   5146: 
1.33      anton    5147: @c what's the purpose of all these @i? Maybe we should define a macro
                   5148: @c so we can produce logical markup.  - anton
                   5149: 
1.44      crook    5150: @c nac-> When I started working on the manual, a mixture of @i and @var
                   5151: @c were used inconsistently in code examples and \Glossary entries. These
                   5152: @c two behave differently in info format so I decided to standardize on @i.
                   5153: @c Logical markup would be better but texi isn't really upto it, and
                   5154: @c texi2html just ignores macros.
1.47      crook    5155: @c nac02dec1999-> update: the latest texinfo release can spit out html
                   5156: @c and it handles macros, so we could do some logical markup. Unfortunately
                   5157: @c texinfo will not split html output, which would be a big pain if you
                   5158: @c wanted to put the document on the web, which would be nice.
1.44      crook    5159: 
1.1       anton    5160: @cindex @code{IF} control structure
                   5161: @example
1.29      crook    5162: @i{flag}
1.1       anton    5163: IF
1.29      crook    5164:   @i{code}
1.1       anton    5165: ENDIF
                   5166: @end example
1.21      crook    5167: @noindent
1.33      anton    5168: 
1.44      crook    5169: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
                   5170: with any bit set represents truth) @i{code} is executed.
1.33      anton    5171: 
1.1       anton    5172: @example
1.29      crook    5173: @i{flag}
1.1       anton    5174: IF
1.29      crook    5175:   @i{code1}
1.1       anton    5176: ELSE
1.29      crook    5177:   @i{code2}
1.1       anton    5178: ENDIF
                   5179: @end example
                   5180: 
1.44      crook    5181: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
                   5182: executed.
1.33      anton    5183: 
1.1       anton    5184: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
                   5185: standard, and @code{ENDIF} is not, although it is quite popular. We
                   5186: recommend using @code{ENDIF}, because it is less confusing for people
                   5187: who also know other languages (and is not prone to reinforcing negative
                   5188: prejudices against Forth in these people). Adding @code{ENDIF} to a
                   5189: system that only supplies @code{THEN} is simple:
                   5190: @example
1.21      crook    5191: : ENDIF   POSTPONE THEN ; immediate
1.1       anton    5192: @end example
                   5193: 
                   5194: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
                   5195: (adv.)}  has the following meanings:
                   5196: @quotation
                   5197: ... 2b: following next after in order ... 3d: as a necessary consequence
                   5198: (if you were there, then you saw them).
                   5199: @end quotation
                   5200: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
                   5201: and many other programming languages has the meaning 3d.]
                   5202: 
1.21      crook    5203: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1       anton    5204: you can avoid using @code{?dup}. Using these alternatives is also more
1.26      crook    5205: efficient than using @code{?dup}. Definitions in ANS Forth
1.1       anton    5206: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
                   5207: @file{compat/control.fs}.
                   5208: 
                   5209: @cindex @code{CASE} control structure
                   5210: @example
1.29      crook    5211: @i{n}
1.1       anton    5212: CASE
1.29      crook    5213:   @i{n1} OF @i{code1} ENDOF
                   5214:   @i{n2} OF @i{code2} ENDOF
1.1       anton    5215:   @dots{}
                   5216: ENDCASE
                   5217: @end example
                   5218: 
1.29      crook    5219: Executes the first @i{codei}, where the @i{ni} is equal to
                   5220: @i{n}. A default case can be added by simply writing the code after
                   5221: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
1.1       anton    5222: but must not consume it.
                   5223: 
                   5224: @node Simple Loops, Counted Loops, Selection, Control Structures
                   5225: @subsection Simple Loops
                   5226: @cindex simple loops
                   5227: @cindex loops without count 
                   5228: 
                   5229: @cindex @code{WHILE} loop
                   5230: @example
                   5231: BEGIN
1.29      crook    5232:   @i{code1}
                   5233:   @i{flag}
1.1       anton    5234: WHILE
1.29      crook    5235:   @i{code2}
1.1       anton    5236: REPEAT
                   5237: @end example
                   5238: 
1.29      crook    5239: @i{code1} is executed and @i{flag} is computed. If it is true,
                   5240: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1       anton    5241: false, execution continues after the @code{REPEAT}.
                   5242: 
                   5243: @cindex @code{UNTIL} loop
                   5244: @example
                   5245: BEGIN
1.29      crook    5246:   @i{code}
                   5247:   @i{flag}
1.1       anton    5248: UNTIL
                   5249: @end example
                   5250: 
1.29      crook    5251: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1       anton    5252: 
                   5253: @cindex endless loop
                   5254: @cindex loops, endless
                   5255: @example
                   5256: BEGIN
1.29      crook    5257:   @i{code}
1.1       anton    5258: AGAIN
                   5259: @end example
                   5260: 
                   5261: This is an endless loop.
                   5262: 
                   5263: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
                   5264: @subsection Counted Loops
                   5265: @cindex counted loops
                   5266: @cindex loops, counted
                   5267: @cindex @code{DO} loops
                   5268: 
                   5269: The basic counted loop is:
                   5270: @example
1.29      crook    5271: @i{limit} @i{start}
1.1       anton    5272: ?DO
1.29      crook    5273:   @i{body}
1.1       anton    5274: LOOP
                   5275: @end example
                   5276: 
1.29      crook    5277: This performs one iteration for every integer, starting from @i{start}
                   5278: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21      crook    5279: accessed with @code{i}. For example, the loop:
1.1       anton    5280: @example
                   5281: 10 0 ?DO
                   5282:   i .
                   5283: LOOP
                   5284: @end example
1.21      crook    5285: @noindent
                   5286: prints @code{0 1 2 3 4 5 6 7 8 9}
                   5287: 
1.1       anton    5288: The index of the innermost loop can be accessed with @code{i}, the index
                   5289: of the next loop with @code{j}, and the index of the third loop with
                   5290: @code{k}.
                   5291: 
1.44      crook    5292: 
1.1       anton    5293: doc-i
                   5294: doc-j
                   5295: doc-k
                   5296: 
1.44      crook    5297: 
1.1       anton    5298: The loop control data are kept on the return stack, so there are some
1.21      crook    5299: restrictions on mixing return stack accesses and counted loop words. In
                   5300: particuler, if you put values on the return stack outside the loop, you
                   5301: cannot read them inside the loop@footnote{well, not in a way that is
                   5302: portable.}. If you put values on the return stack within a loop, you
                   5303: have to remove them before the end of the loop and before accessing the
                   5304: index of the loop.
1.1       anton    5305: 
                   5306: There are several variations on the counted loop:
                   5307: 
1.21      crook    5308: @itemize @bullet
                   5309: @item
                   5310: @code{LEAVE} leaves the innermost counted loop immediately; execution
                   5311: continues after the associated @code{LOOP} or @code{NEXT}. For example:
                   5312: 
                   5313: @example
                   5314: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
                   5315: @end example
                   5316: prints @code{0 1 2 3}
                   5317: 
1.1       anton    5318: 
1.21      crook    5319: @item
                   5320: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
                   5321: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
                   5322: return stack so @code{EXIT} can get to its return address. For example:
                   5323: 
                   5324: @example
                   5325: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
                   5326: @end example
                   5327: prints @code{0 1 2 3}
                   5328: 
                   5329: 
                   5330: @item
1.29      crook    5331: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1       anton    5332: (and @code{LOOP} iterates until they become equal by wrap-around
                   5333: arithmetic). This behaviour is usually not what you want. Therefore,
                   5334: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29      crook    5335: @code{?DO}), which do not enter the loop if @i{start} is greater than
                   5336: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1       anton    5337: unsigned loop parameters.
                   5338: 
1.21      crook    5339: @item
                   5340: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
                   5341: the loop, independent of the loop parameters. Do not use @code{DO}, even
                   5342: if you know that the loop is entered in any case. Such knowledge tends
                   5343: to become invalid during maintenance of a program, and then the
                   5344: @code{DO} will make trouble.
                   5345: 
                   5346: @item
1.29      crook    5347: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
                   5348: index by @i{n} instead of by 1. The loop is terminated when the border
                   5349: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1       anton    5350: 
1.21      crook    5351: @example
                   5352: 4 0 +DO  i .  2 +LOOP
                   5353: @end example
                   5354: @noindent
                   5355: prints @code{0 2}
                   5356: 
                   5357: @example
                   5358: 4 1 +DO  i .  2 +LOOP
                   5359: @end example
                   5360: @noindent
                   5361: prints @code{1 3}
1.1       anton    5362: 
                   5363: 
                   5364: @cindex negative increment for counted loops
                   5365: @cindex counted loops with negative increment
1.29      crook    5366: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1       anton    5367: 
1.21      crook    5368: @example
                   5369: -1 0 ?DO  i .  -1 +LOOP
                   5370: @end example
                   5371: @noindent
                   5372: prints @code{0 -1}
1.1       anton    5373: 
1.21      crook    5374: @example
                   5375: 0 0 ?DO  i .  -1 +LOOP
                   5376: @end example
                   5377: prints nothing.
1.1       anton    5378: 
1.29      crook    5379: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
                   5380: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
                   5381: index by @i{u} each iteration. The loop is terminated when the border
                   5382: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1       anton    5383: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
                   5384: 
1.21      crook    5385: @example
                   5386: -2 0 -DO  i .  1 -LOOP
                   5387: @end example
                   5388: @noindent
                   5389: prints @code{0 -1}
1.1       anton    5390: 
1.21      crook    5391: @example
                   5392: -1 0 -DO  i .  1 -LOOP
                   5393: @end example
                   5394: @noindent
                   5395: prints @code{0}
                   5396: 
                   5397: @example
                   5398: 0 0 -DO  i .  1 -LOOP
                   5399: @end example
                   5400: @noindent
                   5401: prints nothing.
1.1       anton    5402: 
1.21      crook    5403: @end itemize
1.1       anton    5404: 
                   5405: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26      crook    5406: @code{-LOOP} are not defined in ANS Forth. However, an implementation
                   5407: for these words that uses only standard words is provided in
                   5408: @file{compat/loops.fs}.
1.1       anton    5409: 
                   5410: 
                   5411: @cindex @code{FOR} loops
1.26      crook    5412: Another counted loop is:
1.1       anton    5413: @example
1.29      crook    5414: @i{n}
1.1       anton    5415: FOR
1.29      crook    5416:   @i{body}
1.1       anton    5417: NEXT
                   5418: @end example
                   5419: This is the preferred loop of native code compiler writers who are too
1.26      crook    5420: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29      crook    5421: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
                   5422: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26      crook    5423: Forth systems may behave differently, even if they support @code{FOR}
                   5424: loops. To avoid problems, don't use @code{FOR} loops.
1.1       anton    5425: 
                   5426: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
                   5427: @subsection Arbitrary control structures
                   5428: @cindex control structures, user-defined
                   5429: 
                   5430: @cindex control-flow stack
                   5431: ANS Forth permits and supports using control structures in a non-nested
                   5432: way. Information about incomplete control structures is stored on the
                   5433: control-flow stack. This stack may be implemented on the Forth data
                   5434: stack, and this is what we have done in Gforth.
                   5435: 
                   5436: @cindex @code{orig}, control-flow stack item
                   5437: @cindex @code{dest}, control-flow stack item
                   5438: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
                   5439: entry represents a backward branch target. A few words are the basis for
                   5440: building any control structure possible (except control structures that
                   5441: need storage, like calls, coroutines, and backtracking).
                   5442: 
1.44      crook    5443: 
1.1       anton    5444: doc-if
                   5445: doc-ahead
                   5446: doc-then
                   5447: doc-begin
                   5448: doc-until
                   5449: doc-again
                   5450: doc-cs-pick
                   5451: doc-cs-roll
                   5452: 
1.44      crook    5453: 
1.21      crook    5454: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
                   5455: manipulate the control-flow stack in a portable way. Without them, you
                   5456: would need to know how many stack items are occupied by a control-flow
                   5457: entry (many systems use one cell. In Gforth they currently take three,
                   5458: but this may change in the future).
                   5459: 
1.1       anton    5460: Some standard control structure words are built from these words:
                   5461: 
1.44      crook    5462: 
1.1       anton    5463: doc-else
                   5464: doc-while
                   5465: doc-repeat
                   5466: 
1.44      crook    5467: 
                   5468: @noindent
1.1       anton    5469: Gforth adds some more control-structure words:
                   5470: 
1.44      crook    5471: 
1.1       anton    5472: doc-endif
                   5473: doc-?dup-if
                   5474: doc-?dup-0=-if
                   5475: 
1.44      crook    5476: 
                   5477: @noindent
1.1       anton    5478: Counted loop words constitute a separate group of words:
                   5479: 
1.44      crook    5480: 
1.1       anton    5481: doc-?do
                   5482: doc-+do
                   5483: doc-u+do
                   5484: doc--do
                   5485: doc-u-do
                   5486: doc-do
                   5487: doc-for
                   5488: doc-loop
                   5489: doc-+loop
                   5490: doc--loop
                   5491: doc-next
                   5492: doc-leave
                   5493: doc-?leave
                   5494: doc-unloop
                   5495: doc-done
                   5496: 
1.44      crook    5497: 
1.21      crook    5498: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
                   5499: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1       anton    5500: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
                   5501: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
                   5502: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
                   5503: resolved (by using one of the loop-ending words or @code{DONE}).
                   5504: 
1.44      crook    5505: @noindent
1.26      crook    5506: Another group of control structure words are:
1.1       anton    5507: 
1.44      crook    5508: 
1.1       anton    5509: doc-case
                   5510: doc-endcase
                   5511: doc-of
                   5512: doc-endof
                   5513: 
1.44      crook    5514: 
1.21      crook    5515: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
                   5516: @code{CS-ROLL}.
1.1       anton    5517: 
                   5518: @subsubsection Programming Style
1.47      crook    5519: @cindex control structures programming style
                   5520: @cindex programming style, arbitrary control structures
1.1       anton    5521: 
                   5522: In order to ensure readability we recommend that you do not create
                   5523: arbitrary control structures directly, but define new control structure
                   5524: words for the control structure you want and use these words in your
1.26      crook    5525: program. For example, instead of writing:
1.1       anton    5526: 
                   5527: @example
1.26      crook    5528: BEGIN
1.1       anton    5529:   ...
1.26      crook    5530: IF [ 1 CS-ROLL ]
1.1       anton    5531:   ...
1.26      crook    5532: AGAIN THEN
1.1       anton    5533: @end example
                   5534: 
1.21      crook    5535: @noindent
1.1       anton    5536: we recommend defining control structure words, e.g.,
                   5537: 
                   5538: @example
1.26      crook    5539: : WHILE ( DEST -- ORIG DEST )
                   5540:  POSTPONE IF
                   5541:  1 CS-ROLL ; immediate
                   5542: 
                   5543: : REPEAT ( orig dest -- )
                   5544:  POSTPONE AGAIN
                   5545:  POSTPONE THEN ; immediate
1.1       anton    5546: @end example
                   5547: 
1.21      crook    5548: @noindent
1.1       anton    5549: and then using these to create the control structure:
                   5550: 
                   5551: @example
1.26      crook    5552: BEGIN
1.1       anton    5553:   ...
1.26      crook    5554: WHILE
1.1       anton    5555:   ...
1.26      crook    5556: REPEAT
1.1       anton    5557: @end example
                   5558: 
                   5559: That's much easier to read, isn't it? Of course, @code{REPEAT} and
                   5560: @code{WHILE} are predefined, so in this example it would not be
                   5561: necessary to define them.
                   5562: 
                   5563: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
                   5564: @subsection Calls and returns
                   5565: @cindex calling a definition
                   5566: @cindex returning from a definition
                   5567: 
1.3       anton    5568: @cindex recursive definitions
                   5569: A definition can be called simply be writing the name of the definition
1.26      crook    5570: to be called. Normally a definition is invisible during its own
1.3       anton    5571: definition. If you want to write a directly recursive definition, you
1.26      crook    5572: can use @code{recursive} to make the current definition visible, or
                   5573: @code{recurse} to call the current definition directly.
1.3       anton    5574: 
1.44      crook    5575: 
1.3       anton    5576: doc-recursive
                   5577: doc-recurse
                   5578: 
1.44      crook    5579: 
1.21      crook    5580: @comment TODO add example of the two recursion methods
1.12      anton    5581: @quotation
                   5582: @progstyle
                   5583: I prefer using @code{recursive} to @code{recurse}, because calling the
                   5584: definition by name is more descriptive (if the name is well-chosen) than
                   5585: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
                   5586: implementation, it is much better to read (and think) ``now sort the
                   5587: partitions'' than to read ``now do a recursive call''.
                   5588: @end quotation
1.3       anton    5589: 
1.29      crook    5590: For mutual recursion, use @code{Defer}red words, like this:
1.3       anton    5591: 
                   5592: @example
1.28      crook    5593: Defer foo
1.3       anton    5594: 
                   5595: : bar ( ... -- ... )
                   5596:  ... foo ... ;
                   5597: 
                   5598: :noname ( ... -- ... )
                   5599:  ... bar ... ;
                   5600: IS foo
                   5601: @end example
                   5602: 
1.44      crook    5603: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33      anton    5604: 
1.26      crook    5605: The current definition returns control to the calling definition when
1.33      anton    5606: the end of the definition is reached or @code{EXIT} is encountered.
1.1       anton    5607: 
                   5608: doc-exit
                   5609: doc-;s
                   5610: 
1.44      crook    5611: 
1.1       anton    5612: @node Exception Handling,  , Calls and returns, Control Structures
                   5613: @subsection Exception Handling
1.26      crook    5614: @cindex exceptions
1.1       anton    5615: 
1.26      crook    5616: If your program detects a fatal error condition, the simplest action
                   5617: that it can take is to @code{quit}. This resets the return stack and
                   5618: restarts the text interpreter, but does not print any error message.
1.21      crook    5619: 
1.26      crook    5620: The next stage in severity is to execute @code{abort}, which has the
                   5621: same effect as @code{quit}, with the addition that it resets the data
                   5622: stack.
1.1       anton    5623: 
1.26      crook    5624: A slightly more sophisticated approach is use use @code{abort"}, which
                   5625: compiles a string to be used as an error message and does a conditional
                   5626: @code{abort} at run-time. For example:
1.1       anton    5627: 
1.26      crook    5628: @example
1.30      anton    5629: @kbd{: checker abort" That flag was true" ." A false flag" ;@key{RET}}  ok
                   5630: @kbd{0 checker@key{RET}} A false flag ok
                   5631: @kbd{1 checker@key{RET}}
1.26      crook    5632: :1: That flag was true
                   5633: 1 checker
                   5634:   ^^^^^^^
                   5635: $400D1648 throw 
                   5636: $400E4660
                   5637: @end example
1.1       anton    5638: 
1.26      crook    5639: These simple techniques allow a program to react to a fatal error
                   5640: condition, but they are not exactly user-friendly. The ANS Forth
                   5641: Exception word set provides the pair of words @code{throw} and
                   5642: @code{catch}, which can be used to provide sophisticated error-handling.
1.1       anton    5643: 
1.26      crook    5644: @code{catch} has a similar behaviour to @code{execute}, in that it takes
1.29      crook    5645: an @i{xt} as a parameter and starts execution of the xt. However,
1.26      crook    5646: before passing control to the xt, @code{catch} pushes an
1.29      crook    5647: @dfn{exception frame} onto the @dfn{exception stack}. This exception
1.26      crook    5648: frame is used to restore the system to a known state if a detected error
                   5649: occurs during the execution of the xt. A typical way to use @code{catch}
                   5650: would be:
1.1       anton    5651: 
1.26      crook    5652: @example
                   5653: ... ['] foo catch IF ...
                   5654: @end example
1.1       anton    5655: 
1.33      anton    5656: @c TOS is undefined. - anton
1.44      crook    5657: 
                   5658: @c nac-> TODO -- I need to look at this example again.
                   5659: 
1.26      crook    5660: Whilst @code{foo} executes, it can call other words to any level of
                   5661: nesting, as usual.  If @code{foo} (and all the words that it calls)
1.33      anton    5662: execute successfully, control will ultimately pass to the word following
                   5663: the @code{catch}, and there will be a 0 at TOS.  However, if any word
                   5664: detects an error, it can terminate the execution of @code{foo} by
                   5665: pushing a non-zero error code onto the stack and then performing a
                   5666: @code{throw}. The execution of @code{throw} will pass control to the
                   5667: word following the @code{catch}, but this time the TOS will hold the
                   5668: error code. Therefore, the @code{IF} in the example can be used to
                   5669: determine whether @code{foo} executed successfully.
1.1       anton    5670: 
1.26      crook    5671: This simple example shows how you can use @code{throw} and @code{catch}
                   5672: to ``take over'' exception handling from the system:
1.1       anton    5673: @example
1.26      crook    5674: : my-div ['] / catch if ." DIVIDE ERROR" else ." OK.. " . then ;
1.1       anton    5675: @end example
                   5676: 
1.26      crook    5677: The next example is more sophisticated and shows a multi-level
                   5678: @code{throw} and @code{catch}. To understand this example, start at the
                   5679: definition of @code{top-level} and work backwards:
                   5680: 
1.1       anton    5681: @example
1.26      crook    5682: : lowest-level ( -- c )
                   5683:     key dup 27 = if
1.44      crook    5684:         1 throw \ ESCAPE key pressed
1.26      crook    5685:     else
1.44      crook    5686:         ." lowest-level successful" CR
1.26      crook    5687:     then
                   5688: ;
                   5689: 
                   5690: : lower-level ( -- c )
                   5691:     lowest-level
                   5692:     \ at this level consider a CTRL-U to be a fatal error
                   5693:     dup 21 = if \ CTRL-U
1.44      crook    5694:         2 throw
1.26      crook    5695:     else
1.44      crook    5696:         ." lower-level successful" CR
1.26      crook    5697:     then
                   5698: ;
                   5699: 
                   5700: : low-level ( -- c )
                   5701:     ['] lower-level catch
                   5702:     ?dup if
1.44      crook    5703:         \ error occurred - do we recognise it?
                   5704:         dup 1 = if
                   5705:             \ ESCAPE key pressed.. pretend it was an E
                   5706:             [char] E
                   5707:         else throw \ propogate the error upwards
                   5708:         then
1.26      crook    5709:     then
                   5710:     ." low-level successfull" CR
                   5711: ;
                   5712: 
                   5713: : top-level ( -- )
                   5714:     CR ['] low-level catch \ CATCH is used like EXECUTE
                   5715:     ?dup if \ error occurred..
1.44      crook    5716:         ." Error " . ." occurred - contact your supplier"
1.26      crook    5717:     else
1.44      crook    5718:         ." The '" emit ." ' key was pressed" CR
1.26      crook    5719:     then
                   5720: ;
1.1       anton    5721: @end example
                   5722: 
1.26      crook    5723: The ANS Forth document assigns @code{throw} codes thus:
1.1       anton    5724: 
1.26      crook    5725: @itemize @bullet
                   5726: @item
                   5727: codes in the range -1 -- -255 are reserved to be assigned by the
                   5728: Standard. Assignments for codes in the range -1 -- -58 are currently
                   5729: documented in the Standard. In particular, @code{-1 throw} is equivalent
                   5730: to @code{abort} and @code{-2 throw} is equivalent to @code{abort"}.
                   5731: @item
                   5732: codes in the range -256 -- -4095 are reserved to be assigned by the system.
                   5733: @item
                   5734: all other codes may be assigned by programs.
                   5735: @end itemize
1.1       anton    5736: 
1.26      crook    5737: Gforth provides the word @code{exception} as a mechanism for assigning
                   5738: system throw codes to applications. This allows multiple applications to
                   5739: co-exist in memory without any clash of @code{throw} codes. A definition
                   5740: of @code{exception} in ANS Forth is provided in
                   5741: @file{compat/exception.fs}.
1.1       anton    5742: 
1.44      crook    5743: 
1.26      crook    5744: doc-quit
                   5745: doc-abort
                   5746: doc-abort"
1.1       anton    5747: 
1.26      crook    5748: doc-catch
1.29      crook    5749: doc-throw
                   5750: doc---exception-exception
                   5751: 
                   5752: 
1.44      crook    5753: 
1.29      crook    5754: @c -------------------------------------------------------------
1.47      crook    5755: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29      crook    5756: @section Defining Words
                   5757: @cindex defining words
                   5758: 
1.47      crook    5759: Defining words are used to extend Forth by creating new entries in the dictionary.
                   5760: 
1.29      crook    5761: @menu
1.44      crook    5762: * CREATE::
                   5763: * Variables::                   Variables and user variables
                   5764: * Constants::
                   5765: * Values::                      Initialised variables
1.29      crook    5766: * Colon Definitions::
1.44      crook    5767: * Anonymous Definitions::       Definitions without names
1.29      crook    5768: * User-defined Defining Words::
1.44      crook    5769: * Deferred words::              Allow forward references
                   5770: * Aliases::
1.29      crook    5771: * Supplying names::
                   5772: @end menu
                   5773: 
1.44      crook    5774: @node CREATE, Variables, Defining Words, Defining Words
                   5775: @subsection @code{CREATE}
1.29      crook    5776: @cindex simple defining words
                   5777: @cindex defining words, simple
                   5778: 
                   5779: Defining words are used to create new entries in the dictionary. The
                   5780: simplest defining word is @code{CREATE}. @code{CREATE} is used like
                   5781: this:
                   5782: 
                   5783: @example
                   5784: CREATE new-word1
                   5785: @end example
                   5786: 
                   5787: @code{CREATE} is a parsing word that generates a dictionary entry for
                   5788: @code{new-word1}. When @code{new-word1} is executed, all that it does is
                   5789: leave an address on the stack. The address represents the value of
                   5790: the data space pointer (@code{HERE}) at the time that @code{new-word1}
                   5791: was defined. Therefore, @code{CREATE} is a way of associating a name
                   5792: with the address of a region of memory.
                   5793: 
1.34      anton    5794: doc-create
                   5795: 
1.29      crook    5796: By extending this example to reserve some memory in data space, we end
                   5797: up with a @i{variable}. Here are two different ways to do it:
                   5798: 
                   5799: @example
                   5800: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
                   5801: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
                   5802: @end example
                   5803: 
                   5804: The variable can be examined and modified using @code{@@} (``fetch'') and
                   5805: @code{!} (``store'') like this:
                   5806: 
                   5807: @example
                   5808: new-word2 @@ .      \ get address, fetch from it and display
                   5809: 1234 new-word2 !   \ new value, get address, store to it
                   5810: @end example
                   5811: 
1.44      crook    5812: @cindex arrays
                   5813: A similar mechanism can be used to create arrays. For example, an
                   5814: 80-character text input buffer:
1.29      crook    5815: 
                   5816: @example
1.44      crook    5817: CREATE text-buf 80 chars allot
                   5818: 
                   5819: text-buf 0 chars c@@ \ the 1st character (offset 0)
                   5820: text-buf 3 chars c@@ \ the 4th character (offset 3)
                   5821: @end example
1.29      crook    5822: 
1.44      crook    5823: You can build arbitrarily complex data structures by allocating
                   5824: appropriate areas of memory. @xref{Structures} for further discussions
                   5825: of this, and to learn about some Gforth tools that make it easier.
                   5826: 
                   5827: 
                   5828: @node Variables, Constants, CREATE, Defining Words
                   5829: @subsection Variables
                   5830: @cindex variables
                   5831: 
                   5832: The previous section showed how a sequence of commands could be used to
                   5833: generate a variable.  As a final refinement, the whole code sequence can
                   5834: be wrapped up in a defining word (pre-empting the subject of the next
                   5835: section), making it easier to create new variables:
                   5836: 
                   5837: @example
                   5838: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
                   5839: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
                   5840: 
                   5841: myvariableX foo \ variable foo starts off with an unknown value
                   5842: myvariable0 joe \ whilst joe is initialised to 0
1.29      crook    5843: 
                   5844: 45 3 * foo !   \ set foo to 135
                   5845: 1234 joe !     \ set joe to 1234
                   5846: 3 joe +!       \ increment joe by 3.. to 1237
                   5847: @end example
                   5848: 
                   5849: Not surprisingly, there is no need to define @code{myvariable}, since
1.44      crook    5850: Forth already has a definition @code{Variable}. ANS Forth does not
                   5851: require a @code{Variable} to be initialised when it is created (i.e., it
                   5852: behaves like @code{myvariableX}). In contrast, Gforth's @code{Variable}
                   5853: initialises the variable to 0 (i.e., it behaves exactly like
                   5854: @code{myvariable0}). Forth also provides @code{2Variable} and
1.47      crook    5855: @code{fvariable} for double and floating-point variables, respectively
                   5856: -- both are initialised to 0 in Gforth. If you use a @code{Variable} to
                   5857: store a boolean, you can use @code{on} and @code{off} to toggle its
                   5858: state.
1.29      crook    5859: 
1.34      anton    5860: doc-variable
                   5861: doc-2variable
                   5862: doc-fvariable
                   5863: 
1.29      crook    5864: @cindex user variables
                   5865: @cindex user space
                   5866: The defining word @code{User} behaves in the same way as @code{Variable}.
                   5867: The difference is that it reserves space in @i{user (data) space} rather
                   5868: than normal data space. In a Forth system that has a multi-tasker, each
                   5869: task has its own set of user variables.
                   5870: 
1.34      anton    5871: doc-user
                   5872: 
1.29      crook    5873: @comment TODO is that stuff about user variables strictly correct? Is it
                   5874: @comment just terminal tasks that have user variables?
                   5875: @comment should document tasker.fs (with some examples) elsewhere
                   5876: @comment in this manual, then expand on user space and user variables.
                   5877: 
1.44      crook    5878: 
                   5879: @node Constants, Values, Variables, Defining Words
                   5880: @subsection Constants
                   5881: @cindex constants
                   5882: 
                   5883: @code{Constant} allows you to declare a fixed value and refer to it by
                   5884: name. For example:
1.29      crook    5885: 
                   5886: @example
                   5887: 12 Constant INCHES-PER-FOOT
                   5888: 3E+08 fconstant SPEED-O-LIGHT
                   5889: @end example
                   5890: 
                   5891: A @code{Variable} can be both read and written, so its run-time
                   5892: behaviour is to supply an address through which its current value can be
                   5893: manipulated. In contrast, the value of a @code{Constant} cannot be
                   5894: changed once it has been declared@footnote{Well, often it can be -- but
                   5895: not in a Standard, portable way. It's safer to use a @code{Value} (read
                   5896: on).} so it's not necessary to supply the address -- it is more
                   5897: efficient to return the value of the constant directly. That's exactly
                   5898: what happens; the run-time effect of a constant is to put its value on
                   5899: the top of the stack (@ref{User-defined Defining Words} describes one
                   5900: way of implementing @code{Constant}).
                   5901: 
                   5902: Gforth also provides @code{2Constant} and @code{fconstant} for defining
                   5903: double and floating-point constants, respectively.
                   5904: 
1.34      anton    5905: doc-constant
                   5906: doc-2constant
                   5907: doc-fconstant
                   5908: 
                   5909: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44      crook    5910: @c nac-> How could that not be true in an ANS Forth? You can't define a
                   5911: @c constant, use it and then delete the definition of the constant..
                   5912: @c I agree that it's rather deep, but IMO it is an important difference
                   5913: @c relative to other programming languages.. often it's annoying: it
                   5914: @c certainly changes my programming style relative to C.
                   5915: 
1.29      crook    5916: Constants in Forth behave differently from their equivalents in other
                   5917: programming languages. In other languages, a constant (such as an EQU in
                   5918: assembler or a #define in C) only exists at compile-time; in the
                   5919: executable program the constant has been translated into an absolute
                   5920: number and, unless you are using a symbolic debugger, it's impossible to
                   5921: know what abstract thing that number represents. In Forth a constant has
1.44      crook    5922: an entry in the header space and remains there after the code that uses
                   5923: it has been defined. In fact, it must remain in the dictionary since it
                   5924: has run-time duties to perform. For example:
1.29      crook    5925: 
                   5926: @example
                   5927: 12 Constant INCHES-PER-FOOT
                   5928: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
                   5929: @end example
                   5930: 
                   5931: @cindex in-lining of constants
                   5932: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
                   5933: associated with the constant @code{INCHES-PER-FOOT}. If you use
                   5934: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
                   5935: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
                   5936: attempt to optimise constants by in-lining them where they are used. You
                   5937: can force Gforth to in-line a constant like this:
                   5938: 
                   5939: @example
                   5940: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
                   5941: @end example
                   5942: 
                   5943: If you use @code{see} to decompile @i{this} version of
                   5944: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.33      anton    5945: longer present. @xref{Interpret/Compile states} and @ref{Literals} on
                   5946: how this works.
1.29      crook    5947: 
                   5948: In-lining constants in this way might improve execution time
                   5949: fractionally, and can ensure that a constant is now only referenced at
                   5950: compile-time. However, the definition of the constant still remains in
                   5951: the dictionary. Some Forth compilers provide a mechanism for controlling
                   5952: a second dictionary for holding transient words such that this second
                   5953: dictionary can be deleted later in order to recover memory
                   5954: space. However, there is no standard way of doing this.
                   5955: 
                   5956: 
1.44      crook    5957: @node Values, Colon Definitions, Constants, Defining Words
                   5958: @subsection Values
                   5959: @cindex values
1.34      anton    5960: 
1.44      crook    5961: A @code{Value} is like a @code{Variable} but with two important
                   5962: differences:
1.29      crook    5963: 
                   5964: @itemize @bullet
                   5965: @item
1.44      crook    5966: A @code{Value} is initialised when it is declared; like a
                   5967: @code{Constant} but unlike a @code{Variable}.
1.29      crook    5968: @item
1.44      crook    5969: A @code{Value} returns its value rather than its address when it is
                   5970: executed; i.e., it has the same run-time behaviour as @code{Constant}.
1.29      crook    5971: @end itemize
                   5972: 
1.44      crook    5973: A @code{Value} needs an additional word, @code{TO} to allow its value to
                   5974: be changed. Here are some examples:
1.29      crook    5975: 
                   5976: @example
1.44      crook    5977: 12 Value APPLES \ Define APPLES with an initial value of 12
                   5978: 34 TO APPLES    \ Change the value of APPLES. TO is a parsing word
                   5979: APPLES          \ puts 34 on the top of the stack.
1.29      crook    5980: @end example
                   5981: 
1.44      crook    5982: doc-value
                   5983: doc-to
1.29      crook    5984: 
1.35      anton    5985: 
1.44      crook    5986: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
                   5987: @subsection Colon Definitions
                   5988: @cindex colon definitions
1.35      anton    5989: 
                   5990: @example
1.44      crook    5991: : name ( ... -- ... )
                   5992:     word1 word2 word3 ;
1.29      crook    5993: @end example
                   5994: 
1.44      crook    5995: @noindent
                   5996: Creates a word called @code{name} that, upon execution, executes
                   5997: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29      crook    5998: 
1.44      crook    5999: The explanation above is somewhat superficial. @xref{Your first
                   6000: definition} for simple examples of colon definitions, then
                   6001: @xref{Interpretation and Compilation Semantics} for an in-depth
                   6002: discussion of some of the issues involved.
1.29      crook    6003: 
1.44      crook    6004: doc-:
                   6005: doc-;
1.1       anton    6006: 
1.34      anton    6007: 
1.44      crook    6008: @node Anonymous Definitions, User-defined Defining Words, Colon Definitions, Defining Words
                   6009: @subsection Anonymous Definitions
                   6010: @cindex colon definitions
                   6011: @cindex defining words without name
1.34      anton    6012: 
1.44      crook    6013: Sometimes you want to define an @dfn{anonymous word}; a word without a
                   6014: name. You can do this with:
1.1       anton    6015: 
1.44      crook    6016: doc-:noname
1.1       anton    6017: 
1.44      crook    6018: This leaves the execution token for the word on the stack after the
                   6019: closing @code{;}. Here's an example in which a deferred word is
                   6020: initialised with an @code{xt} from an anonymous colon definition:
1.1       anton    6021: 
1.29      crook    6022: @example
1.44      crook    6023: Defer deferred
                   6024: :noname ( ... -- ... )
                   6025:   ... ;
                   6026: IS deferred
1.29      crook    6027: @end example
1.26      crook    6028: 
1.44      crook    6029: @noindent
                   6030: Gforth provides an alternative way of doing this, using two separate
                   6031: words:
1.27      crook    6032: 
1.44      crook    6033: doc-noname
                   6034: @cindex execution token of last defined word
                   6035: doc-lastxt
1.1       anton    6036: 
1.44      crook    6037: @noindent
                   6038: The previous example can be rewritten using @code{noname} and
                   6039: @code{lastxt}:
1.1       anton    6040: 
1.26      crook    6041: @example
1.44      crook    6042: Defer deferred
                   6043: noname : ( ... -- ... )
                   6044:   ... ;
                   6045: lastxt IS deferred
1.26      crook    6046: @end example
1.1       anton    6047: 
1.29      crook    6048: @noindent
1.44      crook    6049: @code{noname} works with any defining word, not just @code{:}.
                   6050: 
                   6051: @code{lastxt} also works when the last word was not defined as
                   6052: @code{noname}. It also has the useful property that is is valid as soon
                   6053: as the header for a definition has been built. Thus:
                   6054: 
                   6055: @example
                   6056: lastxt . : foo [ lastxt . ] ; ' foo .
                   6057: @end example
1.1       anton    6058: 
1.44      crook    6059: @noindent
                   6060: prints 3 numbers; the last two are the same.
1.26      crook    6061: 
1.1       anton    6062: 
1.44      crook    6063: @node User-defined Defining Words, Deferred words, Anonymous Definitions, Defining Words
1.26      crook    6064: @subsection User-defined Defining Words
                   6065: @cindex user-defined defining words
                   6066: @cindex defining words, user-defined
1.1       anton    6067: 
1.29      crook    6068: You can create a new defining word by wrapping defining-time code around
                   6069: an existing defining word and putting the sequence in a colon
                   6070: definition. For example, suppose that you have a word @code{stats} that
                   6071: gathers statistics about colon definitions given the @i{xt} of the
                   6072: definition, and you want every colon definition in your application to
                   6073: make a call to @code{stats}. You can define and use a new version of
                   6074: @code{:} like this:
                   6075: 
                   6076: @example
                   6077: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
                   6078:   ... ;  \ other code
                   6079: 
                   6080: : my: : lastxt postpone literal ['] stats compile, ;
                   6081: 
                   6082: my: foo + - ;
                   6083: @end example
                   6084: 
                   6085: When @code{foo} is defined using @code{my:} these steps occur:
                   6086: 
                   6087: @itemize @bullet
                   6088: @item
                   6089: @code{my:} is executed.
                   6090: @item
                   6091: The @code{:} within the definition (the one between @code{my:} and
                   6092: @code{lastxt}) is executed, and does just what it always does; it parses
                   6093: the input stream for a name, builds a dictionary header for the name
                   6094: @code{foo} and switches @code{state} from interpret to compile.
                   6095: @item
                   6096: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
                   6097: being defined -- @code{foo} -- onto the stack.
                   6098: @item
                   6099: The code that was produced by @code{postpone literal} is executed; this
                   6100: causes the value on the stack to be compiled as a literal in the code
                   6101: area of @code{foo}.
                   6102: @item
                   6103: The code @code{['] stats} compiles a literal into the definition of
                   6104: @code{my:}. When @code{compile,} is executed, that literal -- the
                   6105: execution token for @code{stats} -- is layed down in the code area of
                   6106: @code{foo} , following the literal@footnote{Strictly speaking, the
                   6107: mechanism that @code{compile,} uses to convert an @i{xt} into something
                   6108: in the code area is implementation-dependent. A threaded implementation
                   6109: might spit out the execution token directly whilst another
                   6110: implementation might spit out a native code sequence.}.
                   6111: @item
                   6112: At this point, the execution of @code{my:} is complete, and control
                   6113: returns to the text interpreter. The text interpreter is in compile
                   6114: state, so subsequent text @code{+ -} is compiled into the definition of
                   6115: @code{foo} and the @code{;} terminates the definition as always.
                   6116: @end itemize
                   6117: 
                   6118: You can use @code{see} to decompile a word that was defined using
                   6119: @code{my:} and see how it is different from a normal @code{:}
                   6120: definition. For example:
                   6121: 
                   6122: @example
                   6123: : bar + - ;  \ like foo but using : rather than my:
                   6124: see bar
                   6125: : bar
                   6126:   + - ;
                   6127: see foo
                   6128: : foo
                   6129:   107645672 stats + - ;
                   6130: 
                   6131: \ use ' stats . to show that 107645672 is the xt for stats
                   6132: @end example
                   6133: 
                   6134: You can use techniques like this to make new defining words in terms of
                   6135: @i{any} existing defining word.
1.1       anton    6136: 
                   6137: 
1.29      crook    6138: @cindex defining defining words
1.26      crook    6139: @cindex @code{CREATE} ... @code{DOES>}
                   6140: If you want the words defined with your defining words to behave
                   6141: differently from words defined with standard defining words, you can
                   6142: write your defining word like this:
1.1       anton    6143: 
                   6144: @example
1.26      crook    6145: : def-word ( "name" -- )
1.29      crook    6146:     CREATE @i{code1}
1.26      crook    6147: DOES> ( ... -- ... )
1.29      crook    6148:     @i{code2} ;
1.26      crook    6149: 
                   6150: def-word name
1.1       anton    6151: @end example
                   6152: 
1.29      crook    6153: @cindex child words
                   6154: This fragment defines a @dfn{defining word} @code{def-word} and then
                   6155: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
                   6156: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
                   6157: is not executed at this time. The word @code{name} is sometimes called a
                   6158: @dfn{child} of @code{def-word}.
                   6159: 
                   6160: When you execute @code{name}, the address of the body of @code{name} is
                   6161: put on the data stack and @i{code2} is executed (the address of the body
                   6162: of @code{name} is the address @code{HERE} returns immediately after the
                   6163: @code{CREATE}).
                   6164: 
                   6165: @cindex atavism in child words
1.33      anton    6166: You can use @code{def-word} to define a set of child words that behave
1.29      crook    6167: differently, though atavistically; they all have a common run-time
                   6168: behaviour determined by @i{code2}. Typically, the @i{code1} sequence
                   6169: builds a data area in the body of the child word. The structure of the
                   6170: data is common to all children of @code{def-word}, but the data values
                   6171: are specific -- and private -- to each child word. When a child word is
                   6172: executed, the address of its private data area is passed as a parameter
                   6173: on TOS to be used and manipulated@footnote{It is legitimate both to read
                   6174: and write to this data area.} by @i{code2}.
                   6175: 
                   6176: The two fragments of code that make up the defining words act (are
                   6177: executed) at two completely separate times:
1.1       anton    6178: 
1.29      crook    6179: @itemize @bullet
                   6180: @item
                   6181: At @i{define time}, the defining word executes @i{code1} to generate a
                   6182: child word
                   6183: @item
                   6184: At @i{child execution time}, when a child word is invoked, @i{code2}
                   6185: is executed, using parameters (data) that are private and specific to
                   6186: the child word.
                   6187: @end itemize
                   6188: 
1.44      crook    6189: Another way of understanding the behaviour of @code{def-word} and
                   6190: @code{name} is to say that, if you make the following definitions:
1.33      anton    6191: @example
                   6192: : def-word1 ( "name" -- )
                   6193:     CREATE @i{code1} ;
                   6194: 
                   6195: : action1 ( ... -- ... )
                   6196:     @i{code2} ;
                   6197: 
                   6198: def-word1 name1
                   6199: @end example
                   6200: 
1.44      crook    6201: @noindent
                   6202: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1       anton    6203: 
1.29      crook    6204: The classic example is that you can define @code{CONSTANT} in this way:
1.26      crook    6205: 
1.1       anton    6206: @example
1.29      crook    6207: : CONSTANT ( w "name" -- )
                   6208:     CREATE ,
1.26      crook    6209: DOES> ( -- w )
                   6210:     @@ ;
1.1       anton    6211: @end example
                   6212: 
1.29      crook    6213: @comment There is a beautiful description of how this works and what
                   6214: @comment it does in the Forthwrite 100th edition.. as well as an elegant
                   6215: @comment commentary on the Counting Fruits problem.
                   6216: 
                   6217: When you create a constant with @code{5 CONSTANT five}, a set of
                   6218: define-time actions take place; first a new word @code{five} is created,
                   6219: then the value 5 is laid down in the body of @code{five} with
1.44      crook    6220: @code{,}. When @code{five} is executed, the address of the body is put on
1.29      crook    6221: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
                   6222: no code of its own; it simply contains a data field and a pointer to the
                   6223: code that follows @code{DOES>} in its defining word. That makes words
                   6224: created in this way very compact.
                   6225: 
                   6226: The final example in this section is intended to remind you that space
                   6227: reserved in @code{CREATE}d words is @i{data} space and therefore can be
                   6228: both read and written by a Standard program@footnote{Exercise: use this
                   6229: example as a starting point for your own implementation of @code{Value}
                   6230: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
                   6231: @code{[']}.}:
                   6232: 
                   6233: @example
                   6234: : foo ( "name" -- )
                   6235:     CREATE -1 ,
                   6236: DOES> ( -- )
1.33      anton    6237:     @@ . ;
1.29      crook    6238: 
                   6239: foo first-word
                   6240: foo second-word
                   6241: 
                   6242: 123 ' first-word >BODY !
                   6243: @end example
                   6244: 
                   6245: If @code{first-word} had been a @code{CREATE}d word, we could simply
                   6246: have executed it to get the address of its data field. However, since it
                   6247: was defined to have @code{DOES>} actions, its execution semantics are to
                   6248: perform those @code{DOES>} actions. To get the address of its data field
                   6249: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
                   6250: translate the xt into the address of the data field.  When you execute
                   6251: @code{first-word}, it will display @code{123}. When you execute
                   6252: @code{second-word} it will display @code{-1}.
1.26      crook    6253: 
                   6254: @cindex stack effect of @code{DOES>}-parts
                   6255: @cindex @code{DOES>}-parts, stack effect
1.29      crook    6256: In the examples above the stack comment after the @code{DOES>} specifies
1.26      crook    6257: the stack effect of the defined words, not the stack effect of the
                   6258: following code (the following code expects the address of the body on
                   6259: the top of stack, which is not reflected in the stack comment). This is
                   6260: the convention that I use and recommend (it clashes a bit with using
                   6261: locals declarations for stack effect specification, though).
1.1       anton    6262: 
1.26      crook    6263: @subsubsection Applications of @code{CREATE..DOES>}
                   6264: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1       anton    6265: 
1.26      crook    6266: You may wonder how to use this feature. Here are some usage patterns:
1.1       anton    6267: 
1.26      crook    6268: @cindex factoring similar colon definitions
                   6269: When you see a sequence of code occurring several times, and you can
                   6270: identify a meaning, you will factor it out as a colon definition. When
                   6271: you see similar colon definitions, you can factor them using
                   6272: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
                   6273: that look very similar:
1.1       anton    6274: @example
1.26      crook    6275: : ori, ( reg-target reg-source n -- )
                   6276:     0 asm-reg-reg-imm ;
                   6277: : andi, ( reg-target reg-source n -- )
                   6278:     1 asm-reg-reg-imm ;
1.1       anton    6279: @end example
                   6280: 
1.26      crook    6281: @noindent
                   6282: This could be factored with:
                   6283: @example
                   6284: : reg-reg-imm ( op-code -- )
                   6285:     CREATE ,
                   6286: DOES> ( reg-target reg-source n -- )
                   6287:     @@ asm-reg-reg-imm ;
                   6288: 
                   6289: 0 reg-reg-imm ori,
                   6290: 1 reg-reg-imm andi,
                   6291: @end example
1.1       anton    6292: 
1.26      crook    6293: @cindex currying
                   6294: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
                   6295: supply a part of the parameters for a word (known as @dfn{currying} in
                   6296: the functional language community). E.g., @code{+} needs two
                   6297: parameters. Creating versions of @code{+} with one parameter fixed can
                   6298: be done like this:
1.1       anton    6299: @example
1.26      crook    6300: : curry+ ( n1 -- )
                   6301:     CREATE ,
                   6302: DOES> ( n2 -- n1+n2 )
                   6303:     @@ + ;
                   6304: 
                   6305:  3 curry+ 3+
                   6306: -2 curry+ 2-
1.1       anton    6307: @end example
                   6308: 
1.26      crook    6309: @subsubsection The gory details of @code{CREATE..DOES>}
                   6310: @cindex @code{CREATE} ... @code{DOES>}, details
1.1       anton    6311: 
1.26      crook    6312: doc-does>
1.1       anton    6313: 
1.26      crook    6314: @cindex @code{DOES>} in a separate definition
                   6315: This means that you need not use @code{CREATE} and @code{DOES>} in the
                   6316: same definition; you can put the @code{DOES>}-part in a separate
1.29      crook    6317: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26      crook    6318: @example
                   6319: : does1 
                   6320: DOES> ( ... -- ... )
1.44      crook    6321:     ... ;
                   6322: 
                   6323: : does2
                   6324: DOES> ( ... -- ... )
                   6325:     ... ;
                   6326: 
                   6327: : def-word ( ... -- ... )
                   6328:     create ...
                   6329:     IF
                   6330:        does1
                   6331:     ELSE
                   6332:        does2
                   6333:     ENDIF ;
                   6334: @end example
                   6335: 
                   6336: In this example, the selection of whether to use @code{does1} or
                   6337: @code{does2} is made at compile-time; at the time that the child word is
                   6338: @code{CREATE}d.
                   6339: 
                   6340: @cindex @code{DOES>} in interpretation state
                   6341: In a standard program you can apply a @code{DOES>}-part only if the last
                   6342: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
                   6343: will override the behaviour of the last word defined in any case. In a
                   6344: standard program, you can use @code{DOES>} only in a colon
                   6345: definition. In Gforth, you can also use it in interpretation state, in a
                   6346: kind of one-shot mode; for example:
                   6347: @example
                   6348: CREATE name ( ... -- ... )
                   6349:   @i{initialization}
                   6350: DOES>
                   6351:   @i{code} ;
                   6352: @end example
                   6353: 
                   6354: @noindent
                   6355: is equivalent to the standard:
                   6356: @example
                   6357: :noname
                   6358: DOES>
                   6359:     @i{code} ;
                   6360: CREATE name EXECUTE ( ... -- ... )
                   6361:     @i{initialization}
                   6362: @end example
                   6363: 
                   6364: 
                   6365: doc->body
                   6366: 
                   6367: 
                   6368: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
                   6369: @subsection Deferred words
                   6370: @cindex deferred words
                   6371: 
                   6372: The defining word @code{Defer} allows you to define a word by name
                   6373: without defining its behaviour; the definition of its behaviour is
                   6374: deferred. Here are two situation where this can be useful:
                   6375: 
                   6376: @itemize @bullet
                   6377: @item
                   6378: Where you want to allow the behaviour of a word to be altered later, and
                   6379: for all precompiled references to the word to change when its behaviour
                   6380: is changed.
                   6381: @item
                   6382: For mutual recursion; @xref{Calls and returns}.
                   6383: @end itemize
                   6384: 
                   6385: In the following example, @code{foo} always invokes the version of
                   6386: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
                   6387: always invokes the version that prints ``@code{Hello}''. There is no way
                   6388: of getting @code{foo} to use the later version without re-ordering the
                   6389: source code and recompiling it.
                   6390: 
                   6391: @example
                   6392: : greet ." Good morning" ;
                   6393: : foo ... greet ... ;
                   6394: : greet ." Hello" ;
                   6395: : bar ... greet ... ;
                   6396: @end example
                   6397: 
                   6398: This problem can be solved by defining @code{greet} as a @code{Defer}red
                   6399: word. The behaviour of a @code{Defer}red word can be defined and
                   6400: redefined at any time by using @code{IS} to associate the xt of a
                   6401: previously-defined word with it. The previous example becomes:
                   6402: 
                   6403: @example
                   6404: Defer greet
                   6405: : foo ... greet ... ;
                   6406: : bar ... greet ... ;
                   6407: : greet1 ." Good morning" ;
                   6408: : greet2 ." Hello" ;
                   6409: ' greet2 <IS> greet  \ make greet behave like greet2
                   6410: @end example
                   6411: 
                   6412: A deferred word can be used to improve the statistics-gathering example
                   6413: from @ref{User-defined Defining Words}; rather than edit the
                   6414: application's source code to change every @code{:} to a @code{my:}, do
                   6415: this:
                   6416: 
                   6417: @example
                   6418: : real: : ;     \ retain access to the original
                   6419: defer :         \ redefine as a deferred word
                   6420: ' my: IS :      \ use special version of :
                   6421: \
                   6422: \ load application here
                   6423: \
                   6424: ' real: IS :    \ go back to the original
                   6425: @end example
                   6426: 
                   6427: 
                   6428: One thing to note is that @code{<IS>} consumes its name when it is
                   6429: executed.  If you want to specify the name at compile time, use
                   6430: @code{[IS]}:
                   6431: 
                   6432: @example
                   6433: : set-greet ( xt -- )
                   6434:   [IS] greet ;
                   6435: 
                   6436: ' greet1 set-greet
                   6437: @end example
                   6438: 
                   6439: A deferred word can only inherit default semantics from the xt (because
                   6440: that is all that an xt can represent -- @pxref{Tokens for Words} for
                   6441: more discussion of this). However, the semantics of the deferred word
                   6442: itself can be modified at the time that it is defined. For example:
                   6443: 
                   6444: @example
                   6445: : bar .... ; compile-only
                   6446: Defer fred immediate
                   6447: Defer jim
                   6448: 
                   6449: ' bar <IS> jim  \ jim has default semantics
                   6450: ' bar <IS> fred \ fred is immediate
                   6451: @end example
                   6452: 
                   6453: doc-defer
                   6454: doc-<is>
                   6455: doc-[is]
                   6456: doc-is
                   6457: @comment TODO document these: what's defers [is]
                   6458: doc-what's
                   6459: doc-defers
                   6460: 
                   6461: @c Use @code{words-deferred} to see a list of deferred words.
                   6462: 
                   6463: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
                   6464: are provided in @file{compat/defer.fs}.
                   6465: 
                   6466: 
                   6467: @node Aliases, Supplying names, Deferred words, Defining Words
                   6468: @subsection Aliases
                   6469: @cindex aliases
1.1       anton    6470: 
1.44      crook    6471: The defining word @code{Alias} allows you to define a word by name that
                   6472: has the same behaviour as some other word. Here are two situation where
                   6473: this can be useful:
1.1       anton    6474: 
1.44      crook    6475: @itemize @bullet
                   6476: @item
                   6477: When you want access to a word's definition from a different word list
                   6478: (for an example of this, see the definition of the @code{Root} word list
                   6479: in the Gforth source).
                   6480: @item
                   6481: When you want to create a synonym; a definition that can be known by
                   6482: either of two names (for example, @code{THEN} and @code{ENDIF} are
                   6483: aliases).
                   6484: @end itemize
1.1       anton    6485: 
1.44      crook    6486: The word whose behaviour the alias is to inherit is represented by an
                   6487: xt. Therefore, the alias only inherits default semantics from its
                   6488: ancestor. The semantics of the alias itself can be modified at the time
                   6489: that it is defined. For example:
1.1       anton    6490: 
                   6491: @example
1.44      crook    6492: : foo ... ; immediate
                   6493: 
                   6494: ' foo Alias bar \ bar is not an immediate word
                   6495: ' foo Alias fooby immediate \ fooby is an immediate word
1.1       anton    6496: @end example
                   6497: 
1.44      crook    6498: Words that are aliases have the same xt, different headers in the
                   6499: dictionary, and consequently different name tokens (@pxref{Tokens for
                   6500: Words}) and possibly different immediate flags.  An alias can only have
                   6501: default or immediate compilation semantics; you can define aliases for
                   6502: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1       anton    6503: 
1.44      crook    6504: doc-alias
1.26      crook    6505: 
1.1       anton    6506: 
1.47      crook    6507: @node Supplying names, , Aliases, Defining Words
1.29      crook    6508: @subsection Supplying the name of a defined word
1.26      crook    6509: @cindex names for defined words
1.44      crook    6510: @cindex defining words, name given in a string
1.1       anton    6511: 
1.29      crook    6512: By default, a defining word takes the name for the defined word from the
1.26      crook    6513: input stream. Sometimes you want to supply the name from a string. You
                   6514: can do this with:
1.1       anton    6515: 
1.26      crook    6516: doc-nextname
1.1       anton    6517: 
1.26      crook    6518: For example:
1.1       anton    6519: 
1.26      crook    6520: @example
                   6521: s" foo" nextname create
                   6522: @end example
1.44      crook    6523: 
1.26      crook    6524: @noindent
                   6525: is equivalent to:
1.44      crook    6526: 
1.26      crook    6527: @example
                   6528: create foo
                   6529: @end example
1.1       anton    6530: 
1.29      crook    6531: @noindent
1.44      crook    6532: @code{nextname} works with any defining word, not just @code{:}.
1.1       anton    6533: 
                   6534: 
1.47      crook    6535: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
                   6536: @section Interpretation and Compilation Semantics
1.26      crook    6537: @cindex semantics, interpretation and compilation
1.1       anton    6538: 
1.26      crook    6539: @cindex interpretation semantics
                   6540: The @dfn{interpretation semantics} of a word are what the text
                   6541: interpreter does when it encounters the word in interpret state. It also
                   6542: appears in some other contexts, e.g., the execution token returned by
1.29      crook    6543: @code{' @i{word}} identifies the interpretation semantics of
                   6544: @i{word} (in other words, @code{' @i{word} execute} is equivalent to
                   6545: interpret-state text interpretation of @code{@i{word}}).
1.1       anton    6546: 
1.26      crook    6547: @cindex compilation semantics
                   6548: The @dfn{compilation semantics} of a word are what the text interpreter
                   6549: does when it encounters the word in compile state. It also appears in
1.29      crook    6550: other contexts, e.g, @code{POSTPONE @i{word}} compiles@footnote{In
1.26      crook    6551: standard terminology, ``appends to the current definition''.} the
1.29      crook    6552: compilation semantics of @i{word}.
1.1       anton    6553: 
1.26      crook    6554: @cindex execution semantics
                   6555: The standard also talks about @dfn{execution semantics}. They are used
                   6556: only for defining the interpretation and compilation semantics of many
                   6557: words. By default, the interpretation semantics of a word are to
                   6558: @code{execute} its execution semantics, and the compilation semantics of
                   6559: a word are to @code{compile,} its execution semantics.@footnote{In
                   6560: standard terminology: The default interpretation semantics are its
                   6561: execution semantics; the default compilation semantics are to append its
                   6562: execution semantics to the execution semantics of the current
                   6563: definition.}
                   6564: 
                   6565: @comment TODO expand, make it co-operate with new sections on text interpreter.
                   6566: 
                   6567: @cindex immediate words
                   6568: @cindex compile-only words
                   6569: You can change the semantics of the most-recently defined word:
                   6570: 
1.44      crook    6571: 
1.26      crook    6572: doc-immediate
                   6573: doc-compile-only
                   6574: doc-restrict
                   6575: 
1.44      crook    6576: 
1.26      crook    6577: Note that ticking (@code{'}) a compile-only word gives an error
                   6578: (``Interpreting a compile-only word'').
1.1       anton    6579: 
1.47      crook    6580: @menu
                   6581: * Combined words::
                   6582: @end menu
1.44      crook    6583: 
1.48    ! anton    6584: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44      crook    6585: @subsection Combined Words
                   6586: @cindex combined words
                   6587: 
                   6588: Gforth allows you to define @dfn{combined words} -- words that have an
                   6589: arbitrary combination of interpretation and compilation semantics.
                   6590: 
1.1       anton    6591: 
1.26      crook    6592: doc-interpret/compile:
1.1       anton    6593: 
1.44      crook    6594: 
1.26      crook    6595: This feature was introduced for implementing @code{TO} and @code{S"}. I
                   6596: recommend that you do not define such words, as cute as they may be:
                   6597: they make it hard to get at both parts of the word in some contexts.
                   6598: E.g., assume you want to get an execution token for the compilation
                   6599: part. Instead, define two words, one that embodies the interpretation
                   6600: part, and one that embodies the compilation part.  Once you have done
                   6601: that, you can define a combined word with @code{interpret/compile:} for
                   6602: the convenience of your users.
1.1       anton    6603: 
1.26      crook    6604: You might try to use this feature to provide an optimizing
                   6605: implementation of the default compilation semantics of a word. For
                   6606: example, by defining:
1.1       anton    6607: @example
1.26      crook    6608: :noname
                   6609:    foo bar ;
                   6610: :noname
                   6611:    POSTPONE foo POSTPONE bar ;
1.29      crook    6612: interpret/compile: opti-foobar
1.1       anton    6613: @end example
1.26      crook    6614: 
1.23      crook    6615: @noindent
1.26      crook    6616: as an optimizing version of:
                   6617: 
1.1       anton    6618: @example
1.26      crook    6619: : foobar
                   6620:     foo bar ;
1.1       anton    6621: @end example
                   6622: 
1.26      crook    6623: Unfortunately, this does not work correctly with @code{[compile]},
                   6624: because @code{[compile]} assumes that the compilation semantics of all
                   6625: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29      crook    6626: opti-foobar} would compile compilation semantics, whereas
                   6627: @code{[compile] foobar} would compile interpretation semantics.
1.1       anton    6628: 
1.26      crook    6629: @cindex state-smart words (are a bad idea)
1.29      crook    6630: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26      crook    6631: by @code{interpret/compile:} (words are state-smart if they check
                   6632: @code{STATE} during execution). E.g., they would try to code
                   6633: @code{foobar} like this:
1.1       anton    6634: 
1.26      crook    6635: @example
                   6636: : foobar
                   6637:   STATE @@
                   6638:   IF ( compilation state )
                   6639:     POSTPONE foo POSTPONE bar
                   6640:   ELSE
                   6641:     foo bar
                   6642:   ENDIF ; immediate
                   6643: @end example
1.1       anton    6644: 
1.26      crook    6645: Although this works if @code{foobar} is only processed by the text
                   6646: interpreter, it does not work in other contexts (like @code{'} or
                   6647: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
                   6648: for a state-smart word, not for the interpretation semantics of the
                   6649: original @code{foobar}; when you execute this execution token (directly
                   6650: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
                   6651: state, the result will not be what you expected (i.e., it will not
                   6652: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
                   6653: write them@footnote{For a more detailed discussion of this topic, see
                   6654: @cite{@code{State}-smartness -- Why it is Evil and How to Exorcise it} by Anton
                   6655: Ertl; presented at EuroForth '98 and available from
1.47      crook    6656: @*@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz}}!
1.1       anton    6657: 
1.26      crook    6658: @cindex defining words with arbitrary semantics combinations
                   6659: It is also possible to write defining words that define words with
                   6660: arbitrary combinations of interpretation and compilation semantics. In
                   6661: general, they look like this:
1.1       anton    6662: 
1.26      crook    6663: @example
                   6664: : def-word
                   6665:     create-interpret/compile
1.29      crook    6666:     @i{code1}
1.26      crook    6667: interpretation>
1.29      crook    6668:     @i{code2}
1.26      crook    6669: <interpretation
                   6670: compilation>
1.29      crook    6671:     @i{code3}
1.26      crook    6672: <compilation ;
                   6673: @end example
1.1       anton    6674: 
1.29      crook    6675: For a @i{word} defined with @code{def-word}, the interpretation
                   6676: semantics are to push the address of the body of @i{word} and perform
                   6677: @i{code2}, and the compilation semantics are to push the address of
                   6678: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26      crook    6679: can also be defined like this (except that the defined constants don't
                   6680: behave correctly when @code{[compile]}d):
1.1       anton    6681: 
1.26      crook    6682: @example
                   6683: : constant ( n "name" -- )
                   6684:     create-interpret/compile
                   6685:     ,
                   6686: interpretation> ( -- n )
                   6687:     @@
                   6688: <interpretation
                   6689: compilation> ( compilation. -- ; run-time. -- n )
                   6690:     @@ postpone literal
                   6691: <compilation ;
                   6692: @end example
1.1       anton    6693: 
1.44      crook    6694: 
1.26      crook    6695: doc-create-interpret/compile
                   6696: doc-interpretation>
                   6697: doc-<interpretation
                   6698: doc-compilation>
                   6699: doc-<compilation
1.1       anton    6700: 
1.44      crook    6701: 
1.29      crook    6702: Words defined with @code{interpret/compile:} and
1.26      crook    6703: @code{create-interpret/compile} have an extended header structure that
                   6704: differs from other words; however, unless you try to access them with
                   6705: plain address arithmetic, you should not notice this. Words for
                   6706: accessing the header structure usually know how to deal with this; e.g.,
1.29      crook    6707: @code{'} @i{word} @code{>body} also gives you the body of a word created
                   6708: with @code{create-interpret/compile}.
1.1       anton    6709: 
1.44      crook    6710: 
1.27      crook    6711: doc-postpone
1.44      crook    6712: 
1.29      crook    6713: @comment TODO -- expand glossary text for POSTPONE
1.27      crook    6714: 
1.47      crook    6715: 
                   6716: @c -------------------------------------------------------------
                   6717: @node Tokens for Words, The Text Interpreter, Interpretation and Compilation Semantics, Words
                   6718: @section Tokens for Words
                   6719: @cindex tokens for words
                   6720: 
                   6721: This section describes the creation and use of tokens that represent
                   6722: words.
                   6723: 
                   6724: Named words have information stored in their header space entries to
                   6725: indicate any non-default semantics (@pxref{Interpretation and
                   6726: Compilation Semantics}). The semantics can be modified, using
                   6727: @code{immediate} and/or @code{compile-only}, at the time that the words
                   6728: are defined. Unnamed words have (by definition) no header space
                   6729: entry, and therefore must have default semantics.
                   6730: 
                   6731: Named words have interpretation and compilation semantics. Unnamed words
                   6732: just have execution semantics.
                   6733: 
                   6734: @cindex xt
                   6735: @cindex execution token
                   6736: The execution semantics of an unnamed word are represented by an
                   6737: @dfn{execution token} (@i{xt}). As explained in @ref{Supplying names},
                   6738: the execution token of the last word defined can be produced with
                   6739: @code{lastxt}.
                   6740: 
                   6741: The interpretation semantics of a named word are also represented by an
                   6742: execution token. You can produce the execution token using @code{'} or
                   6743: @code{[']}. A simple example shows the difference between the two:
                   6744: 
                   6745: @example
                   6746: : greet ( -- )   ." Hello" ;
                   6747: : foo ( -- xt )  ['] greet execute ; \ ['] parses greet at compile-time
                   6748: : bar ( -- )     ' execute ; \  '  parses at run-time
                   6749: 
                   6750: \ the next four lines all do the same thing
                   6751: foo
                   6752: bar greet
                   6753: greet
                   6754: ' greet EXECUTE
                   6755: @end example
                   6756: 
                   6757: An execution token occupies one cell.
                   6758: @cindex code field address
                   6759: @cindex CFA
                   6760: In Gforth, the abstract data type @i{execution token} is implemented
                   6761: as a code field address (CFA).
                   6762: @comment TODO note that the standard does not say what it represents..
                   6763: @comment and you cannot necessarily compile it in all Forths (eg native
                   6764: @comment compilers?).
                   6765: 
                   6766: For literals, use @code{'} in interpreted code and @code{[']} in
                   6767: compiled code. Gforth's @code{'} and @code{[']} behave somewhat
                   6768: unusually by complaining about compile-only words. To get the execution
                   6769: token for a compile-only word @i{name}, use @code{COMP' @i{name} DROP}
                   6770: or @code{[COMP'] @i{name} DROP}.
                   6771: 
                   6772: @cindex compilation token
                   6773: The compilation semantics of a named word are represented by a
                   6774: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
                   6775: @i{xt} is an execution token. The compilation semantics represented by
                   6776: the compilation token can be performed with @code{execute}, which
                   6777: consumes the whole compilation token, with an additional stack effect
                   6778: determined by the represented compilation semantics.
                   6779: 
                   6780: At present, the @i{w} part of a compilation token is an execution token,
                   6781: and the @i{xt} part represents either @code{execute} or
                   6782: @code{compile,}@footnote{Depending upon the compilation semantics of the
                   6783: word. If the word has default compilation semantics, the @i{xt} will
                   6784: represent @code{compile,}. Otherwise (e.g., for immediate words), the
                   6785: @i{xt} will represent @code{execute}.}. However, don't rely on that
                   6786: knowledge, unless necessary; future versions of Gforth may introduce
                   6787: unusual compilation tokens (e.g., a compilation token that represents
                   6788: the compilation semantics of a literal).
                   6789: 
                   6790: You can compile the compilation semantics with @code{postpone,}. I.e.,
                   6791: @code{COMP' @i{word} postpone,} is equivalent to @code{postpone
                   6792: @i{word}}.
                   6793: 
                   6794: @cindex name token
                   6795: @cindex name field address
                   6796: @cindex NFA
                   6797: Named words are also represented by the @dfn{name token}, (@i{nt}). In
                   6798: Gforth, the abstract data type @emph{name token} is implemented as a
                   6799: name field address (NFA).
                   6800: 
                   6801: 
                   6802: doc-execute
                   6803: doc-perform
                   6804: doc-compile,
                   6805: doc-[']
                   6806: doc-'
                   6807: doc-[comp']
                   6808: doc-comp'
                   6809: doc-postpone,
                   6810: 
                   6811: doc-find-name
                   6812: doc-name>int
                   6813: doc-name?int
                   6814: doc-name>comp
                   6815: doc-name>string
                   6816: 
                   6817: 
1.26      crook    6818: @c ----------------------------------------------------------
1.47      crook    6819: @node The Text Interpreter, Word Lists, Tokens for Words, Words
1.26      crook    6820: @section  The Text Interpreter
                   6821: @cindex interpreter - outer
                   6822: @cindex text interpreter
                   6823: @cindex outer interpreter
1.1       anton    6824: 
1.34      anton    6825: @c Should we really describe all these ugly details?  IMO the text
                   6826: @c interpreter should be much cleaner, but that may not be possible within
                   6827: @c ANS Forth. - anton
1.44      crook    6828: @c nac-> I wanted to explain how it works to show how you can exploit
                   6829: @c it in your own programs. When I was writing a cross-compiler, figuring out
                   6830: @c some of these gory details was very helpful to me. None of the textbooks
                   6831: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
                   6832: @c seems to positively avoid going into too much detail for some of
                   6833: @c the internals.
1.34      anton    6834: 
1.29      crook    6835: The text interpreter@footnote{This is an expanded version of the
                   6836: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34      anton    6837: that processes input from the current input device. It is also called
                   6838: the outer interpreter, in contrast to the inner interpreter
                   6839: (@pxref{Engine}) which executes the compiled Forth code on interpretive
                   6840: implementations.
1.27      crook    6841: 
1.29      crook    6842: @cindex interpret state
                   6843: @cindex compile state
                   6844: The text interpreter operates in one of two states: @dfn{interpret
                   6845: state} and @dfn{compile state}. The current state is defined by the
                   6846: aptly-named variable, @code{state}.
                   6847: 
                   6848: This section starts by describing how the text interpreter behaves when
                   6849: it is in interpret state, processing input from the user input device --
                   6850: the keyboard. This is the mode that a Forth system is in after it starts
                   6851: up.
                   6852: 
                   6853: @cindex input buffer
                   6854: @cindex terminal input buffer
                   6855: The text interpreter works from an area of memory called the @dfn{input
                   6856: buffer}@footnote{When the text interpreter is processing input from the
                   6857: keyboard, this area of memory is called the @dfn{terminal input buffer}
                   6858: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
                   6859: @code{#TIB}.}, which stores your keyboard input when you press the
1.30      anton    6860: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29      crook    6861: leading spaces (called @dfn{delimiters}) then parses a string (a
                   6862: sequence of non-space characters) until it reaches either a space
                   6863: character or the end of the buffer. Having parsed a string, it makes two
                   6864: attempts to process it:
1.27      crook    6865: 
1.29      crook    6866: @cindex dictionary
1.27      crook    6867: @itemize @bullet
                   6868: @item
1.29      crook    6869: It looks for the string in a @dfn{dictionary} of definitions. If the
                   6870: string is found, the string names a @dfn{definition} (also known as a
                   6871: @dfn{word}) and the dictionary search returns information that allows
                   6872: the text interpreter to perform the word's @dfn{interpretation
                   6873: semantics}. In most cases, this simply means that the word will be
                   6874: executed.
1.27      crook    6875: @item
                   6876: If the string is not found in the dictionary, the text interpreter
1.29      crook    6877: attempts to treat it as a number, using the rules described in
                   6878: @ref{Number Conversion}. If the string represents a legal number in the
                   6879: current radix, the number is pushed onto a parameter stack (the data
                   6880: stack for integers, the floating-point stack for floating-point
                   6881: numbers).
                   6882: @end itemize
                   6883: 
                   6884: If both attempts fail, or if the word is found in the dictionary but has
                   6885: no interpretation semantics@footnote{This happens if the word was
                   6886: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
                   6887: remainder of the input buffer, issues an error message and waits for
                   6888: more input. If one of the attempts succeeds, the text interpreter
                   6889: repeats the parsing process until the whole of the input buffer has been
                   6890: processed, at which point it prints the status message ``@code{ ok}''
                   6891: and waits for more input.
                   6892: 
                   6893: @cindex parse area
                   6894: The text interpreter keeps track of its position in the input buffer by
                   6895: updating a variable called @code{>IN} (pronounced ``to-in''). The value
                   6896: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
                   6897: of the input buffer. The region from offset @code{>IN @@} to the end of
                   6898: the input buffer is called the @dfn{parse area}@footnote{In other words,
                   6899: the text interpreter processes the contents of the input buffer by
                   6900: parsing strings from the parse area until the parse area is empty.}.
                   6901: This example shows how @code{>IN} changes as the text interpreter parses
                   6902: the input buffer:
                   6903: 
                   6904: @example
                   6905: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
                   6906:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
                   6907: 
                   6908: 1 2 3 remaining + remaining . 
                   6909: 
                   6910: : foo 1 2 3 remaining SWAP remaining ;
                   6911: @end example
                   6912: 
                   6913: @noindent
                   6914: The result is:
                   6915: 
                   6916: @example
                   6917: ->+ remaining .<-
                   6918: ->.<-5  ok
                   6919: 
                   6920: ->SWAP remaining ;-<
                   6921: ->;<-  ok
                   6922: @end example
                   6923: 
                   6924: @cindex parsing words
                   6925: The value of @code{>IN} can also be modified by a word in the input
                   6926: buffer that is executed by the text interpreter.  This means that a word
                   6927: can ``trick'' the text interpreter into either skipping a section of the
                   6928: input buffer@footnote{This is how parsing words work.} or into parsing a
                   6929: section twice. For example:
1.27      crook    6930: 
1.29      crook    6931: @example
                   6932: : lat ." <<lat>>" ;
                   6933: : flat ." <<flat>>" >IN DUP @@ 3 - SWAP ! ;
                   6934: @end example
                   6935: 
                   6936: @noindent
                   6937: When @code{flat} is executed, this output is produced@footnote{Exercise
                   6938: for the reader: what would happen if the @code{3} were replaced with
                   6939: @code{4}?}:
                   6940: 
                   6941: @example
                   6942: <<flat>><<lat>>
                   6943: @end example
                   6944: 
                   6945: @noindent
                   6946: Two important notes about the behaviour of the text interpreter:
1.27      crook    6947: 
                   6948: @itemize @bullet
                   6949: @item
                   6950: It processes each input string to completion before parsing additional
1.29      crook    6951: characters from the input buffer.
                   6952: @item
                   6953: It treats the input buffer as a read-only region (and so must your code).
                   6954: @end itemize
                   6955: 
                   6956: @noindent
                   6957: When the text interpreter is in compile state, its behaviour changes in
                   6958: these ways:
                   6959: 
                   6960: @itemize @bullet
                   6961: @item
                   6962: If a parsed string is found in the dictionary, the text interpreter will
                   6963: perform the word's @dfn{compilation semantics}. In most cases, this
                   6964: simply means that the execution semantics of the word will be appended
                   6965: to the current definition.
1.27      crook    6966: @item
1.29      crook    6967: When a number is encountered, it is compiled into the current definition
                   6968: (as a literal) rather than being pushed onto a parameter stack.
                   6969: @item
                   6970: If an error occurs, @code{state} is modified to put the text interpreter
                   6971: back into interpret state.
                   6972: @item
                   6973: Each time a line is entered from the keyboard, Gforth prints
                   6974: ``@code{ compiled}'' rather than `` @code{ok}''.
                   6975: @end itemize
                   6976: 
                   6977: @cindex text interpreter - input sources
                   6978: When the text interpreter is using an input device other than the
                   6979: keyboard, its behaviour changes in these ways:
                   6980: 
                   6981: @itemize @bullet
                   6982: @item
                   6983: When the parse area is empty, the text interpreter attempts to refill
                   6984: the input buffer from the input source. When the input source is
                   6985: exhausted, the input source is set back to the user input device.
                   6986: @item
                   6987: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
                   6988: time the parse area is emptied.
                   6989: @item
                   6990: If an error occurs, the input source is set back to the user input
                   6991: device.
1.27      crook    6992: @end itemize
1.21      crook    6993: 
1.29      crook    6994: @ref{Input Sources} describes this in more detail.
                   6995: 
1.44      crook    6996: 
1.26      crook    6997: doc->in
1.27      crook    6998: doc-source
                   6999: 
1.26      crook    7000: doc-tib
                   7001: doc-#tib
1.1       anton    7002: 
1.44      crook    7003: 
1.26      crook    7004: @menu
1.29      crook    7005: * Input Sources::
1.26      crook    7006: * Number Conversion::
                   7007: * Interpret/Compile states::
                   7008: * Literals::
                   7009: * Interpreter Directives::
                   7010: @end menu
1.1       anton    7011: 
1.29      crook    7012: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
                   7013: @subsection Input Sources
                   7014: @cindex input sources
                   7015: @cindex text interpreter - input sources
                   7016: 
1.44      crook    7017: By default, the text interpreter processes input from the user input
1.29      crook    7018: device (the keyboard) when Forth starts up. The text interpreter can
                   7019: process input from any of these sources:
                   7020: 
                   7021: @itemize @bullet
                   7022: @item
                   7023: The user input device -- the keyboard.
                   7024: @item
                   7025: A file, using the words described in @ref{Forth source files}.
                   7026: @item
                   7027: A block, using the words described in @ref{Blocks}.
                   7028: @item
                   7029: A text string, using @code{evaluate}.
                   7030: @end itemize
                   7031: 
                   7032: A program can identify the current input device from the values of
                   7033: @code{source-id} and @code{blk}.
                   7034: 
1.44      crook    7035: 
1.29      crook    7036: doc-source-id
                   7037: doc-blk
                   7038: 
                   7039: doc-save-input
                   7040: doc-restore-input
                   7041: 
                   7042: doc-evaluate
1.1       anton    7043: 
1.29      crook    7044: 
1.44      crook    7045: 
1.29      crook    7046: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26      crook    7047: @subsection Number Conversion
                   7048: @cindex number conversion
                   7049: @cindex double-cell numbers, input format
                   7050: @cindex input format for double-cell numbers
                   7051: @cindex single-cell numbers, input format
                   7052: @cindex input format for single-cell numbers
                   7053: @cindex floating-point numbers, input format
                   7054: @cindex input format for floating-point numbers
1.1       anton    7055: 
1.29      crook    7056: This section describes the rules that the text interpreter uses when it
                   7057: tries to convert a string into a number.
1.1       anton    7058: 
1.26      crook    7059: Let <digit> represent any character that is a legal digit in the current
1.29      crook    7060: number base@footnote{For example, 0-9 when the number base is decimal or
                   7061: 0-9, A-F when the number base is hexadecimal.}.
1.1       anton    7062: 
1.26      crook    7063: Let <decimal digit> represent any character in the range 0-9.
1.1       anton    7064: 
1.29      crook    7065: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
                   7066: in the braces (@i{a} or @i{b} or neither).
1.1       anton    7067: 
1.26      crook    7068: Let * represent any number of instances of the previous character
                   7069: (including none).
1.1       anton    7070: 
1.26      crook    7071: Let any other character represent itself.
1.1       anton    7072: 
1.29      crook    7073: @noindent
1.26      crook    7074: Now, the conversion rules are:
1.21      crook    7075: 
1.26      crook    7076: @itemize @bullet
                   7077: @item
                   7078: A string of the form <digit><digit>* is treated as a single-precision
1.29      crook    7079: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26      crook    7080: @item
                   7081: A string of the form -<digit><digit>* is treated as a single-precision
1.29      crook    7082: (cell-sized) negative integer, and is represented using 2's-complement
1.26      crook    7083: arithmetic. Examples are -45 -5681 -0
                   7084: @item
                   7085: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29      crook    7086: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
                   7087: (all three of these represent the same number).
1.26      crook    7088: @item
                   7089: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29      crook    7090: double-precision (double-cell-sized) negative integer, and is
1.26      crook    7091: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29      crook    7092: -34.65 (all three of these represent the same number).
1.26      crook    7093: @item
1.29      crook    7094: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
                   7095: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35      anton    7096: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29      crook    7097: number) +12.E-4
1.26      crook    7098: @end itemize
1.1       anton    7099: 
1.26      crook    7100: By default, the number base used for integer number conversion is given
1.35      anton    7101: by the contents of the variable @code{base}.  Note that a lot of
                   7102: confusion can result from unexpected values of @code{base}.  If you
                   7103: change @code{base} anywhere, make sure to save the old value and restore
                   7104: it afterwards.  In general I recommend keeping @code{base} decimal, and
                   7105: using the prefixes described below for the popular non-decimal bases.
1.1       anton    7106: 
1.29      crook    7107: doc-dpl
1.26      crook    7108: doc-base
                   7109: doc-hex
                   7110: doc-decimal
1.1       anton    7111: 
1.44      crook    7112: 
1.26      crook    7113: @cindex '-prefix for character strings
                   7114: @cindex &-prefix for decimal numbers
                   7115: @cindex %-prefix for binary numbers
                   7116: @cindex $-prefix for hexadecimal numbers
1.35      anton    7117: Gforth allows you to override the value of @code{base} by using a
1.29      crook    7118: prefix@footnote{Some Forth implementations provide a similar scheme by
                   7119: implementing @code{$} etc. as parsing words that process the subsequent
                   7120: number in the input stream and push it onto the stack. For example, see
                   7121: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
                   7122: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
                   7123: is required between the prefix and the number.} before the first digit
                   7124: of an (integer) number. Four prefixes are supported:
1.1       anton    7125: 
1.26      crook    7126: @itemize @bullet
                   7127: @item
1.35      anton    7128: @code{&} -- decimal
1.26      crook    7129: @item
1.35      anton    7130: @code{%} -- binary
1.26      crook    7131: @item
1.35      anton    7132: @code{$} -- hexadecimal
1.26      crook    7133: @item
1.35      anton    7134: @code{'} -- base @code{max-char+1}
1.26      crook    7135: @end itemize
1.1       anton    7136: 
1.26      crook    7137: Here are some examples, with the equivalent decimal number shown after
                   7138: in braces:
1.1       anton    7139: 
1.26      crook    7140: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
                   7141: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
                   7142: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
                   7143: &905 (905), $abc (2478), $ABC (2478).
1.1       anton    7144: 
1.26      crook    7145: @cindex number conversion - traps for the unwary
1.29      crook    7146: @noindent
1.26      crook    7147: Number conversion has a number of traps for the unwary:
1.1       anton    7148: 
1.26      crook    7149: @itemize @bullet
                   7150: @item
                   7151: You cannot determine the current number base using the code sequence
1.35      anton    7152: @code{base @@ .} -- the number base is always 10 in the current number
                   7153: base. Instead, use something like @code{base @@ dec.}
1.26      crook    7154: @item
                   7155: If the number base is set to a value greater than 14 (for example,
                   7156: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
                   7157: it to be intepreted as either a single-precision integer or a
                   7158: floating-point number (Gforth treats it as an integer). The ambiguity
                   7159: can be resolved by explicitly stating the sign of the mantissa and/or
                   7160: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
                   7161: ambiguity arises; either representation will be treated as a
                   7162: floating-point number.
                   7163: @item
1.29      crook    7164: There is a word @code{bin} but it does @i{not} set the number base!
1.26      crook    7165: It is used to specify file types.
                   7166: @item
                   7167: ANS Forth requires the @code{.} of a double-precision number to
                   7168: be the final character in the string. Allowing the @code{.} to be
                   7169: anywhere after the first digit is a Gforth extension.
                   7170: @item
                   7171: The number conversion process does not check for overflow.
                   7172: @item
                   7173: In Gforth, number conversion to floating-point numbers always use base
1.35      anton    7174: 10, irrespective of the value of @code{base}. In ANS Forth,
1.26      crook    7175: conversion to floating-point numbers whilst the value of
1.35      anton    7176: @code{base} is not 10 is an ambiguous condition.
1.26      crook    7177: @end itemize
1.1       anton    7178: 
1.29      crook    7179: @ref{Input} describes words that you can use to read numbers into your
                   7180: programs.
1.1       anton    7181: 
1.26      crook    7182: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
                   7183: @subsection Interpret/Compile states
                   7184: @cindex Interpret/Compile states
1.1       anton    7185: 
1.29      crook    7186: A standard program is not permitted to change @code{state}
                   7187: explicitly. However, it can change @code{state} implicitly, using the
                   7188: words @code{[} and @code{]}. When @code{[} is executed it switches
                   7189: @code{state} to interpret state, and therefore the text interpreter
                   7190: starts interpreting. When @code{]} is executed it switches @code{state}
                   7191: to compile state and therefore the text interpreter starts
1.44      crook    7192: compiling. The most common usage for these words is for switching into
                   7193: interpret state and back from within a colon definition; this technique
                   7194: can be used to compile a literal (@pxref{Literals} for an example) or
                   7195: for conditional compilation (@pxref{Interpreter Directives} for an
                   7196: example).
                   7197: 
1.35      anton    7198: 
                   7199: @c This is a bad example: It's non-standard, and it's not necessary.
                   7200: @c However, I can't think of a good example for switching into compile
                   7201: @c state when there is no current word (@code{state}-smart words are not a
                   7202: @c good reason).  So maybe we should use an example for switching into
                   7203: @c interpret @code{state} in a colon def. - anton
1.44      crook    7204: @c nac-> I agree. I started out by putting in the example, then realised
                   7205: @c that it was non-ANS, so wrote more words around it. I hope this
                   7206: @c re-written version is acceptable to you. I do want to keep the example
                   7207: @c as it is helpful for showing what is and what is not portable, particularly
                   7208: @c where it outlaws a style in common use.
                   7209: 
1.35      anton    7210: 
1.44      crook    7211: @code{[} and @code{]} also give you the ability to switch into compile
                   7212: state and back, but we cannot think of any useful Standard application
                   7213: for this ability. Pre-ANS Forth textbooks have examples like this:
1.29      crook    7214: 
                   7215: @example
                   7216: : AA ." this is A" ;
                   7217: : BB ." this is B" ;
                   7218: : CC ." this is C" ;
                   7219: 
1.44      crook    7220: create table ] aa bb cc [
                   7221: 
1.29      crook    7222: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
                   7223:   cells table + @ execute ;
                   7224: @end example
                   7225: 
1.44      crook    7226: This example builds a jump table; @code{0 go} will display ``@code{this
                   7227: is A}''. Using @code{[} and @code{]} in this example is equivalent to
                   7228: defining @code{table} like this:
1.29      crook    7229: 
                   7230: @example
1.44      crook    7231: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
1.29      crook    7232: @end example
                   7233: 
1.44      crook    7234: The problem with this code is that the definition of @code{table} is not
                   7235: portable -- it @i{compile}s execution tokens into code space. Whilst it
                   7236: @i{may} work on systems where code space and data space co-incide, the
1.29      crook    7237: Standard only allows data space to be assigned for a @code{CREATE}d
                   7238: word. In addition, the Standard only allows @code{@@} to access data
                   7239: space, whilst this example is using it to access code space. The only
                   7240: portable, Standard way to build this table is to build it in data space,
                   7241: like this:
                   7242: 
                   7243: @example
                   7244: create table ' aa , ' bb , ' cc ,
                   7245: @end example
                   7246: 
1.26      crook    7247: doc-state
                   7248: doc-[
                   7249: doc-]
1.1       anton    7250: 
1.44      crook    7251: 
1.26      crook    7252: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
                   7253: @subsection Literals
                   7254: @cindex Literals
1.21      crook    7255: 
1.29      crook    7256: Often, you want to use a number within a colon definition. When you do
                   7257: this, the text interpreter automatically compiles the number as a
                   7258: @i{literal}. A literal is a number whose run-time effect is to be pushed
                   7259: onto the stack.  If you had to do some maths to generate the number, you
                   7260: might write it like this:
                   7261: 
                   7262: @example
                   7263: : HOUR-TO-SEC ( n1 -- n2 )
                   7264:   60 *      \ to minutes
                   7265:   60 * ;    \ to seconds
                   7266: @end example
                   7267: 
                   7268: It is very clear what this definition is doing, but it's inefficient
                   7269: since it is performing 2 multiples at run-time. An alternative would be
                   7270: to write:
                   7271: 
                   7272: @example
                   7273: : HOUR-TO-SEC ( n1 -- n2 )
                   7274:   3600 * ;  \ to seconds
                   7275: @end example
                   7276: 
                   7277: Which does the same thing, and has the advantage of using a single
                   7278: multiply. Ideally, we'd like the efficiency of the second with the
                   7279: readability of the first.
                   7280: 
                   7281: @code{Literal} allows us to achieve that. It takes a number from the
                   7282: stack and lays it down in the current definition just as though the
                   7283: number had been typed directly into the definition. Our first attempt
                   7284: might look like this:
                   7285: 
                   7286: @example
                   7287: 60          \ mins per hour
                   7288: 60 *        \ seconds per minute
                   7289: : HOUR-TO-SEC ( n1 -- n2 )
                   7290:   Literal * ;  \ to seconds
                   7291: @end example
                   7292: 
                   7293: But this produces the error message @code{unstructured}. What happened?
                   7294: The stack notation for @code{:} is (@i{ -- colon-sys}) and the size of
                   7295: @i{colon-sys} is implementation-defined. In other words, once we start a
                   7296: colon definition we can't portably access anything that was on the stack
                   7297: before the definition began@footnote{@cite{Two Problems in ANS Forth},
                   7298: by Thomas Worthington; Forth Dimensions 20(2) pages 32--34 describes
                   7299: some situations where you might want to access stack items above
                   7300: colon-sys, and provides a solution to the problem.}. The correct way of
                   7301: solving this problem in this instance is to use @code{[ ]} like this:
                   7302: 
                   7303: @example
                   7304: : HOUR-TO-SEC ( n1 -- n2 )
                   7305:   [ 60          \ minutes per hour
                   7306:     60 * ]      \ seconds per minute
                   7307:   LITERAL * ;   \ to seconds
                   7308: @end example
1.23      crook    7309: 
1.44      crook    7310: 
1.26      crook    7311: doc-literal
                   7312: doc-]L
                   7313: doc-2literal
                   7314: doc-fliteral
1.1       anton    7315: 
1.44      crook    7316: 
1.48    ! anton    7317: @node Interpreter Directives,  , Literals, The Text Interpreter
1.26      crook    7318: @subsection Interpreter Directives
                   7319: @cindex interpreter directives
1.1       anton    7320: 
1.29      crook    7321: These words are usually used in interpret state; typically to control
                   7322: which parts of a source file are processed by the text
1.26      crook    7323: interpreter. There are only a few ANS Forth Standard words, but Gforth
                   7324: supplements these with a rich set of immediate control structure words
                   7325: to compensate for the fact that the non-immediate versions can only be
1.29      crook    7326: used in compile state (@pxref{Control Structures}). Typical usages:
                   7327: 
                   7328: @example
                   7329: FALSE Constant ASSEMBLER
                   7330: .
                   7331: .
                   7332: ASSEMBLER [IF]
                   7333: : ASSEMBLER-FEATURE
                   7334:   ...
                   7335: ;
                   7336: [ENDIF]
                   7337: .
                   7338: .
                   7339: : SEE
                   7340:   ... \ general-purpose SEE code
                   7341:   [ ASSEMBLER [IF] ]
                   7342:   ... \ assembler-specific SEE code
                   7343:   [ [ENDIF] ]
                   7344: ;
                   7345: @end example
1.1       anton    7346: 
1.44      crook    7347: 
1.26      crook    7348: doc-[IF]
                   7349: doc-[ELSE]
                   7350: doc-[THEN]
                   7351: doc-[ENDIF]
1.1       anton    7352: 
1.26      crook    7353: doc-[IFDEF]
                   7354: doc-[IFUNDEF]
1.1       anton    7355: 
1.26      crook    7356: doc-[?DO]
                   7357: doc-[DO]
                   7358: doc-[FOR]
                   7359: doc-[LOOP]
                   7360: doc-[+LOOP]
                   7361: doc-[NEXT]
1.1       anton    7362: 
1.26      crook    7363: doc-[BEGIN]
                   7364: doc-[UNTIL]
                   7365: doc-[AGAIN]
                   7366: doc-[WHILE]
                   7367: doc-[REPEAT]
1.1       anton    7368: 
1.27      crook    7369: 
1.26      crook    7370: @c -------------------------------------------------------------
1.47      crook    7371: @node Word Lists, Environmental Queries, The Text Interpreter, Words
1.26      crook    7372: @section Word Lists
                   7373: @cindex word lists
1.32      anton    7374: @cindex header space
1.1       anton    7375: 
1.36      anton    7376: A wordlist is a list of named words; you can add new words and look up
                   7377: words by name (and you can remove words in a restricted way with
                   7378: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
                   7379: 
                   7380: @cindex search order stack
                   7381: The text interpreter searches the wordlists present in the search order
                   7382: (a stack of wordlists), from the top to the bottom.  Within each
                   7383: wordlist, the search starts conceptually at the newest word; i.e., if
                   7384: two words in a wordlist have the same name, the newer word is found.
1.1       anton    7385: 
1.26      crook    7386: @cindex compilation word list
1.36      anton    7387: New words are added to the @dfn{compilation wordlist} (aka current
                   7388: wordlist).
1.1       anton    7389: 
1.36      anton    7390: @cindex wid
                   7391: A word list is identified by a cell-sized word list identifier (@i{wid})
                   7392: in much the same way as a file is identified by a file handle. The
                   7393: numerical value of the wid has no (portable) meaning, and might change
                   7394: from session to session.
1.1       anton    7395: 
1.29      crook    7396: The ANS Forth ``Search order'' word set is intended to provide a set of
                   7397: low-level tools that allow various different schemes to be
1.26      crook    7398: implemented. Gforth provides @code{vocabulary}, a traditional Forth
                   7399: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
1.45      crook    7400: Forth.
1.1       anton    7401: 
1.27      crook    7402: @comment TODO: locals section refers to here, saying that every word list (aka
                   7403: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.1       anton    7404: 
1.45      crook    7405: @comment TODO: document markers, reveal, tables, mappedwordlist
                   7406: 
                   7407: @comment the gforthman- prefix is used to pick out the true definition of a
1.27      crook    7408: @comment word from the source files, rather than some alias.
1.44      crook    7409: 
1.26      crook    7410: doc-forth-wordlist
                   7411: doc-definitions
                   7412: doc-get-current
                   7413: doc-set-current
                   7414: doc-get-order
1.45      crook    7415: doc---gforthman-set-order
1.26      crook    7416: doc-wordlist
1.30      anton    7417: doc-table
1.36      anton    7418: doc-push-order
                   7419: doc-previous
1.26      crook    7420: doc-also
1.45      crook    7421: doc---gforthman-forth
1.26      crook    7422: doc-only
1.45      crook    7423: doc---gforthman-order
1.15      anton    7424: 
1.26      crook    7425: doc-find
                   7426: doc-search-wordlist
1.15      anton    7427: 
1.26      crook    7428: doc-words
                   7429: doc-vlist
1.44      crook    7430: @c doc-words-deferred
1.1       anton    7431: 
1.26      crook    7432: doc-mappedwordlist
                   7433: doc-root
                   7434: doc-vocabulary
                   7435: doc-seal
                   7436: doc-vocs
                   7437: doc-current
                   7438: doc-context
1.1       anton    7439: 
1.44      crook    7440: 
1.26      crook    7441: @menu
                   7442: * Why use word lists?::
                   7443: * Word list examples::
                   7444: @end menu
                   7445: 
                   7446: @node Why use word lists?, Word list examples, Word Lists, Word Lists
                   7447: @subsection Why use word lists?
                   7448: @cindex word lists - why use them?
                   7449: 
1.29      crook    7450: Here are some reasons for using multiple word lists:
1.26      crook    7451: 
                   7452: @itemize @bullet
                   7453: @item
1.32      anton    7454: To improve compilation speed by reducing the number of header space
1.26      crook    7455: entries that must be searched. This is achieved by creating a new
                   7456: word list that contains all of the definitions that are used in the
                   7457: definition of a Forth system but which would not usually be used by
                   7458: programs running on that system. That word list would be on the search
                   7459: list when the Forth system was compiled but would be removed from the
                   7460: search list for normal operation. This can be a useful technique for
                   7461: low-performance systems (for example, 8-bit processors in embedded
                   7462: systems) but is unlikely to be necessary in high-performance desktop
                   7463: systems.
                   7464: @item
                   7465: To prevent a set of words from being used outside the context in which
                   7466: they are valid. Two classic examples of this are an integrated editor
                   7467: (all of the edit commands are defined in a separate word list; the
                   7468: search order is set to the editor word list when the editor is invoked;
                   7469: the old search order is restored when the editor is terminated) and an
                   7470: integrated assembler (the op-codes for the machine are defined in a
                   7471: separate word list which is used when a @code{CODE} word is defined).
                   7472: @item
                   7473: To prevent a name-space clash between multiple definitions with the same
                   7474: name. For example, when building a cross-compiler you might have a word
                   7475: @code{IF} that generates conditional code for your target system. By
                   7476: placing this definition in a different word list you can control whether
                   7477: the host system's @code{IF} or the target system's @code{IF} get used in
                   7478: any particular context by controlling the order of the word lists on the
                   7479: search order stack.
                   7480: @end itemize
1.1       anton    7481: 
1.48    ! anton    7482: @node Word list examples,  , Why use word lists?, Word Lists
1.26      crook    7483: @subsection Word list examples
                   7484: @cindex word lists - examples
1.1       anton    7485: 
1.26      crook    7486: Here is an example of creating and using a new wordlist using ANS
                   7487: Forth Standard words:
1.1       anton    7488: 
                   7489: @example
1.26      crook    7490: wordlist constant my-new-words-wordlist
                   7491: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
1.21      crook    7492: 
1.26      crook    7493: \ add it to the search order
                   7494: also my-new-words
1.21      crook    7495: 
1.26      crook    7496: \ alternatively, add it to the search order and make it
                   7497: \ the compilation word list
                   7498: also my-new-words definitions
                   7499: \ type "order" to see the problem
1.21      crook    7500: @end example
                   7501: 
1.26      crook    7502: The problem with this example is that @code{order} has no way to
                   7503: associate the name @code{my-new-words} with the wid of the word list (in
                   7504: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
                   7505: that has no associated name). There is no Standard way of associating a
                   7506: name with a wid.
                   7507: 
                   7508: In Gforth, this example can be re-coded using @code{vocabulary}, which
                   7509: associates a name with a wid:
1.21      crook    7510: 
1.26      crook    7511: @example
                   7512: vocabulary my-new-words
1.21      crook    7513: 
1.26      crook    7514: \ add it to the search order
1.45      crook    7515: also my-new-words
1.21      crook    7516: 
1.26      crook    7517: \ alternatively, add it to the search order and make it
                   7518: \ the compilation word list
                   7519: my-new-words definitions
                   7520: \ type "order" to see that the problem is solved
                   7521: @end example
1.23      crook    7522: 
1.26      crook    7523: @c -------------------------------------------------------------
                   7524: @node Environmental Queries, Files, Word Lists, Words
                   7525: @section Environmental Queries
                   7526: @cindex environmental queries
1.21      crook    7527: 
1.26      crook    7528: ANS Forth introduced the idea of ``environmental queries'' as a way
                   7529: for a program running on a system to determine certain characteristics of the system.
                   7530: The Standard specifies a number of strings that might be recognised by a system.
1.21      crook    7531: 
1.32      anton    7532: The Standard requires that the header space used for environmental queries
                   7533: be distinct from the header space used for definitions.
1.21      crook    7534: 
1.26      crook    7535: Typically, environmental queries are supported by creating a set of
1.29      crook    7536: definitions in a word list that is @i{only} used during environmental
1.26      crook    7537: queries; that is what Gforth does. There is no Standard way of adding
                   7538: definitions to the set of recognised environmental queries, but any
                   7539: implementation that supports the loading of optional word sets must have
                   7540: some mechanism for doing this (after loading the word set, the
                   7541: associated environmental query string must return @code{true}). In
                   7542: Gforth, the word list used to honour environmental queries can be
                   7543: manipulated just like any other word list.
1.21      crook    7544: 
1.44      crook    7545: 
1.26      crook    7546: doc-environment?
                   7547: doc-environment-wordlist
1.21      crook    7548: 
1.26      crook    7549: doc-gforth
                   7550: doc-os-class
1.21      crook    7551: 
1.44      crook    7552: 
1.26      crook    7553: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
                   7554: returning two items on the stack, querying it using @code{environment?}
                   7555: will return an additional item; the @code{true} flag that shows that the
                   7556: string was recognised.
1.21      crook    7557: 
1.26      crook    7558: @comment TODO Document the standard strings or note where they are documented herein
1.21      crook    7559: 
1.26      crook    7560: Here are some examples of using environmental queries:
1.21      crook    7561: 
1.26      crook    7562: @example
                   7563: s" address-unit-bits" environment? 0=
                   7564: [IF]
                   7565:      cr .( environmental attribute address-units-bits unknown... ) cr
                   7566: [THEN]
1.21      crook    7567: 
1.26      crook    7568: s" block" environment? [IF] DROP include block.fs [THEN]
1.21      crook    7569: 
1.26      crook    7570: s" gforth" environment? [IF] 2DROP include compat/vocabulary.fs [THEN]
1.21      crook    7571: 
1.26      crook    7572: s" gforth" environment? [IF] .( Gforth version ) TYPE
                   7573:                         [ELSE] .( Not Gforth..) [THEN]
                   7574: @end example
1.21      crook    7575: 
                   7576: 
1.26      crook    7577: Here is an example of adding a definition to the environment word list:
1.21      crook    7578: 
1.26      crook    7579: @example
                   7580: get-current environment-wordlist set-current
                   7581: true constant block
                   7582: true constant block-ext
                   7583: set-current
                   7584: @end example
1.21      crook    7585: 
1.26      crook    7586: You can see what definitions are in the environment word list like this:
1.21      crook    7587: 
1.26      crook    7588: @example
                   7589: get-order 1+ environment-wordlist swap set-order words previous
                   7590: @end example
1.21      crook    7591: 
                   7592: 
1.26      crook    7593: @c -------------------------------------------------------------
                   7594: @node Files, Blocks, Environmental Queries, Words
                   7595: @section Files
1.28      crook    7596: @cindex files
                   7597: @cindex I/O - file-handling
1.21      crook    7598: 
1.26      crook    7599: Gforth provides facilities for accessing files that are stored in the
                   7600: host operating system's file-system. Files that are processed by Gforth
                   7601: can be divided into two categories:
1.21      crook    7602: 
1.23      crook    7603: @itemize @bullet
                   7604: @item
1.29      crook    7605: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23      crook    7606: @item
1.29      crook    7607: Files that are processed by some other program (@dfn{general files}).
1.26      crook    7608: @end itemize
                   7609: 
1.45      crook    7610: doc-loadfilename
                   7611: doc-sourcefilename
                   7612: doc-sourceline#
                   7613: 
1.26      crook    7614: @menu
1.48    ! anton    7615: * Forth source files::          
        !          7616: * General files::               
        !          7617: * Search Paths::                
1.26      crook    7618: @end menu
                   7619: 
1.21      crook    7620: 
1.26      crook    7621: @c -------------------------------------------------------------
                   7622: @node Forth source files, General files, Files, Files
                   7623: @subsection Forth source files
                   7624: @cindex including files
                   7625: @cindex Forth source files
1.21      crook    7626: 
1.26      crook    7627: The simplest way to interpret the contents of a file is to use one of
                   7628: these two formats:
1.21      crook    7629: 
1.26      crook    7630: @example
                   7631: include mysource.fs
                   7632: s" mysource.fs" included
                   7633: @end example
1.21      crook    7634: 
1.26      crook    7635: Sometimes you want to include a file only if it is not included already
                   7636: (by, say, another source file). In that case, you can use one of these
1.45      crook    7637: three formats:
1.21      crook    7638: 
1.26      crook    7639: @example
                   7640: require mysource.fs
                   7641: needs mysource.fs
                   7642: s" mysource.fs" required
                   7643: @end example
1.21      crook    7644: 
1.26      crook    7645: @cindex stack effect of included files
                   7646: @cindex including files, stack effect
1.45      crook    7647: It is good practice to write your source files such that interpreting them
                   7648: does not change the stack. Source files designed in this way can be used with
1.26      crook    7649: @code{required} and friends without complications. For example:
1.21      crook    7650: 
1.26      crook    7651: @example
                   7652: 1 require foo.fs drop
                   7653: @end example
1.21      crook    7654: 
1.44      crook    7655: 
1.26      crook    7656: doc-include-file
                   7657: doc-included
1.28      crook    7658: doc-included?
1.26      crook    7659: doc-include
                   7660: doc-required
                   7661: doc-require
                   7662: doc-needs
1.28      crook    7663: doc-init-included-files
1.21      crook    7664: 
1.44      crook    7665: 
1.26      crook    7666: A definition in ANS Forth for @code{required} is provided in
                   7667: @file{compat/required.fs}.
1.21      crook    7668: 
1.26      crook    7669: @c -------------------------------------------------------------
                   7670: @node General files, Search Paths, Forth source files, Files
                   7671: @subsection General files
                   7672: @cindex general files
                   7673: @cindex file-handling
1.21      crook    7674: 
1.26      crook    7675: Files are opened/created by name and type. The following types are
                   7676: recognised:
1.1       anton    7677: 
1.44      crook    7678: 
1.26      crook    7679: doc-r/o
                   7680: doc-r/w
                   7681: doc-w/o
                   7682: doc-bin
1.1       anton    7683: 
1.44      crook    7684: 
1.26      crook    7685: When a file is opened/created, it returns a file identifier,
1.29      crook    7686: @i{wfileid} that is used for all other file commands. All file
                   7687: commands also return a status value, @i{wior}, that is 0 for a
1.26      crook    7688: successful operation and an implementation-defined non-zero value in the
                   7689: case of an error.
1.21      crook    7690: 
1.44      crook    7691: 
1.26      crook    7692: doc-open-file
                   7693: doc-create-file
1.21      crook    7694: 
1.26      crook    7695: doc-close-file
                   7696: doc-delete-file
                   7697: doc-rename-file
                   7698: doc-read-file
                   7699: doc-read-line
                   7700: doc-write-file
                   7701: doc-write-line
                   7702: doc-emit-file
                   7703: doc-flush-file
1.21      crook    7704: 
1.26      crook    7705: doc-file-status
                   7706: doc-file-position
                   7707: doc-reposition-file
                   7708: doc-file-size
                   7709: doc-resize-file
1.21      crook    7710: 
1.44      crook    7711: 
1.26      crook    7712: @c ---------------------------------------------------------
1.48    ! anton    7713: @node Search Paths,  , General files, Files
1.26      crook    7714: @subsection Search Paths
                   7715: @cindex path for @code{included}
                   7716: @cindex file search path
                   7717: @cindex @code{include} search path
                   7718: @cindex search path for files
1.21      crook    7719: 
1.26      crook    7720: If you specify an absolute filename (i.e., a filename starting with
                   7721: @file{/} or @file{~}, or with @file{:} in the second position (as in
                   7722: @samp{C:...})) for @code{included} and friends, that file is included
                   7723: just as you would expect.
1.21      crook    7724: 
1.26      crook    7725: For relative filenames, Gforth uses a search path similar to Forth's
                   7726: search order (@pxref{Word Lists}). It tries to find the given filename
                   7727: in the directories present in the path, and includes the first one it
                   7728: finds. There are separate search paths for Forth source files and
                   7729: general files.
1.21      crook    7730: 
1.26      crook    7731: If the search path contains the directory @file{.} (as it should), this
                   7732: refers to the directory that the present file was @code{included}
                   7733: from. This allows files to include other files relative to their own
                   7734: position (irrespective of the current working directory or the absolute
                   7735: position).  This feature is essential for libraries consisting of
                   7736: several files, where a file may include other files from the library.
                   7737: It corresponds to @code{#include "..."} in C. If the current input
                   7738: source is not a file, @file{.} refers to the directory of the innermost
                   7739: file being included, or, if there is no file being included, to the
                   7740: current working directory.
1.21      crook    7741: 
1.26      crook    7742: Use @file{~+} to refer to the current working directory (as in the
                   7743: @code{bash}).
1.1       anton    7744: 
1.26      crook    7745: If the filename starts with @file{./}, the search path is not searched
                   7746: (just as with absolute filenames), and the @file{.} has the same meaning
                   7747: as described above.
1.1       anton    7748: 
1.48    ! anton    7749: @menu
        !          7750: * Forth Search Paths::          
        !          7751: * General Search Paths::        
        !          7752: @end menu
        !          7753: 
1.26      crook    7754: @c ---------------------------------------------------------
1.48    ! anton    7755: @node Forth Search Paths, General Search Paths, Search Paths, Search Paths
1.26      crook    7756: @subsubsection Forth Search Paths
1.28      crook    7757: @cindex search path control - Forth
1.5       anton    7758: 
1.26      crook    7759: The search path is initialized when you start Gforth (@pxref{Invoking
                   7760: Gforth}). You can display it and change it using these words:
1.5       anton    7761: 
1.44      crook    7762: 
1.26      crook    7763: doc-.fpath
                   7764: doc-fpath+
                   7765: doc-fpath=
                   7766: doc-open-fpath-file
1.5       anton    7767: 
1.44      crook    7768: 
                   7769: @noindent
1.26      crook    7770: Here is an example of using @code{fpath} and @code{require}:
1.5       anton    7771: 
1.26      crook    7772: @example
                   7773: fpath= /usr/lib/forth/|./
                   7774: require timer.fs
                   7775: @end example
1.5       anton    7776: 
1.26      crook    7777: @c ---------------------------------------------------------
1.48    ! anton    7778: @node General Search Paths,  , Forth Search Paths, Search Paths
1.26      crook    7779: @subsubsection General Search Paths
                   7780: @cindex search path control - for user applications
1.5       anton    7781: 
1.26      crook    7782: Your application may need to search files in several directories, like
                   7783: @code{included} does. To facilitate this, Gforth allows you to define
                   7784: and use your own search paths, by providing generic equivalents of the
                   7785: Forth search path words:
1.5       anton    7786: 
1.44      crook    7787: 
1.26      crook    7788: doc-.path
                   7789: doc-path+
                   7790: doc-path=
                   7791: doc-open-path-file
1.5       anton    7792: 
1.44      crook    7793: 
1.26      crook    7794: Here's an example of creating a search path:
1.5       anton    7795: 
1.26      crook    7796: @example
                   7797: \ Make a buffer for the path:
                   7798: create mypath   100 chars ,     \ maximum length (is checked)
                   7799:                 0 ,             \ real len
                   7800:                 100 chars allot \ space for path
                   7801: @end example
1.5       anton    7802: 
1.26      crook    7803: @c -------------------------------------------------------------
                   7804: @node Blocks, Other I/O, Files, Words
                   7805: @section Blocks
1.28      crook    7806: @cindex I/O - blocks
                   7807: @cindex blocks
                   7808: 
                   7809: When you run Gforth on a modern desk-top computer, it runs under the
                   7810: control of an operating system which provides certain services.  One of
                   7811: these services is @var{file services}, which allows Forth source code
                   7812: and data to be stored in files and read into Gforth (@pxref{Files}).
                   7813: 
                   7814: Traditionally, Forth has been an important programming language on
                   7815: systems where it has interfaced directly to the underlying hardware with
                   7816: no intervening operating system. Forth provides a mechanism, called
1.29      crook    7817: @dfn{blocks}, for accessing mass storage on such systems.
1.28      crook    7818: 
                   7819: A block is a 1024-byte data area, which can be used to hold data or
                   7820: Forth source code. No structure is imposed on the contents of the
                   7821: block. A block is identified by its number; blocks are numbered
                   7822: contiguously from 1 to an implementation-defined maximum.
                   7823: 
                   7824: A typical system that used blocks but no operating system might use a
                   7825: single floppy-disk drive for mass storage, with the disks formatted to
                   7826: provide 256-byte sectors. Blocks would be implemented by assigning the
                   7827: first four sectors of the disk to block 1, the second four sectors to
                   7828: block 2 and so on, up to the limit of the capacity of the disk. The disk
                   7829: would not contain any file system information, just the set of blocks.
                   7830: 
1.29      crook    7831: @cindex blocks file
1.28      crook    7832: On systems that do provide file services, blocks are typically
1.29      crook    7833: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28      crook    7834: file}.  The size of the blocks file will be an exact multiple of 1024
                   7835: bytes, corresponding to the number of blocks it contains. This is the
                   7836: mechanism that Gforth uses.
                   7837: 
1.29      crook    7838: @cindex @file{blocks.fb}
1.28      crook    7839: Only 1 blocks file can be open at a time. If you use block words without
                   7840: having specified a blocks file, Gforth defaults to the blocks file
                   7841: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
                   7842: locate a blocks file (@pxref{Forth Search Paths}).
                   7843: 
1.29      crook    7844: @cindex block buffers
1.28      crook    7845: When you read and write blocks under program control, Gforth uses a
1.29      crook    7846: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28      crook    7847: not used when you use @code{load} to interpret the contents of a block.
                   7848: 
                   7849: The behaviour of the block buffers is directly analagous to that of a
                   7850: cache. Each block buffer has three states:
                   7851: 
                   7852: @itemize @bullet
                   7853: @item
                   7854: Unassigned
                   7855: @item
                   7856: Assigned-clean
                   7857: @item
                   7858: Assigned-dirty
                   7859: @end itemize
                   7860: 
1.29      crook    7861: Initially, all block buffers are @i{unassigned}. In order to access a
1.28      crook    7862: block, the block (specified by its block number) must be assigned to a
                   7863: block buffer.
                   7864: 
                   7865: The assignment of a block to a block buffer is performed by @code{block}
                   7866: or @code{buffer}. Use @code{block} when you wish to modify the existing
                   7867: contents of a block. Use @code{buffer} when you don't care about the
                   7868: existing contents of the block@footnote{The ANS Forth definition of
1.35      anton    7869: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28      crook    7870: with the particular block is already stored in a block buffer due to an
                   7871: earlier @code{block} command, @code{buffer} will return that block
                   7872: buffer and the existing contents of the block will be
                   7873: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29      crook    7874: block buffer for the block.}.
1.28      crook    7875: 
1.47      crook    7876: Once a block has been assigned to a block buffer using @code{block} or
                   7877: @code{buffer}, that block buffer becomes the @i{current block buffer}
                   7878: and its state changes to @i{assigned-clean}. Data may only be
                   7879: manipulated (read or written) within the current block buffer.
                   7880: 
                   7881: When the contents of the current block buffer has been modified it is
1.48    ! anton    7882: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
        !          7883: either abandon the changes (by doing nothing) or commit the changes,
        !          7884: using @code{update}. Using @code{update} does not change the blocks
        !          7885: file; it simply changes a block buffer's state to @i{assigned-dirty}.
1.28      crook    7886: 
1.29      crook    7887: The word @code{flush} causes all @i{assigned-dirty} blocks to be
1.28      crook    7888: written back to the blocks file on disk. Leaving Gforth using @code{bye}
                   7889: also causes a @code{flush} to be performed.
                   7890: 
1.29      crook    7891: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28      crook    7892: algorithm to assign a block buffer to a block. That means that any
                   7893: particular block can only be assigned to one specific block buffer,
1.29      crook    7894: called (for the particular operation) the @i{victim buffer}. If the
1.47      crook    7895: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
                   7896: the new block immediately. If it is @i{assigned-dirty} its current
                   7897: contents are written back to the blocks file on disk before it is
1.28      crook    7898: allocated to the new block.
                   7899: 
                   7900: Although no structure is imposed on the contents of a block, it is
                   7901: traditional to display the contents as 16 lines each of 64 characters.  A
                   7902: block provides a single, continuous stream of input (for example, it
                   7903: acts as a single parse area) -- there are no end-of-line characters
                   7904: within a block, and no end-of-file character at the end of a
                   7905: block. There are two consequences of this:
1.26      crook    7906: 
1.28      crook    7907: @itemize @bullet
                   7908: @item
                   7909: The last character of one line wraps straight into the first character
                   7910: of the following line
                   7911: @item
                   7912: The word @code{\} -- comment to end of line -- requires special
                   7913: treatment; in the context of a block it causes all characters until the
                   7914: end of the current 64-character ``line'' to be ignored.
                   7915: @end itemize
                   7916: 
                   7917: In Gforth, when you use @code{block} with a non-existent block number,
1.45      crook    7918: the current blocks file will be extended to the appropriate size and the
1.28      crook    7919: block buffer will be initialised with spaces.
                   7920: 
1.47      crook    7921: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
                   7922: for details) but doesn't encourage the use of blocks; the mechanism is
                   7923: only provided for backward compatibility -- ANS Forth requires blocks to
                   7924: be available when files are.
1.28      crook    7925: 
                   7926: Common techniques that are used when working with blocks include:
                   7927: 
                   7928: @itemize @bullet
                   7929: @item
                   7930: A screen editor that allows you to edit blocks without leaving the Forth
                   7931: environment.
                   7932: @item
                   7933: Shadow screens; where every code block has an associated block
                   7934: containing comments (for example: code in odd block numbers, comments in
                   7935: even block numbers). Typically, the block editor provides a convenient
                   7936: mechanism to toggle between code and comments.
                   7937: @item
                   7938: Load blocks; a single block (typically block 1) contains a number of
                   7939: @code{thru} commands which @code{load} the whole of the application.
                   7940: @end itemize
1.26      crook    7941: 
1.29      crook    7942: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
                   7943: integrated into a Forth programming environment.
1.26      crook    7944: 
                   7945: @comment TODO what about errors on open-blocks?
1.44      crook    7946: 
1.26      crook    7947: doc-open-blocks
                   7948: doc-use
                   7949: doc-get-block-fid
                   7950: doc-block-position
1.28      crook    7951: 
                   7952: doc-scr
                   7953: doc-list
                   7954: 
1.45      crook    7955: doc---gforthman-block
1.28      crook    7956: doc-buffer
                   7957: 
1.26      crook    7958: doc-update
1.28      crook    7959: doc-updated?
1.26      crook    7960: doc-save-buffers
                   7961: doc-empty-buffers
                   7962: doc-empty-buffer
                   7963: doc-flush
1.28      crook    7964: 
1.26      crook    7965: doc-load
                   7966: doc-thru
                   7967: doc-+load
                   7968: doc-+thru
1.45      crook    7969: doc---gforthman--->
1.26      crook    7970: doc-block-included
                   7971: 
1.44      crook    7972: 
1.26      crook    7973: @c -------------------------------------------------------------
                   7974: @node Other I/O, Programming Tools, Blocks, Words
                   7975: @section Other I/O
1.28      crook    7976: @cindex I/O - keyboard and display
1.26      crook    7977: 
                   7978: @menu
                   7979: * Simple numeric output::       Predefined formats
                   7980: * Formatted numeric output::    Formatted (pictured) output
                   7981: * String Formats::              How Forth stores strings in memory
                   7982: * Displaying characters and strings:: Other stuff
                   7983: * Input::                       Input
                   7984: @end menu
                   7985: 
                   7986: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
                   7987: @subsection Simple numeric output
1.28      crook    7988: @cindex numeric output - simple/free-format
1.5       anton    7989: 
1.26      crook    7990: The simplest output functions are those that display numbers from the
                   7991: data or floating-point stacks. Floating-point output is always displayed
                   7992: using base 10. Numbers displayed from the data stack use the value stored
                   7993: in @code{base}.
1.5       anton    7994: 
1.44      crook    7995: 
1.26      crook    7996: doc-.
                   7997: doc-dec.
                   7998: doc-hex.
                   7999: doc-u.
                   8000: doc-.r
                   8001: doc-u.r
                   8002: doc-d.
                   8003: doc-ud.
                   8004: doc-d.r
                   8005: doc-ud.r
                   8006: doc-f.
                   8007: doc-fe.
                   8008: doc-fs.
1.5       anton    8009: 
1.44      crook    8010: 
1.26      crook    8011: Examples of printing the number 1234.5678E23 in the different floating-point output
                   8012: formats are shown below:
1.5       anton    8013: 
                   8014: @example
1.26      crook    8015: f. 123456779999999000000000000.
                   8016: fe. 123.456779999999E24
                   8017: fs. 1.23456779999999E26
1.5       anton    8018: @end example
                   8019: 
                   8020: 
1.26      crook    8021: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
                   8022: @subsection Formatted numeric output
1.28      crook    8023: @cindex formatted numeric output
1.26      crook    8024: @cindex pictured numeric output
1.28      crook    8025: @cindex numeric output - formatted
1.26      crook    8026: 
1.29      crook    8027: Forth traditionally uses a technique called @dfn{pictured numeric
1.26      crook    8028: output} for formatted printing of integers.  In this technique, digits
                   8029: are extracted from the number (using the current output radix defined by
                   8030: @code{base}), converted to ASCII codes and appended to a string that is
                   8031: built in a scratch-pad area of memory (@pxref{core-idef,
                   8032: Implementation-defined options, Implementation-defined
                   8033: options}). Arbitrary characters can be appended to the string during the
                   8034: extraction process. The completed string is specified by an address
                   8035: and length and can be manipulated (@code{TYPE}ed, copied, modified)
                   8036: under program control.
1.5       anton    8037: 
1.26      crook    8038: All of the words described in the previous section for simple numeric
                   8039: output are implemented in Gforth using pictured numeric output.
1.5       anton    8040: 
1.47      crook    8041: Three important things to remember about pictured numeric output:
1.5       anton    8042: 
1.26      crook    8043: @itemize @bullet
                   8044: @item
1.28      crook    8045: It always operates on double-precision numbers; to display a
                   8046: single-precision number, convert it first (@pxref{Double precision} for
                   8047: ways of doing this).
1.26      crook    8048: @item
1.28      crook    8049: It always treats the double-precision number as though it were
                   8050: unsigned. The examples below show ways of printing signed numbers.
1.26      crook    8051: @item
                   8052: The string is built up from right to left; least significant digit first.
                   8053: @end itemize
1.5       anton    8054: 
1.44      crook    8055: 
1.26      crook    8056: doc-<#
1.47      crook    8057: doc-<<#
1.26      crook    8058: doc-#
                   8059: doc-#s
                   8060: doc-hold
                   8061: doc-sign
                   8062: doc-#>
1.47      crook    8063: doc-#>>
1.5       anton    8064: 
1.26      crook    8065: doc-represent
1.5       anton    8066: 
1.44      crook    8067: 
                   8068: @noindent
1.26      crook    8069: Here are some examples of using pictured numeric output:
1.5       anton    8070: 
                   8071: @example
1.26      crook    8072: : my-u. ( u -- )
                   8073:   \ Simplest use of pns.. behaves like Standard u. 
                   8074:   0              \ convert to unsigned double
                   8075:   <#             \ start conversion
                   8076:   #s             \ convert all digits
                   8077:   #>             \ complete conversion
                   8078:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    8079: 
1.26      crook    8080: : cents-only ( u -- )
                   8081:   0              \ convert to unsigned double
                   8082:   <#             \ start conversion
                   8083:   # #            \ convert two least-significant digits
                   8084:   #>             \ complete conversion, discard other digits
                   8085:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    8086: 
1.26      crook    8087: : dollars-and-cents ( u -- )
                   8088:   0              \ convert to unsigned double
                   8089:   <#             \ start conversion
                   8090:   # #            \ convert two least-significant digits
                   8091:   [char] . hold  \ insert decimal point
                   8092:   #s             \ convert remaining digits
                   8093:   [char] $ hold  \ append currency symbol
                   8094:   #>             \ complete conversion
                   8095:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    8096: 
1.26      crook    8097: : my-. ( n -- )
                   8098:   \ handling negatives.. behaves like Standard .
                   8099:   s>d            \ convert to signed double
                   8100:   swap over dabs \ leave sign byte followed by unsigned double
                   8101:   <#             \ start conversion
                   8102:   #s             \ convert all digits
                   8103:   rot sign       \ get at sign byte, append "-" if needed
                   8104:   #>             \ complete conversion
                   8105:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    8106: 
1.26      crook    8107: : account. ( n -- )
                   8108:   \ accountants don't like minus signs, they use braces
                   8109:   \ for negative numbers
                   8110:   s>d            \ convert to signed double
                   8111:   swap over dabs \ leave sign byte followed by unsigned double
                   8112:   <#             \ start conversion
                   8113:   2 pick         \ get copy of sign byte
                   8114:   0< IF [char] ) hold THEN \ right-most character of output
                   8115:   #s             \ convert all digits
                   8116:   rot            \ get at sign byte
                   8117:   0< IF [char] ( hold THEN
                   8118:   #>             \ complete conversion
                   8119:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    8120: @end example
                   8121: 
1.26      crook    8122: Here are some examples of using these words:
1.5       anton    8123: 
                   8124: @example
1.26      crook    8125: 1 my-u. 1
                   8126: hex -1 my-u. decimal FFFFFFFF
                   8127: 1 cents-only 01
                   8128: 1234 cents-only 34
                   8129: 2 dollars-and-cents $0.02
                   8130: 1234 dollars-and-cents $12.34
                   8131: 123 my-. 123
                   8132: -123 my. -123
                   8133: 123 account. 123
                   8134: -456 account. (456)
1.5       anton    8135: @end example
                   8136: 
                   8137: 
1.26      crook    8138: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
                   8139: @subsection String Formats
1.27      crook    8140: @cindex strings - see character strings
                   8141: @cindex character strings - formats
1.28      crook    8142: @cindex I/O - see character strings
1.26      crook    8143: 
1.27      crook    8144: Forth commonly uses two different methods for representing character
                   8145: strings:
1.26      crook    8146: 
                   8147: @itemize @bullet
                   8148: @item
                   8149: @cindex address of counted string
1.45      crook    8150: @cindex counted string
1.29      crook    8151: As a @dfn{counted string}, represented by a @i{c-addr}. The char
                   8152: addressed by @i{c-addr} contains a character-count, @i{n}, of the
                   8153: string and the string occupies the subsequent @i{n} char addresses in
1.26      crook    8154: memory.
                   8155: @item
1.29      crook    8156: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
                   8157: of the string in characters, and @i{c-addr} is the address of the
1.26      crook    8158: first byte of the string.
                   8159: @end itemize
                   8160: 
                   8161: ANS Forth encourages the use of the second format when representing
                   8162: strings on the stack, whilst conceeding that the counted string format
                   8163: remains useful as a way of storing strings in memory.
                   8164: 
1.44      crook    8165: 
1.26      crook    8166: doc-count
                   8167: 
1.44      crook    8168: 
1.26      crook    8169: @xref{Memory Blocks} for words that move, copy and search
                   8170: for strings. @xref{Displaying characters and strings,} for words that
                   8171: display characters and strings.
                   8172: 
                   8173: 
                   8174: @node Displaying characters and strings, Input, String Formats, Other I/O
                   8175: @subsection Displaying characters and strings
1.27      crook    8176: @cindex characters - compiling and displaying
                   8177: @cindex character strings - compiling and displaying
1.26      crook    8178: 
                   8179: This section starts with a glossary of Forth words and ends with a set
                   8180: of examples.
                   8181: 
1.44      crook    8182: 
1.26      crook    8183: doc-bl
                   8184: doc-space
                   8185: doc-spaces
                   8186: doc-emit
                   8187: doc-toupper
                   8188: doc-."
                   8189: doc-.(
                   8190: doc-type
1.44      crook    8191: doc-typewhite
1.26      crook    8192: doc-cr
1.27      crook    8193: @cindex cursor control
1.26      crook    8194: doc-at-xy
                   8195: doc-page
                   8196: doc-s"
                   8197: doc-c"
                   8198: doc-char
                   8199: doc-[char]
                   8200: doc-sliteral
                   8201: 
1.44      crook    8202: 
                   8203: @noindent
1.26      crook    8204: As an example, consider the following text, stored in a file @file{test.fs}:
1.5       anton    8205: 
                   8206: @example
1.26      crook    8207: .( text-1)
                   8208: : my-word
                   8209:   ." text-2" cr
                   8210:   .( text-3)
                   8211: ;
                   8212: 
                   8213: ." text-4"
                   8214: 
                   8215: : my-char
                   8216:   [char] ALPHABET emit
                   8217:   char emit
                   8218: ;
1.5       anton    8219: @end example
                   8220: 
1.26      crook    8221: When you load this code into Gforth, the following output is generated:
1.5       anton    8222: 
1.26      crook    8223: @example
1.30      anton    8224: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26      crook    8225: @end example
1.5       anton    8226: 
1.26      crook    8227: @itemize @bullet
                   8228: @item
                   8229: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
                   8230: is an immediate word; it behaves in the same way whether it is used inside
                   8231: or outside a colon definition.
                   8232: @item
                   8233: Message @code{text-4} is displayed because of Gforth's added interpretation
                   8234: semantics for @code{."}.
                   8235: @item
1.29      crook    8236: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26      crook    8237: performs the compilation semantics for @code{."} within the definition of
                   8238: @code{my-word}.
                   8239: @end itemize
1.5       anton    8240: 
1.26      crook    8241: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5       anton    8242: 
1.26      crook    8243: @example
1.30      anton    8244: @kbd{my-word @key{RET}} text-2
1.26      crook    8245:  ok
1.30      anton    8246: @kbd{my-char fred @key{RET}} Af ok
                   8247: @kbd{my-char jim @key{RET}} Aj ok
1.26      crook    8248: @end example
1.5       anton    8249: 
                   8250: @itemize @bullet
                   8251: @item
1.26      crook    8252: Message @code{text-2} is displayed because of the run-time behaviour of
                   8253: @code{."}.
                   8254: @item
                   8255: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
                   8256: on the stack at run-time. @code{emit} always displays the character
                   8257: when @code{my-char} is executed.
                   8258: @item
                   8259: @code{char} parses a string at run-time and the second @code{emit} displays
                   8260: the first character of the string.
1.5       anton    8261: @item
1.26      crook    8262: If you type @code{see my-char} you can see that @code{[char]} discarded
                   8263: the text ``LPHABET'' and only compiled the display code for ``A'' into the
                   8264: definition of @code{my-char}.
1.5       anton    8265: @end itemize
                   8266: 
                   8267: 
                   8268: 
1.48    ! anton    8269: @node Input,  , Displaying characters and strings, Other I/O
1.26      crook    8270: @subsection Input
                   8271: @cindex input
1.28      crook    8272: @cindex I/O - see input
                   8273: @cindex parsing a string
1.5       anton    8274: 
1.27      crook    8275: @xref{String Formats} for ways of storing character strings in memory.
1.5       anton    8276: 
1.27      crook    8277: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29      crook    8278: @comment then index them
1.27      crook    8279: 
1.44      crook    8280: 
1.27      crook    8281: doc-key
                   8282: doc-key?
1.45      crook    8283: doc-ekey
                   8284: doc-ekey?
                   8285: doc-ekey>char
1.26      crook    8286: doc->number
                   8287: doc->float
                   8288: doc-accept
1.27      crook    8289: doc-pad
                   8290: doc-parse
                   8291: doc-word
                   8292: doc-sword
1.44      crook    8293: doc-(name)
1.27      crook    8294: doc-refill
                   8295: @comment obsolescent words..
                   8296: doc-convert
1.26      crook    8297: doc-query
                   8298: doc-expect
1.27      crook    8299: doc-span
1.5       anton    8300: 
                   8301: 
1.44      crook    8302: 
1.5       anton    8303: @c -------------------------------------------------------------
1.26      crook    8304: @node Programming Tools, Assembler and Code Words, Other I/O, Words
                   8305: @section Programming Tools
                   8306: @cindex programming tools
1.12      anton    8307: 
                   8308: @menu
1.26      crook    8309: * Debugging::                   Simple and quick.
                   8310: * Assertions::                  Making your programs self-checking.
1.46      pazsan   8311: * Singlestep Debugger::         Executing your program word by word.
1.5       anton    8312: @end menu
                   8313: 
1.26      crook    8314: @node Debugging, Assertions, Programming Tools, Programming Tools
                   8315: @subsection Debugging
                   8316: @cindex debugging
1.5       anton    8317: 
1.26      crook    8318: Languages with a slow edit/compile/link/test development loop tend to
                   8319: require sophisticated tracing/stepping debuggers to facilate
                   8320: productive debugging.
1.5       anton    8321: 
1.26      crook    8322: A much better (faster) way in fast-compiling languages is to add
                   8323: printing code at well-selected places, let the program run, look at
                   8324: the output, see where things went wrong, add more printing code, etc.,
                   8325: until the bug is found.
1.5       anton    8326: 
1.26      crook    8327: The simple debugging aids provided in @file{debugs.fs}
                   8328: are meant to support this style of debugging. In addition, there are
                   8329: words for non-destructively inspecting the stack and memory:
1.5       anton    8330: 
1.44      crook    8331: 
1.26      crook    8332: doc-.s
                   8333: doc-f.s
1.5       anton    8334: 
1.44      crook    8335: 
1.29      crook    8336: There is a word @code{.r} but it does @i{not} display the return
1.26      crook    8337: stack! It is used for formatted numeric output.
1.5       anton    8338: 
1.44      crook    8339: 
1.26      crook    8340: doc-depth
                   8341: doc-fdepth
                   8342: doc-clearstack
                   8343: doc-?
                   8344: doc-dump
1.5       anton    8345: 
1.44      crook    8346: 
1.26      crook    8347: The word @code{~~} prints debugging information (by default the source
                   8348: location and the stack contents). It is easy to insert. If you use Emacs
                   8349: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
                   8350: query-replace them with nothing). The deferred words
                   8351: @code{printdebugdata} and @code{printdebugline} control the output of
                   8352: @code{~~}. The default source location output format works well with
                   8353: Emacs' compilation mode, so you can step through the program at the
                   8354: source level using @kbd{C-x `} (the advantage over a stepping debugger
                   8355: is that you can step in any direction and you know where the crash has
                   8356: happened or where the strange data has occurred).
1.5       anton    8357: 
1.26      crook    8358: The default actions of @code{~~} clobber the contents of the pictured
                   8359: numeric output string, so you should not use @code{~~}, e.g., between
                   8360: @code{<#} and @code{#>}.
1.5       anton    8361: 
1.44      crook    8362: 
1.26      crook    8363: doc-~~
                   8364: doc-printdebugdata
                   8365: doc-printdebugline
1.5       anton    8366: 
1.26      crook    8367: doc-see
                   8368: doc-marker
1.5       anton    8369: 
1.44      crook    8370: 
1.26      crook    8371: Here's an example of using @code{marker} at the start of a source file
                   8372: that you are debugging; it ensures that you only ever have one copy of
                   8373: the file's definitions compiled at any time:
1.5       anton    8374: 
1.26      crook    8375: @example
                   8376: [IFDEF] my-code
                   8377:     my-code
                   8378: [ENDIF]
1.5       anton    8379: 
1.26      crook    8380: marker my-code
1.28      crook    8381: init-included-files
1.5       anton    8382: 
1.26      crook    8383: \ .. definitions start here
                   8384: \ .
                   8385: \ .
                   8386: \ end
                   8387: @end example
1.5       anton    8388: 
                   8389: 
                   8390: 
1.26      crook    8391: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
                   8392: @subsection Assertions
                   8393: @cindex assertions
1.5       anton    8394: 
1.26      crook    8395: It is a good idea to make your programs self-checking, especially if you
                   8396: make an assumption that may become invalid during maintenance (for
                   8397: example, that a certain field of a data structure is never zero). Gforth
1.29      crook    8398: supports @dfn{assertions} for this purpose. They are used like this:
1.23      crook    8399: 
1.26      crook    8400: @example
1.29      crook    8401: assert( @i{flag} )
1.26      crook    8402: @end example
1.23      crook    8403: 
1.26      crook    8404: The code between @code{assert(} and @code{)} should compute a flag, that
                   8405: should be true if everything is alright and false otherwise. It should
                   8406: not change anything else on the stack. The overall stack effect of the
                   8407: assertion is @code{( -- )}. E.g.
1.23      crook    8408: 
1.26      crook    8409: @example
                   8410: assert( 1 1 + 2 = ) \ what we learn in school
                   8411: assert( dup 0<> ) \ assert that the top of stack is not zero
                   8412: assert( false ) \ this code should not be reached
                   8413: @end example
1.23      crook    8414: 
1.26      crook    8415: The need for assertions is different at different times. During
                   8416: debugging, we want more checking, in production we sometimes care more
                   8417: for speed. Therefore, assertions can be turned off, i.e., the assertion
                   8418: becomes a comment. Depending on the importance of an assertion and the
                   8419: time it takes to check it, you may want to turn off some assertions and
                   8420: keep others turned on. Gforth provides several levels of assertions for
                   8421: this purpose:
1.23      crook    8422: 
1.44      crook    8423: 
1.26      crook    8424: doc-assert0(
                   8425: doc-assert1(
                   8426: doc-assert2(
                   8427: doc-assert3(
                   8428: doc-assert(
                   8429: doc-)
1.23      crook    8430: 
1.44      crook    8431: 
1.26      crook    8432: The variable @code{assert-level} specifies the highest assertions that
                   8433: are turned on. I.e., at the default @code{assert-level} of one,
                   8434: @code{assert0(} and @code{assert1(} assertions perform checking, while
                   8435: @code{assert2(} and @code{assert3(} assertions are treated as comments.
                   8436: 
                   8437: The value of @code{assert-level} is evaluated at compile-time, not at
                   8438: run-time. Therefore you cannot turn assertions on or off at run-time;
                   8439: you have to set the @code{assert-level} appropriately before compiling a
                   8440: piece of code. You can compile different pieces of code at different
                   8441: @code{assert-level}s (e.g., a trusted library at level 1 and
                   8442: newly-written code at level 3).
1.23      crook    8443: 
1.44      crook    8444: 
1.26      crook    8445: doc-assert-level
1.23      crook    8446: 
1.44      crook    8447: 
1.26      crook    8448: If an assertion fails, a message compatible with Emacs' compilation mode
                   8449: is produced and the execution is aborted (currently with @code{ABORT"}.
                   8450: If there is interest, we will introduce a special throw code. But if you
                   8451: intend to @code{catch} a specific condition, using @code{throw} is
                   8452: probably more appropriate than an assertion).
1.23      crook    8453: 
1.26      crook    8454: Definitions in ANS Forth for these assertion words are provided
                   8455: in @file{compat/assert.fs}.
1.23      crook    8456: 
                   8457: 
1.48    ! anton    8458: @node Singlestep Debugger,  , Assertions, Programming Tools
1.26      crook    8459: @subsection Singlestep Debugger
                   8460: @cindex singlestep Debugger
                   8461: @cindex debugging Singlestep
1.23      crook    8462: 
1.26      crook    8463: When you create a new word there's often the need to check whether it
                   8464: behaves correctly or not. You can do this by typing @code{dbg
                   8465: badword}. A debug session might look like this:
1.23      crook    8466: 
1.26      crook    8467: @example
                   8468: : badword 0 DO i . LOOP ;  ok
                   8469: 2 dbg badword 
                   8470: : badword  
                   8471: Scanning code...
1.23      crook    8472: 
1.26      crook    8473: Nesting debugger ready!
1.23      crook    8474: 
1.26      crook    8475: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
                   8476: 400D4740  8049F68 DO             -> [ 0 ] 
                   8477: 400D4744  804A0C8 i              -> [ 1 ] 00000 
                   8478: 400D4748 400C5E60 .              -> 0 [ 0 ] 
                   8479: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   8480: 400D4744  804A0C8 i              -> [ 1 ] 00001 
                   8481: 400D4748 400C5E60 .              -> 1 [ 0 ] 
                   8482: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   8483: 400D4758  804B384 ;              ->  ok
                   8484: @end example
1.23      crook    8485: 
1.26      crook    8486: Each line displayed is one step. You always have to hit return to
                   8487: execute the next word that is displayed. If you don't want to execute
                   8488: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
                   8489: an overview what keys are available:
1.23      crook    8490: 
1.26      crook    8491: @table @i
1.23      crook    8492: 
1.30      anton    8493: @item @key{RET}
1.26      crook    8494: Next; Execute the next word.
1.23      crook    8495: 
1.26      crook    8496: @item n
                   8497: Nest; Single step through next word.
1.5       anton    8498: 
1.26      crook    8499: @item u
                   8500: Unnest; Stop debugging and execute rest of word. If we got to this word
                   8501: with nest, continue debugging with the calling word.
1.5       anton    8502: 
1.26      crook    8503: @item d
                   8504: Done; Stop debugging and execute rest.
1.5       anton    8505: 
1.26      crook    8506: @item s
                   8507: Stop; Abort immediately.
1.5       anton    8508: 
1.26      crook    8509: @end table
1.5       anton    8510: 
1.26      crook    8511: Debugging large application with this mechanism is very difficult, because
                   8512: you have to nest very deeply into the program before the interesting part
                   8513: begins. This takes a lot of time. 
1.5       anton    8514: 
1.26      crook    8515: To do it more directly put a @code{BREAK:} command into your source code.
                   8516: When program execution reaches @code{BREAK:} the single step debugger is
                   8517: invoked and you have all the features described above.
1.23      crook    8518: 
1.26      crook    8519: If you have more than one part to debug it is useful to know where the
                   8520: program has stopped at the moment. You can do this by the 
                   8521: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
                   8522: string is typed out when the ``breakpoint'' is reached.
                   8523: 
1.44      crook    8524: 
1.26      crook    8525: doc-dbg
1.45      crook    8526: doc-break:
                   8527: doc-break"
1.26      crook    8528: 
                   8529: 
1.44      crook    8530: 
1.26      crook    8531: @c -------------------------------------------------------------
                   8532: @node Assembler and Code Words, Threading Words, Programming Tools, Words
                   8533: @section Assembler and Code Words
                   8534: @cindex assembler
                   8535: @cindex code words
1.5       anton    8536: 
1.26      crook    8537: Gforth provides some words for defining primitives (words written in
1.29      crook    8538: machine code), and for defining the machine-code equivalent of
1.26      crook    8539: @code{DOES>}-based defining words. However, the machine-independent
                   8540: nature of Gforth poses a few problems: First of all, Gforth runs on
                   8541: several architectures, so it can provide no standard assembler. What's
                   8542: worse is that the register allocation not only depends on the processor,
                   8543: but also on the @code{gcc} version and options used.
1.5       anton    8544: 
1.29      crook    8545: The words that Gforth offers encapsulate some system dependences (e.g.,
                   8546: the header structure), so a system-independent assembler may be used in
1.26      crook    8547: Gforth. If you do not have an assembler, you can compile machine code
1.29      crook    8548: directly with @code{,} and @code{c,}@footnote{This isn't portable,
                   8549: because these words emit stuff in @i{data} space; it works because
                   8550: Gforth has unified code/data spaces. Assembler isn't likely to be
                   8551: portable anyway.}.
1.5       anton    8552: 
1.44      crook    8553: 
1.26      crook    8554: doc-assembler
1.45      crook    8555: doc-init-asm
1.26      crook    8556: doc-code
                   8557: doc-end-code
                   8558: doc-;code
                   8559: doc-flush-icache
1.5       anton    8560: 
1.44      crook    8561: 
1.26      crook    8562: If @code{flush-icache} does not work correctly, @code{code} words
                   8563: etc. will not work (reliably), either.
1.5       anton    8564: 
1.29      crook    8565: The typical usage of these @code{code} words can be shown most easily by
                   8566: analogy to the equivalent high-level defining words:
                   8567: 
                   8568: @example
                   8569: : foo                                        code foo
                   8570:    <high-level Forth words>                        <assembler>
                   8571: ;                                            end-code
                   8572: 
                   8573: : bar                                        : bar
                   8574:    <high-level Forth words>                     <high-level Forth words>
                   8575:    CREATE                                       CREATE
                   8576:       <high-level Forth words>                     <high-level Forth words>
                   8577:    DOES>                                        ;code
                   8578:       <high-level Forth words>                     <assembler>
                   8579: ;                                            end-code
                   8580: @end example
                   8581: 
1.26      crook    8582: @code{flush-icache} is always present. The other words are rarely used
                   8583: and reside in @code{code.fs}, which is usually not loaded. You can load
                   8584: it with @code{require code.fs}.
1.5       anton    8585: 
1.26      crook    8586: @cindex registers of the inner interpreter
                   8587: In the assembly code you will want to refer to the inner interpreter's
                   8588: registers (e.g., the data stack pointer) and you may want to use other
                   8589: registers for temporary storage. Unfortunately, the register allocation
                   8590: is installation-dependent.
1.5       anton    8591: 
1.26      crook    8592: The easiest solution is to use explicit register declarations
                   8593: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
                   8594: GNU C Manual}) for all of the inner interpreter's registers: You have to
                   8595: compile Gforth with @code{-DFORCE_REG} (configure option
                   8596: @code{--enable-force-reg}) and the appropriate declarations must be
                   8597: present in the @code{machine.h} file (see @code{mips.h} for an example;
                   8598: you can find a full list of all declarable register symbols with
                   8599: @code{grep register engine.c}). If you give explicit registers to all
                   8600: variables that are declared at the beginning of @code{engine()}, you
                   8601: should be able to use the other caller-saved registers for temporary
                   8602: storage. Alternatively, you can use the @code{gcc} option
                   8603: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
                   8604: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
                   8605: (however, this restriction on register allocation may slow Gforth
                   8606: significantly).
1.5       anton    8607: 
1.26      crook    8608: If this solution is not viable (e.g., because @code{gcc} does not allow
                   8609: you to explicitly declare all the registers you need), you have to find
                   8610: out by looking at the code where the inner interpreter's registers
                   8611: reside and which registers can be used for temporary storage. You can
                   8612: get an assembly listing of the engine's code with @code{make engine.s}.
1.5       anton    8613: 
1.26      crook    8614: In any case, it is good practice to abstract your assembly code from the
                   8615: actual register allocation. E.g., if the data stack pointer resides in
                   8616: register @code{$17}, create an alias for this register called @code{sp},
                   8617: and use that in your assembly code.
1.5       anton    8618: 
1.26      crook    8619: @cindex code words, portable
                   8620: Another option for implementing normal and defining words efficiently
                   8621: is to add the desired functionality to the source of Gforth. For normal
                   8622: words you just have to edit @file{primitives} (@pxref{Automatic
                   8623: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
                   8624: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
                   8625: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.5       anton    8626: 
                   8627: 
1.26      crook    8628: @c -------------------------------------------------------------
                   8629: @node Threading Words, Locals, Assembler and Code Words, Words
                   8630: @section Threading Words
                   8631: @cindex threading words
1.5       anton    8632: 
1.26      crook    8633: @cindex code address
                   8634: These words provide access to code addresses and other threading stuff
                   8635: in Gforth (and, possibly, other interpretive Forths). It more or less
                   8636: abstracts away the differences between direct and indirect threading
                   8637: (and, for direct threading, the machine dependences). However, at
                   8638: present this wordset is still incomplete. It is also pretty low-level;
                   8639: some day it will hopefully be made unnecessary by an internals wordset
                   8640: that abstracts implementation details away completely.
1.5       anton    8641: 
1.44      crook    8642: 
1.26      crook    8643: doc-threading-method
                   8644: doc->code-address
                   8645: doc->does-code
                   8646: doc-code-address!
                   8647: doc-does-code!
                   8648: doc-does-handler!
                   8649: doc-/does-handler
1.5       anton    8650: 
1.44      crook    8651: 
1.26      crook    8652: The code addresses produced by various defining words are produced by
                   8653: the following words:
1.5       anton    8654: 
1.44      crook    8655: 
1.26      crook    8656: doc-docol:
                   8657: doc-docon:
                   8658: doc-dovar:
                   8659: doc-douser:
                   8660: doc-dodefer:
                   8661: doc-dofield:
1.5       anton    8662: 
1.44      crook    8663: 
1.26      crook    8664: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
                   8665: with @code{>does-code}. If the word was defined in that way, the value
                   8666: returned is non-zero and identifies the @code{DOES>} used by the
                   8667: defining word.
                   8668: @comment TODO should that be ``identifies the xt of the DOES> ??''
1.5       anton    8669: 
1.26      crook    8670: @c -------------------------------------------------------------
                   8671: @node Locals, Structures, Threading Words, Words
                   8672: @section Locals
                   8673: @cindex locals
1.5       anton    8674: 
1.26      crook    8675: Local variables can make Forth programming more enjoyable and Forth
                   8676: programs easier to read. Unfortunately, the locals of ANS Forth are
                   8677: laden with restrictions. Therefore, we provide not only the ANS Forth
                   8678: locals wordset, but also our own, more powerful locals wordset (we
                   8679: implemented the ANS Forth locals wordset through our locals wordset).
1.5       anton    8680: 
1.26      crook    8681: The ideas in this section have also been published in the paper
                   8682: @cite{Automatic Scoping of Local Variables} by M. Anton Ertl, presented
                   8683: at EuroForth '94; it is available at
1.47      crook    8684: @*@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz}.
1.5       anton    8685: 
1.26      crook    8686: @menu
                   8687: * Gforth locals::               
                   8688: * ANS Forth locals::            
                   8689: @end menu
1.5       anton    8690: 
1.26      crook    8691: @node Gforth locals, ANS Forth locals, Locals, Locals
                   8692: @subsection Gforth locals
                   8693: @cindex Gforth locals
                   8694: @cindex locals, Gforth style
1.5       anton    8695: 
1.26      crook    8696: Locals can be defined with
1.5       anton    8697: 
                   8698: @example
1.26      crook    8699: @{ local1 local2 ... -- comment @}
                   8700: @end example
                   8701: or
                   8702: @example
                   8703: @{ local1 local2 ... @}
1.5       anton    8704: @end example
                   8705: 
1.26      crook    8706: E.g.,
1.5       anton    8707: @example
1.26      crook    8708: : max @{ n1 n2 -- n3 @}
                   8709:  n1 n2 > if
                   8710:    n1
                   8711:  else
                   8712:    n2
                   8713:  endif ;
1.5       anton    8714: @end example
                   8715: 
1.26      crook    8716: The similarity of locals definitions with stack comments is intended. A
                   8717: locals definition often replaces the stack comment of a word. The order
                   8718: of the locals corresponds to the order in a stack comment and everything
                   8719: after the @code{--} is really a comment.
1.5       anton    8720: 
1.26      crook    8721: This similarity has one disadvantage: It is too easy to confuse locals
                   8722: declarations with stack comments, causing bugs and making them hard to
                   8723: find. However, this problem can be avoided by appropriate coding
                   8724: conventions: Do not use both notations in the same program. If you do,
                   8725: they should be distinguished using additional means, e.g. by position.
                   8726: 
                   8727: @cindex types of locals
                   8728: @cindex locals types
                   8729: The name of the local may be preceded by a type specifier, e.g.,
                   8730: @code{F:} for a floating point value:
                   8731: 
                   8732: @example
                   8733: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
                   8734: \ complex multiplication
                   8735:  Ar Br f* Ai Bi f* f-
                   8736:  Ar Bi f* Ai Br f* f+ ;
                   8737: @end example
                   8738: 
                   8739: @cindex flavours of locals
                   8740: @cindex locals flavours
                   8741: @cindex value-flavoured locals
                   8742: @cindex variable-flavoured locals
                   8743: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
                   8744: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
                   8745: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
                   8746: with @code{W:}, @code{D:} etc.) produces its value and can be changed
                   8747: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
                   8748: produces its address (which becomes invalid when the variable's scope is
                   8749: left). E.g., the standard word @code{emit} can be defined in terms of
                   8750: @code{type} like this:
1.5       anton    8751: 
                   8752: @example
1.26      crook    8753: : emit @{ C^ char* -- @}
                   8754:     char* 1 type ;
1.5       anton    8755: @end example
                   8756: 
1.26      crook    8757: @cindex default type of locals
                   8758: @cindex locals, default type
                   8759: A local without type specifier is a @code{W:} local. Both flavours of
                   8760: locals are initialized with values from the data or FP stack.
1.5       anton    8761: 
1.26      crook    8762: Currently there is no way to define locals with user-defined data
                   8763: structures, but we are working on it.
1.5       anton    8764: 
1.26      crook    8765: Gforth allows defining locals everywhere in a colon definition. This
                   8766: poses the following questions:
1.5       anton    8767: 
1.26      crook    8768: @menu
                   8769: * Where are locals visible by name?::  
                   8770: * How long do locals live?::    
                   8771: * Programming Style::           
                   8772: * Implementation::              
                   8773: @end menu
1.5       anton    8774: 
1.26      crook    8775: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
                   8776: @subsubsection Where are locals visible by name?
                   8777: @cindex locals visibility
                   8778: @cindex visibility of locals
                   8779: @cindex scope of locals
1.5       anton    8780: 
1.26      crook    8781: Basically, the answer is that locals are visible where you would expect
                   8782: it in block-structured languages, and sometimes a little longer. If you
                   8783: want to restrict the scope of a local, enclose its definition in
                   8784: @code{SCOPE}...@code{ENDSCOPE}.
1.5       anton    8785: 
1.44      crook    8786: 
1.26      crook    8787: doc-scope
                   8788: doc-endscope
1.5       anton    8789: 
1.44      crook    8790: 
1.26      crook    8791: These words behave like control structure words, so you can use them
                   8792: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
                   8793: arbitrary ways.
1.5       anton    8794: 
1.26      crook    8795: If you want a more exact answer to the visibility question, here's the
                   8796: basic principle: A local is visible in all places that can only be
                   8797: reached through the definition of the local@footnote{In compiler
                   8798: construction terminology, all places dominated by the definition of the
                   8799: local.}. In other words, it is not visible in places that can be reached
                   8800: without going through the definition of the local. E.g., locals defined
                   8801: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
                   8802: defined in @code{BEGIN}...@code{UNTIL} are visible after the
                   8803: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.5       anton    8804: 
1.26      crook    8805: The reasoning behind this solution is: We want to have the locals
                   8806: visible as long as it is meaningful. The user can always make the
                   8807: visibility shorter by using explicit scoping. In a place that can
                   8808: only be reached through the definition of a local, the meaning of a
                   8809: local name is clear. In other places it is not: How is the local
                   8810: initialized at the control flow path that does not contain the
                   8811: definition? Which local is meant, if the same name is defined twice in
                   8812: two independent control flow paths?
1.5       anton    8813: 
1.26      crook    8814: This should be enough detail for nearly all users, so you can skip the
                   8815: rest of this section. If you really must know all the gory details and
                   8816: options, read on.
1.5       anton    8817: 
1.26      crook    8818: In order to implement this rule, the compiler has to know which places
                   8819: are unreachable. It knows this automatically after @code{AHEAD},
                   8820: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
                   8821: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
                   8822: compiler that the control flow never reaches that place. If
                   8823: @code{UNREACHABLE} is not used where it could, the only consequence is
                   8824: that the visibility of some locals is more limited than the rule above
                   8825: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
                   8826: lie to the compiler), buggy code will be produced.
1.5       anton    8827: 
1.44      crook    8828: 
1.26      crook    8829: doc-unreachable
1.5       anton    8830: 
1.44      crook    8831: 
1.26      crook    8832: Another problem with this rule is that at @code{BEGIN}, the compiler
                   8833: does not know which locals will be visible on the incoming
                   8834: back-edge. All problems discussed in the following are due to this
                   8835: ignorance of the compiler (we discuss the problems using @code{BEGIN}
                   8836: loops as examples; the discussion also applies to @code{?DO} and other
                   8837: loops). Perhaps the most insidious example is:
1.5       anton    8838: @example
1.26      crook    8839: AHEAD
                   8840: BEGIN
                   8841:   x
                   8842: [ 1 CS-ROLL ] THEN
                   8843:   @{ x @}
                   8844:   ...
                   8845: UNTIL
                   8846: @end example
1.5       anton    8847: 
1.26      crook    8848: This should be legal according to the visibility rule. The use of
                   8849: @code{x} can only be reached through the definition; but that appears
                   8850: textually below the use.
1.5       anton    8851: 
1.26      crook    8852: From this example it is clear that the visibility rules cannot be fully
                   8853: implemented without major headaches. Our implementation treats common
                   8854: cases as advertised and the exceptions are treated in a safe way: The
                   8855: compiler makes a reasonable guess about the locals visible after a
                   8856: @code{BEGIN}; if it is too pessimistic, the
                   8857: user will get a spurious error about the local not being defined; if the
                   8858: compiler is too optimistic, it will notice this later and issue a
                   8859: warning. In the case above the compiler would complain about @code{x}
                   8860: being undefined at its use. You can see from the obscure examples in
                   8861: this section that it takes quite unusual control structures to get the
                   8862: compiler into trouble, and even then it will often do fine.
1.5       anton    8863: 
1.26      crook    8864: If the @code{BEGIN} is reachable from above, the most optimistic guess
                   8865: is that all locals visible before the @code{BEGIN} will also be
                   8866: visible after the @code{BEGIN}. This guess is valid for all loops that
                   8867: are entered only through the @code{BEGIN}, in particular, for normal
                   8868: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
                   8869: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
                   8870: compiler. When the branch to the @code{BEGIN} is finally generated by
                   8871: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
                   8872: warns the user if it was too optimistic:
                   8873: @example
                   8874: IF
                   8875:   @{ x @}
                   8876: BEGIN
                   8877:   \ x ? 
                   8878: [ 1 cs-roll ] THEN
                   8879:   ...
                   8880: UNTIL
1.5       anton    8881: @end example
                   8882: 
1.26      crook    8883: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
                   8884: optimistically assumes that it lives until the @code{THEN}. It notices
                   8885: this difference when it compiles the @code{UNTIL} and issues a
                   8886: warning. The user can avoid the warning, and make sure that @code{x}
                   8887: is not used in the wrong area by using explicit scoping:
                   8888: @example
                   8889: IF
                   8890:   SCOPE
                   8891:   @{ x @}
                   8892:   ENDSCOPE
                   8893: BEGIN
                   8894: [ 1 cs-roll ] THEN
                   8895:   ...
                   8896: UNTIL
                   8897: @end example
1.5       anton    8898: 
1.26      crook    8899: Since the guess is optimistic, there will be no spurious error messages
                   8900: about undefined locals.
1.5       anton    8901: 
1.26      crook    8902: If the @code{BEGIN} is not reachable from above (e.g., after
                   8903: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
                   8904: optimistic guess, as the locals visible after the @code{BEGIN} may be
                   8905: defined later. Therefore, the compiler assumes that no locals are
                   8906: visible after the @code{BEGIN}. However, the user can use
                   8907: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
                   8908: visible at the BEGIN as at the point where the top control-flow stack
                   8909: item was created.
1.5       anton    8910: 
1.44      crook    8911: 
1.26      crook    8912: doc-assume-live
1.5       anton    8913: 
1.44      crook    8914: 
                   8915: @noindent
1.26      crook    8916: E.g.,
1.5       anton    8917: @example
1.26      crook    8918: @{ x @}
                   8919: AHEAD
                   8920: ASSUME-LIVE
                   8921: BEGIN
                   8922:   x
                   8923: [ 1 CS-ROLL ] THEN
                   8924:   ...
                   8925: UNTIL
1.5       anton    8926: @end example
                   8927: 
1.26      crook    8928: Other cases where the locals are defined before the @code{BEGIN} can be
                   8929: handled by inserting an appropriate @code{CS-ROLL} before the
                   8930: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
                   8931: behind the @code{ASSUME-LIVE}).
1.5       anton    8932: 
1.26      crook    8933: Cases where locals are defined after the @code{BEGIN} (but should be
                   8934: visible immediately after the @code{BEGIN}) can only be handled by
                   8935: rearranging the loop. E.g., the ``most insidious'' example above can be
                   8936: arranged into:
1.5       anton    8937: @example
1.26      crook    8938: BEGIN
                   8939:   @{ x @}
                   8940:   ... 0=
                   8941: WHILE
                   8942:   x
                   8943: REPEAT
1.5       anton    8944: @end example
                   8945: 
1.26      crook    8946: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
                   8947: @subsubsection How long do locals live?
                   8948: @cindex locals lifetime
                   8949: @cindex lifetime of locals
1.5       anton    8950: 
1.26      crook    8951: The right answer for the lifetime question would be: A local lives at
                   8952: least as long as it can be accessed. For a value-flavoured local this
                   8953: means: until the end of its visibility. However, a variable-flavoured
                   8954: local could be accessed through its address far beyond its visibility
                   8955: scope. Ultimately, this would mean that such locals would have to be
                   8956: garbage collected. Since this entails un-Forth-like implementation
                   8957: complexities, I adopted the same cowardly solution as some other
                   8958: languages (e.g., C): The local lives only as long as it is visible;
                   8959: afterwards its address is invalid (and programs that access it
                   8960: afterwards are erroneous).
1.5       anton    8961: 
1.26      crook    8962: @node Programming Style, Implementation, How long do locals live?, Gforth locals
                   8963: @subsubsection Programming Style
                   8964: @cindex locals programming style
                   8965: @cindex programming style, locals
1.5       anton    8966: 
1.26      crook    8967: The freedom to define locals anywhere has the potential to change
                   8968: programming styles dramatically. In particular, the need to use the
                   8969: return stack for intermediate storage vanishes. Moreover, all stack
                   8970: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
                   8971: determined arguments) can be eliminated: If the stack items are in the
                   8972: wrong order, just write a locals definition for all of them; then
                   8973: write the items in the order you want.
1.5       anton    8974: 
1.26      crook    8975: This seems a little far-fetched and eliminating stack manipulations is
                   8976: unlikely to become a conscious programming objective. Still, the number
                   8977: of stack manipulations will be reduced dramatically if local variables
                   8978: are used liberally (e.g., compare @code{max} in @ref{Gforth locals} with
                   8979: a traditional implementation of @code{max}).
1.5       anton    8980: 
1.26      crook    8981: This shows one potential benefit of locals: making Forth programs more
                   8982: readable. Of course, this benefit will only be realized if the
                   8983: programmers continue to honour the principle of factoring instead of
                   8984: using the added latitude to make the words longer.
1.5       anton    8985: 
1.26      crook    8986: @cindex single-assignment style for locals
                   8987: Using @code{TO} can and should be avoided.  Without @code{TO},
                   8988: every value-flavoured local has only a single assignment and many
                   8989: advantages of functional languages apply to Forth. I.e., programs are
                   8990: easier to analyse, to optimize and to read: It is clear from the
                   8991: definition what the local stands for, it does not turn into something
                   8992: different later.
1.5       anton    8993: 
1.26      crook    8994: E.g., a definition using @code{TO} might look like this:
1.5       anton    8995: @example
1.26      crook    8996: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   8997:  u1 u2 min 0
                   8998:  ?do
                   8999:    addr1 c@@ addr2 c@@ -
                   9000:    ?dup-if
                   9001:      unloop exit
                   9002:    then
                   9003:    addr1 char+ TO addr1
                   9004:    addr2 char+ TO addr2
                   9005:  loop
                   9006:  u1 u2 - ;
1.5       anton    9007: @end example
1.26      crook    9008: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
                   9009: every loop iteration. @code{strcmp} is a typical example of the
                   9010: readability problems of using @code{TO}. When you start reading
                   9011: @code{strcmp}, you think that @code{addr1} refers to the start of the
                   9012: string. Only near the end of the loop you realize that it is something
                   9013: else.
1.5       anton    9014: 
1.26      crook    9015: This can be avoided by defining two locals at the start of the loop that
                   9016: are initialized with the right value for the current iteration.
1.5       anton    9017: @example
1.26      crook    9018: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9019:  addr1 addr2
                   9020:  u1 u2 min 0 
                   9021:  ?do @{ s1 s2 @}
                   9022:    s1 c@@ s2 c@@ -
                   9023:    ?dup-if
                   9024:      unloop exit
                   9025:    then
                   9026:    s1 char+ s2 char+
                   9027:  loop
                   9028:  2drop
                   9029:  u1 u2 - ;
1.5       anton    9030: @end example
1.26      crook    9031: Here it is clear from the start that @code{s1} has a different value
                   9032: in every loop iteration.
1.5       anton    9033: 
1.26      crook    9034: @node Implementation,  , Programming Style, Gforth locals
                   9035: @subsubsection Implementation
                   9036: @cindex locals implementation
                   9037: @cindex implementation of locals
1.5       anton    9038: 
1.26      crook    9039: @cindex locals stack
                   9040: Gforth uses an extra locals stack. The most compelling reason for
                   9041: this is that the return stack is not float-aligned; using an extra stack
                   9042: also eliminates the problems and restrictions of using the return stack
                   9043: as locals stack. Like the other stacks, the locals stack grows toward
                   9044: lower addresses. A few primitives allow an efficient implementation:
1.5       anton    9045: 
1.44      crook    9046: 
1.26      crook    9047: doc-@local#
                   9048: doc-f@local#
                   9049: doc-laddr#
                   9050: doc-lp+!#
                   9051: doc-lp!
                   9052: doc->l
                   9053: doc-f>l
1.5       anton    9054: 
1.44      crook    9055: 
1.26      crook    9056: In addition to these primitives, some specializations of these
                   9057: primitives for commonly occurring inline arguments are provided for
                   9058: efficiency reasons, e.g., @code{@@local0} as specialization of
                   9059: @code{@@local#} for the inline argument 0. The following compiling words
                   9060: compile the right specialized version, or the general version, as
                   9061: appropriate:
1.6       pazsan   9062: 
1.44      crook    9063: 
1.26      crook    9064: doc-compile-@local
                   9065: doc-compile-f@local
                   9066: doc-compile-lp+!
1.12      anton    9067: 
1.44      crook    9068: 
1.26      crook    9069: Combinations of conditional branches and @code{lp+!#} like
                   9070: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
                   9071: is taken) are provided for efficiency and correctness in loops.
1.6       pazsan   9072: 
1.26      crook    9073: A special area in the dictionary space is reserved for keeping the
                   9074: local variable names. @code{@{} switches the dictionary pointer to this
                   9075: area and @code{@}} switches it back and generates the locals
                   9076: initializing code. @code{W:} etc.@ are normal defining words. This
                   9077: special area is cleared at the start of every colon definition.
1.6       pazsan   9078: 
1.26      crook    9079: @cindex word list for defining locals
                   9080: A special feature of Gforth's dictionary is used to implement the
                   9081: definition of locals without type specifiers: every word list (aka
                   9082: vocabulary) has its own methods for searching
                   9083: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
                   9084: with a special search method: When it is searched for a word, it
                   9085: actually creates that word using @code{W:}. @code{@{} changes the search
                   9086: order to first search the word list containing @code{@}}, @code{W:} etc.,
                   9087: and then the word list for defining locals without type specifiers.
1.12      anton    9088: 
1.26      crook    9089: The lifetime rules support a stack discipline within a colon
                   9090: definition: The lifetime of a local is either nested with other locals
                   9091: lifetimes or it does not overlap them.
1.6       pazsan   9092: 
1.26      crook    9093: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
                   9094: pointer manipulation is generated. Between control structure words
                   9095: locals definitions can push locals onto the locals stack. @code{AGAIN}
                   9096: is the simplest of the other three control flow words. It has to
                   9097: restore the locals stack depth of the corresponding @code{BEGIN}
                   9098: before branching. The code looks like this:
                   9099: @format
                   9100: @code{lp+!#} current-locals-size @minus{} dest-locals-size
                   9101: @code{branch} <begin>
                   9102: @end format
1.6       pazsan   9103: 
1.26      crook    9104: @code{UNTIL} is a little more complicated: If it branches back, it
                   9105: must adjust the stack just like @code{AGAIN}. But if it falls through,
                   9106: the locals stack must not be changed. The compiler generates the
                   9107: following code:
                   9108: @format
                   9109: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
                   9110: @end format
                   9111: The locals stack pointer is only adjusted if the branch is taken.
1.6       pazsan   9112: 
1.26      crook    9113: @code{THEN} can produce somewhat inefficient code:
                   9114: @format
                   9115: @code{lp+!#} current-locals-size @minus{} orig-locals-size
                   9116: <orig target>:
                   9117: @code{lp+!#} orig-locals-size @minus{} new-locals-size
                   9118: @end format
                   9119: The second @code{lp+!#} adjusts the locals stack pointer from the
1.29      crook    9120: level at the @i{orig} point to the level after the @code{THEN}. The
1.26      crook    9121: first @code{lp+!#} adjusts the locals stack pointer from the current
                   9122: level to the level at the orig point, so the complete effect is an
                   9123: adjustment from the current level to the right level after the
                   9124: @code{THEN}.
1.6       pazsan   9125: 
1.26      crook    9126: @cindex locals information on the control-flow stack
                   9127: @cindex control-flow stack items, locals information
                   9128: In a conventional Forth implementation a dest control-flow stack entry
                   9129: is just the target address and an orig entry is just the address to be
                   9130: patched. Our locals implementation adds a word list to every orig or dest
                   9131: item. It is the list of locals visible (or assumed visible) at the point
                   9132: described by the entry. Our implementation also adds a tag to identify
                   9133: the kind of entry, in particular to differentiate between live and dead
                   9134: (reachable and unreachable) orig entries.
1.6       pazsan   9135: 
1.26      crook    9136: A few unusual operations have to be performed on locals word lists:
1.6       pazsan   9137: 
1.44      crook    9138: 
1.26      crook    9139: doc-common-list
                   9140: doc-sub-list?
                   9141: doc-list-size
1.6       pazsan   9142: 
1.44      crook    9143: 
1.26      crook    9144: Several features of our locals word list implementation make these
                   9145: operations easy to implement: The locals word lists are organised as
                   9146: linked lists; the tails of these lists are shared, if the lists
                   9147: contain some of the same locals; and the address of a name is greater
                   9148: than the address of the names behind it in the list.
1.6       pazsan   9149: 
1.26      crook    9150: Another important implementation detail is the variable
                   9151: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
                   9152: determine if they can be reached directly or only through the branch
                   9153: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
                   9154: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
                   9155: definition, by @code{BEGIN} and usually by @code{THEN}.
1.6       pazsan   9156: 
1.26      crook    9157: Counted loops are similar to other loops in most respects, but
                   9158: @code{LEAVE} requires special attention: It performs basically the same
                   9159: service as @code{AHEAD}, but it does not create a control-flow stack
                   9160: entry. Therefore the information has to be stored elsewhere;
                   9161: traditionally, the information was stored in the target fields of the
                   9162: branches created by the @code{LEAVE}s, by organizing these fields into a
                   9163: linked list. Unfortunately, this clever trick does not provide enough
                   9164: space for storing our extended control flow information. Therefore, we
                   9165: introduce another stack, the leave stack. It contains the control-flow
                   9166: stack entries for all unresolved @code{LEAVE}s.
1.6       pazsan   9167: 
1.26      crook    9168: Local names are kept until the end of the colon definition, even if
                   9169: they are no longer visible in any control-flow path. In a few cases
                   9170: this may lead to increased space needs for the locals name area, but
                   9171: usually less than reclaiming this space would cost in code size.
1.6       pazsan   9172: 
                   9173: 
1.26      crook    9174: @node ANS Forth locals,  , Gforth locals, Locals
                   9175: @subsection ANS Forth locals
                   9176: @cindex locals, ANS Forth style
1.6       pazsan   9177: 
1.26      crook    9178: The ANS Forth locals wordset does not define a syntax for locals, but
                   9179: words that make it possible to define various syntaxes. One of the
                   9180: possible syntaxes is a subset of the syntax we used in the Gforth locals
                   9181: wordset, i.e.:
1.6       pazsan   9182: 
                   9183: @example
1.26      crook    9184: @{ local1 local2 ... -- comment @}
1.6       pazsan   9185: @end example
1.23      crook    9186: @noindent
1.26      crook    9187: or
1.6       pazsan   9188: @example
1.26      crook    9189: @{ local1 local2 ... @}
1.6       pazsan   9190: @end example
                   9191: 
1.26      crook    9192: The order of the locals corresponds to the order in a stack comment. The
                   9193: restrictions are:
1.6       pazsan   9194: 
                   9195: @itemize @bullet
                   9196: @item
1.26      crook    9197: Locals can only be cell-sized values (no type specifiers are allowed).
1.6       pazsan   9198: @item
1.26      crook    9199: Locals can be defined only outside control structures.
1.6       pazsan   9200: @item
1.26      crook    9201: Locals can interfere with explicit usage of the return stack. For the
                   9202: exact (and long) rules, see the standard. If you don't use return stack
                   9203: accessing words in a definition using locals, you will be all right. The
                   9204: purpose of this rule is to make locals implementation on the return
                   9205: stack easier.
1.6       pazsan   9206: @item
1.26      crook    9207: The whole definition must be in one line.
                   9208: @end itemize
1.6       pazsan   9209: 
1.44      crook    9210: Locals defined in this way behave like @code{VALUE}s
                   9211: (@xref{Values}). I.e., they are initialized from the stack. Using their
1.26      crook    9212: name produces their value. Their value can be changed using @code{TO}.
1.6       pazsan   9213: 
1.26      crook    9214: Since this syntax is supported by Gforth directly, you need not do
                   9215: anything to use it. If you want to port a program using this syntax to
                   9216: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
                   9217: syntax on the other system.
1.6       pazsan   9218: 
1.26      crook    9219: Note that a syntax shown in the standard, section A.13 looks
                   9220: similar, but is quite different in having the order of locals
                   9221: reversed. Beware!
1.6       pazsan   9222: 
1.26      crook    9223: The ANS Forth locals wordset itself consists of a word:
1.6       pazsan   9224: 
1.44      crook    9225: 
1.26      crook    9226: doc-(local)
1.6       pazsan   9227: 
1.44      crook    9228: 
1.26      crook    9229: The ANS Forth locals extension wordset defines a syntax using @code{locals|}, but it is so
                   9230: awful that we strongly recommend not to use it. We have implemented this
                   9231: syntax to make porting to Gforth easy, but do not document it here. The
                   9232: problem with this syntax is that the locals are defined in an order
                   9233: reversed with respect to the standard stack comment notation, making
                   9234: programs harder to read, and easier to misread and miswrite. The only
                   9235: merit of this syntax is that it is easy to implement using the ANS Forth
                   9236: locals wordset.
1.7       pazsan   9237: 
                   9238: 
1.26      crook    9239: @c ----------------------------------------------------------
                   9240: @node Structures, Object-oriented Forth, Locals, Words
                   9241: @section  Structures
                   9242: @cindex structures
                   9243: @cindex records
1.7       pazsan   9244: 
1.26      crook    9245: This section presents the structure package that comes with Gforth. A
                   9246: version of the package implemented in ANS Forth is available in
                   9247: @file{compat/struct.fs}. This package was inspired by a posting on
                   9248: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
                   9249: possibly John Hayes). A version of this section has been published in
                   9250: ???. Marcel Hendrix provided helpful comments.
1.7       pazsan   9251: 
1.26      crook    9252: @menu
                   9253: * Why explicit structure support?::  
                   9254: * Structure Usage::             
                   9255: * Structure Naming Convention::  
                   9256: * Structure Implementation::    
                   9257: * Structure Glossary::          
                   9258: @end menu
1.7       pazsan   9259: 
1.26      crook    9260: @node Why explicit structure support?, Structure Usage, Structures, Structures
                   9261: @subsection Why explicit structure support?
1.7       pazsan   9262: 
1.26      crook    9263: @cindex address arithmetic for structures
                   9264: @cindex structures using address arithmetic
                   9265: If we want to use a structure containing several fields, we could simply
                   9266: reserve memory for it, and access the fields using address arithmetic
1.32      anton    9267: (@pxref{Address arithmetic}). As an example, consider a structure with
1.26      crook    9268: the following fields
1.7       pazsan   9269: 
1.26      crook    9270: @table @code
                   9271: @item a
                   9272: is a float
                   9273: @item b
                   9274: is a cell
                   9275: @item c
                   9276: is a float
                   9277: @end table
1.7       pazsan   9278: 
1.26      crook    9279: Given the (float-aligned) base address of the structure we get the
                   9280: address of the field
1.13      pazsan   9281: 
1.26      crook    9282: @table @code
                   9283: @item a
                   9284: without doing anything further.
                   9285: @item b
                   9286: with @code{float+}
                   9287: @item c
                   9288: with @code{float+ cell+ faligned}
                   9289: @end table
1.13      pazsan   9290: 
1.26      crook    9291: It is easy to see that this can become quite tiring. 
1.13      pazsan   9292: 
1.26      crook    9293: Moreover, it is not very readable, because seeing a
                   9294: @code{cell+} tells us neither which kind of structure is
                   9295: accessed nor what field is accessed; we have to somehow infer the kind
                   9296: of structure, and then look up in the documentation, which field of
                   9297: that structure corresponds to that offset.
1.13      pazsan   9298: 
1.26      crook    9299: Finally, this kind of address arithmetic also causes maintenance
                   9300: troubles: If you add or delete a field somewhere in the middle of the
                   9301: structure, you have to find and change all computations for the fields
                   9302: afterwards.
1.13      pazsan   9303: 
1.26      crook    9304: So, instead of using @code{cell+} and friends directly, how
                   9305: about storing the offsets in constants:
1.13      pazsan   9306: 
                   9307: @example
1.26      crook    9308: 0 constant a-offset
                   9309: 0 float+ constant b-offset
                   9310: 0 float+ cell+ faligned c-offset
1.13      pazsan   9311: @end example
                   9312: 
1.26      crook    9313: Now we can get the address of field @code{x} with @code{x-offset
                   9314: +}. This is much better in all respects. Of course, you still
                   9315: have to change all later offset definitions if you add a field. You can
                   9316: fix this by declaring the offsets in the following way:
1.13      pazsan   9317: 
                   9318: @example
1.26      crook    9319: 0 constant a-offset
                   9320: a-offset float+ constant b-offset
                   9321: b-offset cell+ faligned constant c-offset
1.13      pazsan   9322: @end example
                   9323: 
1.26      crook    9324: Since we always use the offsets with @code{+}, we could use a defining
                   9325: word @code{cfield} that includes the @code{+} in the action of the
                   9326: defined word:
1.8       pazsan   9327: 
                   9328: @example
1.26      crook    9329: : cfield ( n "name" -- )
                   9330:     create ,
                   9331: does> ( name execution: addr1 -- addr2 )
                   9332:     @@ + ;
1.13      pazsan   9333: 
1.26      crook    9334: 0 cfield a
                   9335: 0 a float+ cfield b
                   9336: 0 b cell+ faligned cfield c
1.13      pazsan   9337: @end example
                   9338: 
1.26      crook    9339: Instead of @code{x-offset +}, we now simply write @code{x}.
                   9340: 
                   9341: The structure field words now can be used quite nicely. However,
                   9342: their definition is still a bit cumbersome: We have to repeat the
                   9343: name, the information about size and alignment is distributed before
                   9344: and after the field definitions etc.  The structure package presented
                   9345: here addresses these problems.
                   9346: 
                   9347: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
                   9348: @subsection Structure Usage
                   9349: @cindex structure usage
1.13      pazsan   9350: 
1.26      crook    9351: @cindex @code{field} usage
                   9352: @cindex @code{struct} usage
                   9353: @cindex @code{end-struct} usage
                   9354: You can define a structure for a (data-less) linked list with:
1.13      pazsan   9355: @example
1.26      crook    9356: struct
                   9357:     cell% field list-next
                   9358: end-struct list%
1.13      pazsan   9359: @end example
                   9360: 
1.26      crook    9361: With the address of the list node on the stack, you can compute the
                   9362: address of the field that contains the address of the next node with
                   9363: @code{list-next}. E.g., you can determine the length of a list
                   9364: with:
1.13      pazsan   9365: 
                   9366: @example
1.26      crook    9367: : list-length ( list -- n )
                   9368: \ "list" is a pointer to the first element of a linked list
                   9369: \ "n" is the length of the list
                   9370:     0 BEGIN ( list1 n1 )
                   9371:         over
                   9372:     WHILE ( list1 n1 )
                   9373:         1+ swap list-next @@ swap
                   9374:     REPEAT
                   9375:     nip ;
1.13      pazsan   9376: @end example
                   9377: 
1.26      crook    9378: You can reserve memory for a list node in the dictionary with
                   9379: @code{list% %allot}, which leaves the address of the list node on the
                   9380: stack. For the equivalent allocation on the heap you can use @code{list%
                   9381: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
                   9382: use @code{list% %allocate}). You can get the the size of a list
                   9383: node with @code{list% %size} and its alignment with @code{list%
                   9384: %alignment}.
1.13      pazsan   9385: 
1.26      crook    9386: Note that in ANS Forth the body of a @code{create}d word is
                   9387: @code{aligned} but not necessarily @code{faligned};
                   9388: therefore, if you do a:
1.13      pazsan   9389: @example
1.26      crook    9390: create @emph{name} foo% %allot
1.8       pazsan   9391: @end example
                   9392: 
1.26      crook    9393: @noindent
                   9394: then the memory alloted for @code{foo%} is
                   9395: guaranteed to start at the body of @code{@emph{name}} only if
                   9396: @code{foo%} contains only character, cell and double fields.
1.20      pazsan   9397: 
1.45      crook    9398: @cindex structures containing structures
1.26      crook    9399: You can include a structure @code{foo%} as a field of
                   9400: another structure, like this:
1.20      pazsan   9401: @example
1.26      crook    9402: struct
                   9403: ...
                   9404:     foo% field ...
                   9405: ...
                   9406: end-struct ...
1.20      pazsan   9407: @end example
                   9408: 
1.26      crook    9409: @cindex structure extension
                   9410: @cindex extended records
                   9411: Instead of starting with an empty structure, you can extend an
                   9412: existing structure. E.g., a plain linked list without data, as defined
                   9413: above, is hardly useful; You can extend it to a linked list of integers,
                   9414: like this:@footnote{This feature is also known as @emph{extended
                   9415: records}. It is the main innovation in the Oberon language; in other
                   9416: words, adding this feature to Modula-2 led Wirth to create a new
                   9417: language, write a new compiler etc.  Adding this feature to Forth just
                   9418: required a few lines of code.}
1.20      pazsan   9419: 
                   9420: @example
1.26      crook    9421: list%
                   9422:     cell% field intlist-int
                   9423: end-struct intlist%
1.20      pazsan   9424: @end example
                   9425: 
1.26      crook    9426: @code{intlist%} is a structure with two fields:
                   9427: @code{list-next} and @code{intlist-int}.
1.20      pazsan   9428: 
1.26      crook    9429: @cindex structures containing arrays
                   9430: You can specify an array type containing @emph{n} elements of
                   9431: type @code{foo%} like this:
1.20      pazsan   9432: 
                   9433: @example
1.26      crook    9434: foo% @emph{n} *
1.20      pazsan   9435: @end example
                   9436: 
1.26      crook    9437: You can use this array type in any place where you can use a normal
                   9438: type, e.g., when defining a @code{field}, or with
                   9439: @code{%allot}.
1.20      pazsan   9440: 
1.26      crook    9441: @cindex first field optimization
                   9442: The first field is at the base address of a structure and the word
                   9443: for this field (e.g., @code{list-next}) actually does not change
                   9444: the address on the stack. You may be tempted to leave it away in the
                   9445: interest of run-time and space efficiency. This is not necessary,
                   9446: because the structure package optimizes this case and compiling such
                   9447: words does not generate any code. So, in the interest of readability
                   9448: and maintainability you should include the word for the field when
                   9449: accessing the field.
1.20      pazsan   9450: 
1.26      crook    9451: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
                   9452: @subsection Structure Naming Convention
                   9453: @cindex structure naming convention
1.20      pazsan   9454: 
1.26      crook    9455: The field names that come to (my) mind are often quite generic, and,
                   9456: if used, would cause frequent name clashes. E.g., many structures
                   9457: probably contain a @code{counter} field. The structure names
                   9458: that come to (my) mind are often also the logical choice for the names
                   9459: of words that create such a structure.
1.20      pazsan   9460: 
1.26      crook    9461: Therefore, I have adopted the following naming conventions: 
1.20      pazsan   9462: 
1.26      crook    9463: @itemize @bullet
                   9464: @cindex field naming convention
                   9465: @item
                   9466: The names of fields are of the form
                   9467: @code{@emph{struct}-@emph{field}}, where
                   9468: @code{@emph{struct}} is the basic name of the structure, and
                   9469: @code{@emph{field}} is the basic name of the field. You can
                   9470: think of field words as converting the (address of the)
                   9471: structure into the (address of the) field.
1.20      pazsan   9472: 
1.26      crook    9473: @cindex structure naming convention
                   9474: @item
                   9475: The names of structures are of the form
                   9476: @code{@emph{struct}%}, where
                   9477: @code{@emph{struct}} is the basic name of the structure.
                   9478: @end itemize
1.20      pazsan   9479: 
1.26      crook    9480: This naming convention does not work that well for fields of extended
                   9481: structures; e.g., the integer list structure has a field
                   9482: @code{intlist-int}, but has @code{list-next}, not
                   9483: @code{intlist-next}.
1.20      pazsan   9484: 
1.26      crook    9485: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
                   9486: @subsection Structure Implementation
                   9487: @cindex structure implementation
                   9488: @cindex implementation of structures
1.20      pazsan   9489: 
1.26      crook    9490: The central idea in the implementation is to pass the data about the
                   9491: structure being built on the stack, not in some global
                   9492: variable. Everything else falls into place naturally once this design
                   9493: decision is made.
1.20      pazsan   9494: 
1.26      crook    9495: The type description on the stack is of the form @emph{align
                   9496: size}. Keeping the size on the top-of-stack makes dealing with arrays
                   9497: very simple.
1.20      pazsan   9498: 
1.26      crook    9499: @code{field} is a defining word that uses @code{Create}
                   9500: and @code{DOES>}. The body of the field contains the offset
                   9501: of the field, and the normal @code{DOES>} action is simply:
1.20      pazsan   9502: 
                   9503: @example
1.48    ! anton    9504: @@ +
1.20      pazsan   9505: @end example
                   9506: 
1.23      crook    9507: @noindent
1.26      crook    9508: i.e., add the offset to the address, giving the stack effect
1.29      crook    9509: @i{addr1 -- addr2} for a field.
1.20      pazsan   9510: 
1.26      crook    9511: @cindex first field optimization, implementation
                   9512: This simple structure is slightly complicated by the optimization
                   9513: for fields with offset 0, which requires a different
                   9514: @code{DOES>}-part (because we cannot rely on there being
                   9515: something on the stack if such a field is invoked during
                   9516: compilation). Therefore, we put the different @code{DOES>}-parts
                   9517: in separate words, and decide which one to invoke based on the
                   9518: offset. For a zero offset, the field is basically a noop; it is
                   9519: immediate, and therefore no code is generated when it is compiled.
1.20      pazsan   9520: 
1.26      crook    9521: @node Structure Glossary,  , Structure Implementation, Structures
                   9522: @subsection Structure Glossary
                   9523: @cindex structure glossary
1.20      pazsan   9524: 
1.44      crook    9525: 
1.26      crook    9526: doc-%align
                   9527: doc-%alignment
                   9528: doc-%alloc
                   9529: doc-%allocate
                   9530: doc-%allot
                   9531: doc-cell%
                   9532: doc-char%
                   9533: doc-dfloat%
                   9534: doc-double%
                   9535: doc-end-struct
                   9536: doc-field
                   9537: doc-float%
                   9538: doc-naligned
                   9539: doc-sfloat%
                   9540: doc-%size
                   9541: doc-struct
1.23      crook    9542: 
1.44      crook    9543: 
1.26      crook    9544: @c -------------------------------------------------------------
                   9545: @node Object-oriented Forth, Passing Commands to the OS, Structures, Words
                   9546: @section Object-oriented Forth
1.20      pazsan   9547: 
1.26      crook    9548: Gforth comes with three packages for object-oriented programming:
                   9549: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
                   9550: is preloaded, so you have to @code{include} them before use. The most
                   9551: important differences between these packages (and others) are discussed
                   9552: in @ref{Comparison with other object models}. All packages are written
                   9553: in ANS Forth and can be used with any other ANS Forth.
1.20      pazsan   9554: 
1.26      crook    9555: @menu
1.48    ! anton    9556: * Why object-oriented programming?::  
        !          9557: * Object-Oriented Terminology::  
        !          9558: * Objects::                     
        !          9559: * OOF::                         
        !          9560: * Mini-OOF::                    
1.26      crook    9561: * Comparison with other object models::  
                   9562: @end menu
1.20      pazsan   9563: 
1.48    ! anton    9564: @c ----------------------------------------------------------------
        !          9565: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
        !          9566: @subsection Why object-oriented programming?
1.26      crook    9567: @cindex object-oriented programming motivation
                   9568: @cindex motivation for object-oriented programming
1.23      crook    9569: 
1.26      crook    9570: Often we have to deal with several data structures (@emph{objects}),
                   9571: that have to be treated similarly in some respects, but differently in
                   9572: others. Graphical objects are the textbook example: circles, triangles,
                   9573: dinosaurs, icons, and others, and we may want to add more during program
                   9574: development. We want to apply some operations to any graphical object,
                   9575: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
                   9576: has to do something different for every kind of object.
                   9577: @comment TODO add some other operations eg perimeter, area
                   9578: @comment and tie in to concrete examples later..
1.23      crook    9579: 
1.26      crook    9580: We could implement @code{draw} as a big @code{CASE}
                   9581: control structure that executes the appropriate code depending on the
                   9582: kind of object to be drawn. This would be not be very elegant, and,
                   9583: moreover, we would have to change @code{draw} every time we add
                   9584: a new kind of graphical object (say, a spaceship).
1.23      crook    9585: 
1.26      crook    9586: What we would rather do is: When defining spaceships, we would tell
                   9587: the system: ``Here's how you @code{draw} a spaceship; you figure
                   9588: out the rest''.
1.23      crook    9589: 
1.26      crook    9590: This is the problem that all systems solve that (rightfully) call
                   9591: themselves object-oriented; the object-oriented packages presented here
                   9592: solve this problem (and not much else).
                   9593: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.23      crook    9594: 
1.48    ! anton    9595: @c ------------------------------------------------------------------------
1.26      crook    9596: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
1.48    ! anton    9597: @subsection Object-Oriented Terminology
1.26      crook    9598: @cindex object-oriented terminology
                   9599: @cindex terminology for object-oriented programming
1.23      crook    9600: 
1.26      crook    9601: This section is mainly for reference, so you don't have to understand
                   9602: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
                   9603: short:
1.23      crook    9604: 
1.26      crook    9605: @table @emph
                   9606: @cindex class
                   9607: @item class
                   9608: a data structure definition with some extras.
1.23      crook    9609: 
1.26      crook    9610: @cindex object
                   9611: @item object
                   9612: an instance of the data structure described by the class definition.
1.23      crook    9613: 
1.26      crook    9614: @cindex instance variables
                   9615: @item instance variables
                   9616: fields of the data structure.
1.23      crook    9617: 
1.26      crook    9618: @cindex selector
                   9619: @cindex method selector
                   9620: @cindex virtual function
                   9621: @item selector
                   9622: (or @emph{method selector}) a word (e.g.,
                   9623: @code{draw}) that performs an operation on a variety of data
                   9624: structures (classes). A selector describes @emph{what} operation to
                   9625: perform. In C++ terminology: a (pure) virtual function.
1.23      crook    9626: 
1.26      crook    9627: @cindex method
                   9628: @item method
                   9629: the concrete definition that performs the operation
                   9630: described by the selector for a specific class. A method specifies
                   9631: @emph{how} the operation is performed for a specific class.
1.23      crook    9632: 
1.26      crook    9633: @cindex selector invocation
                   9634: @cindex message send
                   9635: @cindex invoking a selector
                   9636: @item selector invocation
                   9637: a call of a selector. One argument of the call (the TOS (top-of-stack))
                   9638: is used for determining which method is used. In Smalltalk terminology:
                   9639: a message (consisting of the selector and the other arguments) is sent
                   9640: to the object.
1.1       anton    9641: 
1.26      crook    9642: @cindex receiving object
                   9643: @item receiving object
                   9644: the object used for determining the method executed by a selector
                   9645: invocation. In the @file{objects.fs} model, it is the object that is on
                   9646: the TOS when the selector is invoked. (@emph{Receiving} comes from
                   9647: the Smalltalk @emph{message} terminology.)
1.1       anton    9648: 
1.26      crook    9649: @cindex child class
                   9650: @cindex parent class
                   9651: @cindex inheritance
                   9652: @item child class
                   9653: a class that has (@emph{inherits}) all properties (instance variables,
                   9654: selectors, methods) from a @emph{parent class}. In Smalltalk
                   9655: terminology: The subclass inherits from the superclass. In C++
                   9656: terminology: The derived class inherits from the base class.
1.1       anton    9657: 
1.26      crook    9658: @end table
1.21      crook    9659: 
1.26      crook    9660: @c If you wonder about the message sending terminology, it comes from
                   9661: @c a time when each object had it's own task and objects communicated via
                   9662: @c message passing; eventually the Smalltalk developers realized that
                   9663: @c they can do most things through simple (indirect) calls. They kept the
                   9664: @c terminology.
1.1       anton    9665: 
1.48    ! anton    9666: @c --------------------------------------------------------------
1.26      crook    9667: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
                   9668: @subsection The @file{objects.fs} model
                   9669: @cindex objects
                   9670: @cindex object-oriented programming
1.1       anton    9671: 
1.26      crook    9672: @cindex @file{objects.fs}
                   9673: @cindex @file{oof.fs}
1.1       anton    9674: 
1.37      anton    9675: This section describes the @file{objects.fs} package. This material also
                   9676: has been published in @cite{Yet Another Forth Objects Package} by Anton
                   9677: Ertl and appeared in Forth Dimensions 19(2), pages 37--43
1.47      crook    9678: (@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html}).
1.26      crook    9679: @c McKewan's and Zsoter's packages
1.1       anton    9680: 
1.26      crook    9681: This section assumes that you have read @ref{Structures}.
1.1       anton    9682: 
1.26      crook    9683: The techniques on which this model is based have been used to implement
                   9684: the parser generator, Gray, and have also been used in Gforth for
                   9685: implementing the various flavours of word lists (hashed or not,
                   9686: case-sensitive or not, special-purpose word lists for locals etc.).
1.1       anton    9687: 
                   9688: 
1.26      crook    9689: @menu
                   9690: * Properties of the Objects model::  
                   9691: * Basic Objects Usage::         
1.37      anton    9692: * The Objects base class::      
1.26      crook    9693: * Creating objects::            
                   9694: * Object-Oriented Programming Style::  
                   9695: * Class Binding::               
                   9696: * Method conveniences::         
                   9697: * Classes and Scoping::         
1.37      anton    9698: * Dividing classes::            
1.26      crook    9699: * Object Interfaces::           
                   9700: * Objects Implementation::      
                   9701: * Objects Glossary::            
                   9702: @end menu
1.1       anton    9703: 
1.26      crook    9704: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
                   9705: and Bernd Paysan helped me with the related works section.
1.1       anton    9706: 
1.26      crook    9707: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
                   9708: @subsubsection Properties of the @file{objects.fs} model
                   9709: @cindex @file{objects.fs} properties
1.1       anton    9710: 
1.26      crook    9711: @itemize @bullet
                   9712: @item
                   9713: It is straightforward to pass objects on the stack. Passing
                   9714: selectors on the stack is a little less convenient, but possible.
1.1       anton    9715: 
1.26      crook    9716: @item
                   9717: Objects are just data structures in memory, and are referenced by their
                   9718: address. You can create words for objects with normal defining words
                   9719: like @code{constant}. Likewise, there is no difference between instance
                   9720: variables that contain objects and those that contain other data.
1.1       anton    9721: 
1.26      crook    9722: @item
                   9723: Late binding is efficient and easy to use.
1.21      crook    9724: 
1.26      crook    9725: @item
                   9726: It avoids parsing, and thus avoids problems with state-smartness
                   9727: and reduced extensibility; for convenience there are a few parsing
                   9728: words, but they have non-parsing counterparts. There are also a few
                   9729: defining words that parse. This is hard to avoid, because all standard
                   9730: defining words parse (except @code{:noname}); however, such
                   9731: words are not as bad as many other parsing words, because they are not
                   9732: state-smart.
1.21      crook    9733: 
1.26      crook    9734: @item
                   9735: It does not try to incorporate everything. It does a few things and does
                   9736: them well (IMO). In particular, this model was not designed to support
                   9737: information hiding (although it has features that may help); you can use
                   9738: a separate package for achieving this.
1.21      crook    9739: 
1.26      crook    9740: @item
                   9741: It is layered; you don't have to learn and use all features to use this
                   9742: model. Only a few features are necessary (@xref{Basic Objects Usage},
                   9743: @xref{The Objects base class}, @xref{Creating objects}.), the others
                   9744: are optional and independent of each other.
1.21      crook    9745: 
1.26      crook    9746: @item
                   9747: An implementation in ANS Forth is available.
1.21      crook    9748: 
1.26      crook    9749: @end itemize
1.21      crook    9750: 
                   9751: 
1.26      crook    9752: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
                   9753: @subsubsection Basic @file{objects.fs} Usage
                   9754: @cindex basic objects usage
                   9755: @cindex objects, basic usage
1.21      crook    9756: 
1.26      crook    9757: You can define a class for graphical objects like this:
1.21      crook    9758: 
1.26      crook    9759: @cindex @code{class} usage
                   9760: @cindex @code{end-class} usage
                   9761: @cindex @code{selector} usage
                   9762: @example
                   9763: object class \ "object" is the parent class
                   9764:   selector draw ( x y graphical -- )
                   9765: end-class graphical
                   9766: @end example
1.21      crook    9767: 
1.26      crook    9768: This code defines a class @code{graphical} with an
                   9769: operation @code{draw}.  We can perform the operation
                   9770: @code{draw} on any @code{graphical} object, e.g.:
1.21      crook    9771: 
1.26      crook    9772: @example
                   9773: 100 100 t-rex draw
                   9774: @end example
1.21      crook    9775: 
1.26      crook    9776: @noindent
                   9777: where @code{t-rex} is a word (say, a constant) that produces a
                   9778: graphical object.
1.21      crook    9779: 
1.29      crook    9780: @comment TODO add a 2nd operation eg perimeter.. and use for
1.26      crook    9781: @comment a concrete example
1.21      crook    9782: 
1.26      crook    9783: @cindex abstract class
                   9784: How do we create a graphical object? With the present definitions,
                   9785: we cannot create a useful graphical object. The class
                   9786: @code{graphical} describes graphical objects in general, but not
                   9787: any concrete graphical object type (C++ users would call it an
                   9788: @emph{abstract class}); e.g., there is no method for the selector
                   9789: @code{draw} in the class @code{graphical}.
1.21      crook    9790: 
1.26      crook    9791: For concrete graphical objects, we define child classes of the
                   9792: class @code{graphical}, e.g.:
1.21      crook    9793: 
1.26      crook    9794: @cindex @code{overrides} usage
                   9795: @cindex @code{field} usage in class definition
                   9796: @example
                   9797: graphical class \ "graphical" is the parent class
                   9798:   cell% field circle-radius
1.21      crook    9799: 
1.26      crook    9800: :noname ( x y circle -- )
                   9801:   circle-radius @@ draw-circle ;
                   9802: overrides draw
1.21      crook    9803: 
1.26      crook    9804: :noname ( n-radius circle -- )
                   9805:   circle-radius ! ;
                   9806: overrides construct
1.21      crook    9807: 
1.26      crook    9808: end-class circle
1.21      crook    9809: @end example
                   9810: 
1.26      crook    9811: Here we define a class @code{circle} as a child of @code{graphical},
                   9812: with field @code{circle-radius} (which behaves just like a field
                   9813: (@pxref{Structures}); it defines (using @code{overrides}) new methods
                   9814: for the selectors @code{draw} and @code{construct} (@code{construct} is
                   9815: defined in @code{object}, the parent class of @code{graphical}).
1.21      crook    9816: 
1.26      crook    9817: Now we can create a circle on the heap (i.e.,
                   9818: @code{allocate}d memory) with:
1.21      crook    9819: 
1.26      crook    9820: @cindex @code{heap-new} usage
1.21      crook    9821: @example
1.26      crook    9822: 50 circle heap-new constant my-circle
                   9823: @end example
1.21      crook    9824: 
1.26      crook    9825: @noindent
                   9826: @code{heap-new} invokes @code{construct}, thus
                   9827: initializing the field @code{circle-radius} with 50. We can draw
                   9828: this new circle at (100,100) with:
1.21      crook    9829: 
1.26      crook    9830: @example
                   9831: 100 100 my-circle draw
1.21      crook    9832: @end example
                   9833: 
1.26      crook    9834: @cindex selector invocation, restrictions
                   9835: @cindex class definition, restrictions
                   9836: Note: You can only invoke a selector if the object on the TOS
                   9837: (the receiving object) belongs to the class where the selector was
                   9838: defined or one of its descendents; e.g., you can invoke
                   9839: @code{draw} only for objects belonging to @code{graphical}
                   9840: or its descendents (e.g., @code{circle}).  Immediately before
                   9841: @code{end-class}, the search order has to be the same as
                   9842: immediately after @code{class}.
1.21      crook    9843: 
1.26      crook    9844: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
                   9845: @subsubsection The @file{object.fs} base class
                   9846: @cindex @code{object} class
1.21      crook    9847: 
1.26      crook    9848: When you define a class, you have to specify a parent class.  So how do
                   9849: you start defining classes? There is one class available from the start:
                   9850: @code{object}. It is ancestor for all classes and so is the
                   9851: only class that has no parent. It has two selectors: @code{construct}
                   9852: and @code{print}.
1.21      crook    9853: 
1.26      crook    9854: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
                   9855: @subsubsection Creating objects
                   9856: @cindex creating objects
                   9857: @cindex object creation
                   9858: @cindex object allocation options
1.21      crook    9859: 
1.26      crook    9860: @cindex @code{heap-new} discussion
                   9861: @cindex @code{dict-new} discussion
                   9862: @cindex @code{construct} discussion
                   9863: You can create and initialize an object of a class on the heap with
                   9864: @code{heap-new} ( ... class -- object ) and in the dictionary
                   9865: (allocation with @code{allot}) with @code{dict-new} (
                   9866: ... class -- object ). Both words invoke @code{construct}, which
                   9867: consumes the stack items indicated by "..." above.
1.21      crook    9868: 
1.26      crook    9869: @cindex @code{init-object} discussion
                   9870: @cindex @code{class-inst-size} discussion
                   9871: If you want to allocate memory for an object yourself, you can get its
                   9872: alignment and size with @code{class-inst-size 2@@} ( class --
                   9873: align size ). Once you have memory for an object, you can initialize
                   9874: it with @code{init-object} ( ... class object -- );
                   9875: @code{construct} does only a part of the necessary work.
1.21      crook    9876: 
1.26      crook    9877: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
                   9878: @subsubsection Object-Oriented Programming Style
                   9879: @cindex object-oriented programming style
1.47      crook    9880: @cindex programming style, object-oriented
1.21      crook    9881: 
1.26      crook    9882: This section is not exhaustive.
1.1       anton    9883: 
1.26      crook    9884: @cindex stack effects of selectors
                   9885: @cindex selectors and stack effects
                   9886: In general, it is a good idea to ensure that all methods for the
                   9887: same selector have the same stack effect: when you invoke a selector,
                   9888: you often have no idea which method will be invoked, so, unless all
                   9889: methods have the same stack effect, you will not know the stack effect
                   9890: of the selector invocation.
1.21      crook    9891: 
1.26      crook    9892: One exception to this rule is methods for the selector
                   9893: @code{construct}. We know which method is invoked, because we
                   9894: specify the class to be constructed at the same place. Actually, I
                   9895: defined @code{construct} as a selector only to give the users a
                   9896: convenient way to specify initialization. The way it is used, a
                   9897: mechanism different from selector invocation would be more natural
                   9898: (but probably would take more code and more space to explain).
1.21      crook    9899: 
1.26      crook    9900: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
                   9901: @subsubsection Class Binding
                   9902: @cindex class binding
                   9903: @cindex early binding
1.21      crook    9904: 
1.26      crook    9905: @cindex late binding
                   9906: Normal selector invocations determine the method at run-time depending
                   9907: on the class of the receiving object. This run-time selection is called
1.29      crook    9908: @i{late binding}.
1.21      crook    9909: 
1.26      crook    9910: Sometimes it's preferable to invoke a different method. For example,
                   9911: you might want to use the simple method for @code{print}ing
                   9912: @code{object}s instead of the possibly long-winded @code{print} method
                   9913: of the receiver class. You can achieve this by replacing the invocation
                   9914: of @code{print} with:
1.21      crook    9915: 
1.26      crook    9916: @cindex @code{[bind]} usage
                   9917: @example
                   9918: [bind] object print
1.21      crook    9919: @end example
                   9920: 
1.26      crook    9921: @noindent
                   9922: in compiled code or:
1.21      crook    9923: 
1.26      crook    9924: @cindex @code{bind} usage
1.21      crook    9925: @example
1.26      crook    9926: bind object print
1.21      crook    9927: @end example
                   9928: 
1.26      crook    9929: @cindex class binding, alternative to
                   9930: @noindent
                   9931: in interpreted code. Alternatively, you can define the method with a
                   9932: name (e.g., @code{print-object}), and then invoke it through the
                   9933: name. Class binding is just a (often more convenient) way to achieve
                   9934: the same effect; it avoids name clutter and allows you to invoke
                   9935: methods directly without naming them first.
                   9936: 
                   9937: @cindex superclass binding
                   9938: @cindex parent class binding
                   9939: A frequent use of class binding is this: When we define a method
                   9940: for a selector, we often want the method to do what the selector does
                   9941: in the parent class, and a little more. There is a special word for
                   9942: this purpose: @code{[parent]}; @code{[parent]
                   9943: @emph{selector}} is equivalent to @code{[bind] @emph{parent
                   9944: selector}}, where @code{@emph{parent}} is the parent
                   9945: class of the current class. E.g., a method definition might look like:
1.21      crook    9946: 
1.26      crook    9947: @cindex @code{[parent]} usage
1.21      crook    9948: @example
1.26      crook    9949: :noname
                   9950:   dup [parent] foo \ do parent's foo on the receiving object
                   9951:   ... \ do some more
                   9952: ; overrides foo
1.21      crook    9953: @end example
                   9954: 
1.26      crook    9955: @cindex class binding as optimization
                   9956: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
                   9957: March 1997), Andrew McKewan presents class binding as an optimization
                   9958: technique. I recommend not using it for this purpose unless you are in
                   9959: an emergency. Late binding is pretty fast with this model anyway, so the
                   9960: benefit of using class binding is small; the cost of using class binding
                   9961: where it is not appropriate is reduced maintainability.
1.21      crook    9962: 
1.26      crook    9963: While we are at programming style questions: You should bind
                   9964: selectors only to ancestor classes of the receiving object. E.g., say,
                   9965: you know that the receiving object is of class @code{foo} or its
                   9966: descendents; then you should bind only to @code{foo} and its
                   9967: ancestors.
1.21      crook    9968: 
1.26      crook    9969: @node Method conveniences, Classes and Scoping, Class Binding, Objects
                   9970: @subsubsection Method conveniences
                   9971: @cindex method conveniences
1.1       anton    9972: 
1.26      crook    9973: In a method you usually access the receiving object pretty often.  If
                   9974: you define the method as a plain colon definition (e.g., with
                   9975: @code{:noname}), you may have to do a lot of stack
                   9976: gymnastics. To avoid this, you can define the method with @code{m:
                   9977: ... ;m}. E.g., you could define the method for
                   9978: @code{draw}ing a @code{circle} with
1.20      pazsan   9979: 
1.26      crook    9980: @cindex @code{this} usage
                   9981: @cindex @code{m:} usage
                   9982: @cindex @code{;m} usage
                   9983: @example
                   9984: m: ( x y circle -- )
                   9985:   ( x y ) this circle-radius @@ draw-circle ;m
                   9986: @end example
1.20      pazsan   9987: 
1.26      crook    9988: @cindex @code{exit} in @code{m: ... ;m}
                   9989: @cindex @code{exitm} discussion
                   9990: @cindex @code{catch} in @code{m: ... ;m}
                   9991: When this method is executed, the receiver object is removed from the
                   9992: stack; you can access it with @code{this} (admittedly, in this
                   9993: example the use of @code{m: ... ;m} offers no advantage). Note
                   9994: that I specify the stack effect for the whole method (i.e. including
                   9995: the receiver object), not just for the code between @code{m:}
                   9996: and @code{;m}. You cannot use @code{exit} in
                   9997: @code{m:...;m}; instead, use
                   9998: @code{exitm}.@footnote{Moreover, for any word that calls
                   9999: @code{catch} and was defined before loading
                   10000: @code{objects.fs}, you have to redefine it like I redefined
                   10001: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.20      pazsan   10002: 
1.26      crook    10003: @cindex @code{inst-var} usage
                   10004: You will frequently use sequences of the form @code{this
                   10005: @emph{field}} (in the example above: @code{this
                   10006: circle-radius}). If you use the field only in this way, you can
                   10007: define it with @code{inst-var} and eliminate the
                   10008: @code{this} before the field name. E.g., the @code{circle}
                   10009: class above could also be defined with:
1.20      pazsan   10010: 
1.26      crook    10011: @example
                   10012: graphical class
                   10013:   cell% inst-var radius
1.20      pazsan   10014: 
1.26      crook    10015: m: ( x y circle -- )
                   10016:   radius @@ draw-circle ;m
                   10017: overrides draw
1.20      pazsan   10018: 
1.26      crook    10019: m: ( n-radius circle -- )
                   10020:   radius ! ;m
                   10021: overrides construct
1.12      anton    10022: 
1.26      crook    10023: end-class circle
                   10024: @end example
1.12      anton    10025: 
1.26      crook    10026: @code{radius} can only be used in @code{circle} and its
                   10027: descendent classes and inside @code{m:...;m}.
1.12      anton    10028: 
1.26      crook    10029: @cindex @code{inst-value} usage
                   10030: You can also define fields with @code{inst-value}, which is
                   10031: to @code{inst-var} what @code{value} is to
                   10032: @code{variable}.  You can change the value of such a field with
                   10033: @code{[to-inst]}.  E.g., we could also define the class
                   10034: @code{circle} like this:
1.12      anton    10035: 
1.26      crook    10036: @example
                   10037: graphical class
                   10038:   inst-value radius
1.12      anton    10039: 
1.26      crook    10040: m: ( x y circle -- )
                   10041:   radius draw-circle ;m
                   10042: overrides draw
1.12      anton    10043: 
1.26      crook    10044: m: ( n-radius circle -- )
                   10045:   [to-inst] radius ;m
                   10046: overrides construct
1.21      crook    10047: 
1.26      crook    10048: end-class circle
1.12      anton    10049: @end example
                   10050: 
1.38      anton    10051: Finally, you can define named methods with @code{:m}.  One use of this
                   10052: feature is the definition of words that occur only in one class and are
                   10053: not intended to be overridden, but which still need method context
                   10054: (e.g., for accessing @code{inst-var}s).  Another use is for methods that
                   10055: would be bound frequently, if defined anonymously.
                   10056: 
1.12      anton    10057: 
1.37      anton    10058: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
1.26      crook    10059: @subsubsection Classes and Scoping
                   10060: @cindex classes and scoping
                   10061: @cindex scoping and classes
1.12      anton    10062: 
1.26      crook    10063: Inheritance is frequent, unlike structure extension. This exacerbates
                   10064: the problem with the field name convention (@pxref{Structure Naming
                   10065: Convention}): One always has to remember in which class the field was
                   10066: originally defined; changing a part of the class structure would require
                   10067: changes for renaming in otherwise unaffected code.
1.12      anton    10068: 
1.26      crook    10069: @cindex @code{inst-var} visibility
                   10070: @cindex @code{inst-value} visibility
                   10071: To solve this problem, I added a scoping mechanism (which was not in my
                   10072: original charter): A field defined with @code{inst-var} (or
                   10073: @code{inst-value}) is visible only in the class where it is defined and in
                   10074: the descendent classes of this class.  Using such fields only makes
                   10075: sense in @code{m:}-defined methods in these classes anyway.
1.12      anton    10076: 
1.26      crook    10077: This scoping mechanism allows us to use the unadorned field name,
                   10078: because name clashes with unrelated words become much less likely.
1.12      anton    10079: 
1.26      crook    10080: @cindex @code{protected} discussion
                   10081: @cindex @code{private} discussion
                   10082: Once we have this mechanism, we can also use it for controlling the
                   10083: visibility of other words: All words defined after
                   10084: @code{protected} are visible only in the current class and its
                   10085: descendents. @code{public} restores the compilation
                   10086: (i.e. @code{current}) word list that was in effect before. If you
                   10087: have several @code{protected}s without an intervening
                   10088: @code{public} or @code{set-current}, @code{public}
                   10089: will restore the compilation word list in effect before the first of
                   10090: these @code{protected}s.
1.12      anton    10091: 
1.37      anton    10092: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
                   10093: @subsubsection Dividing classes
                   10094: @cindex Dividing classes
                   10095: @cindex @code{methods}...@code{end-methods}
                   10096: 
                   10097: You may want to do the definition of methods separate from the
                   10098: definition of the class, its selectors, fields, and instance variables,
                   10099: i.e., separate the implementation from the definition.  You can do this
                   10100: in the following way:
                   10101: 
                   10102: @example
                   10103: graphical class
                   10104:   inst-value radius
                   10105: end-class circle
                   10106: 
                   10107: ... \ do some other stuff
                   10108: 
                   10109: circle methods \ now we are ready
                   10110: 
                   10111: m: ( x y circle -- )
                   10112:   radius draw-circle ;m
                   10113: overrides draw
                   10114: 
                   10115: m: ( n-radius circle -- )
                   10116:   [to-inst] radius ;m
                   10117: overrides construct
                   10118: 
                   10119: end-methods
                   10120: @end example
                   10121: 
                   10122: You can use several @code{methods}...@code{end-methods} sections.  The
                   10123: only things you can do to the class in these sections are: defining
                   10124: methods, and overriding the class's selectors.  You must not define new
                   10125: selectors or fields.
                   10126: 
                   10127: Note that you often have to override a selector before using it.  In
                   10128: particular, you usually have to override @code{construct} with a new
                   10129: method before you can invoke @code{heap-new} and friends.  E.g., you
                   10130: must not create a circle before the @code{overrides construct} sequence
                   10131: in the example above.
                   10132: 
                   10133: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
1.26      crook    10134: @subsubsection Object Interfaces
                   10135: @cindex object interfaces
                   10136: @cindex interfaces for objects
1.12      anton    10137: 
1.26      crook    10138: In this model you can only call selectors defined in the class of the
                   10139: receiving objects or in one of its ancestors. If you call a selector
                   10140: with a receiving object that is not in one of these classes, the
                   10141: result is undefined; if you are lucky, the program crashes
                   10142: immediately.
1.12      anton    10143: 
1.26      crook    10144: @cindex selectors common to hardly-related classes
                   10145: Now consider the case when you want to have a selector (or several)
                   10146: available in two classes: You would have to add the selector to a
                   10147: common ancestor class, in the worst case to @code{object}. You
                   10148: may not want to do this, e.g., because someone else is responsible for
                   10149: this ancestor class.
1.12      anton    10150: 
1.26      crook    10151: The solution for this problem is interfaces. An interface is a
                   10152: collection of selectors. If a class implements an interface, the
                   10153: selectors become available to the class and its descendents. A class
                   10154: can implement an unlimited number of interfaces. For the problem
                   10155: discussed above, we would define an interface for the selector(s), and
                   10156: both classes would implement the interface.
1.12      anton    10157: 
1.26      crook    10158: As an example, consider an interface @code{storage} for
                   10159: writing objects to disk and getting them back, and a class
                   10160: @code{foo} that implements it. The code would look like this:
1.12      anton    10161: 
1.26      crook    10162: @cindex @code{interface} usage
                   10163: @cindex @code{end-interface} usage
                   10164: @cindex @code{implementation} usage
                   10165: @example
                   10166: interface
                   10167:   selector write ( file object -- )
                   10168:   selector read1 ( file object -- )
                   10169: end-interface storage
1.12      anton    10170: 
1.26      crook    10171: bar class
                   10172:   storage implementation
1.12      anton    10173: 
1.26      crook    10174: ... overrides write
1.37      anton    10175: ... overrides read1
1.26      crook    10176: ...
                   10177: end-class foo
1.12      anton    10178: @end example
                   10179: 
1.26      crook    10180: @noindent
1.29      crook    10181: (I would add a word @code{read} @i{( file -- object )} that uses
1.26      crook    10182: @code{read1} internally, but that's beyond the point illustrated
                   10183: here.)
1.12      anton    10184: 
1.26      crook    10185: Note that you cannot use @code{protected} in an interface; and
                   10186: of course you cannot define fields.
1.12      anton    10187: 
1.26      crook    10188: In the Neon model, all selectors are available for all classes;
                   10189: therefore it does not need interfaces. The price you pay in this model
                   10190: is slower late binding, and therefore, added complexity to avoid late
                   10191: binding.
1.12      anton    10192: 
1.26      crook    10193: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
                   10194: @subsubsection @file{objects.fs} Implementation
                   10195: @cindex @file{objects.fs} implementation
1.12      anton    10196: 
1.26      crook    10197: @cindex @code{object-map} discussion
                   10198: An object is a piece of memory, like one of the data structures
                   10199: described with @code{struct...end-struct}. It has a field
                   10200: @code{object-map} that points to the method map for the object's
                   10201: class.
1.12      anton    10202: 
1.26      crook    10203: @cindex method map
                   10204: @cindex virtual function table
                   10205: The @emph{method map}@footnote{This is Self terminology; in C++
                   10206: terminology: virtual function table.} is an array that contains the
1.29      crook    10207: execution tokens (@i{xt}s) of the methods for the object's class. Each
1.26      crook    10208: selector contains an offset into a method map.
1.12      anton    10209: 
1.26      crook    10210: @cindex @code{selector} implementation, class
                   10211: @code{selector} is a defining word that uses
                   10212: @code{CREATE} and @code{DOES>}. The body of the
1.44      crook    10213: selector contains the offset; the @code{DOES>} action for a
1.26      crook    10214: class selector is, basically:
1.21      crook    10215: 
1.26      crook    10216: @example
                   10217: ( object addr ) @@ over object-map @@ + @@ execute
                   10218: @end example
1.12      anton    10219: 
1.26      crook    10220: Since @code{object-map} is the first field of the object, it
                   10221: does not generate any code. As you can see, calling a selector has a
                   10222: small, constant cost.
1.12      anton    10223: 
1.26      crook    10224: @cindex @code{current-interface} discussion
                   10225: @cindex class implementation and representation
                   10226: A class is basically a @code{struct} combined with a method
                   10227: map. During the class definition the alignment and size of the class
                   10228: are passed on the stack, just as with @code{struct}s, so
                   10229: @code{field} can also be used for defining class
                   10230: fields. However, passing more items on the stack would be
                   10231: inconvenient, so @code{class} builds a data structure in memory,
                   10232: which is accessed through the variable
                   10233: @code{current-interface}. After its definition is complete, the
                   10234: class is represented on the stack by a pointer (e.g., as parameter for
                   10235: a child class definition).
1.1       anton    10236: 
1.26      crook    10237: A new class starts off with the alignment and size of its parent,
                   10238: and a copy of the parent's method map. Defining new fields extends the
                   10239: size and alignment; likewise, defining new selectors extends the
1.29      crook    10240: method map. @code{overrides} just stores a new @i{xt} in the method
1.26      crook    10241: map at the offset given by the selector.
1.20      pazsan   10242: 
1.26      crook    10243: @cindex class binding, implementation
1.29      crook    10244: Class binding just gets the @i{xt} at the offset given by the selector
1.26      crook    10245: from the class's method map and @code{compile,}s (in the case of
                   10246: @code{[bind]}) it.
1.21      crook    10247: 
1.26      crook    10248: @cindex @code{this} implementation
                   10249: @cindex @code{catch} and @code{this}
                   10250: @cindex @code{this} and @code{catch}
                   10251: I implemented @code{this} as a @code{value}. At the
                   10252: start of an @code{m:...;m} method the old @code{this} is
                   10253: stored to the return stack and restored at the end; and the object on
                   10254: the TOS is stored @code{TO this}. This technique has one
                   10255: disadvantage: If the user does not leave the method via
                   10256: @code{;m}, but via @code{throw} or @code{exit},
                   10257: @code{this} is not restored (and @code{exit} may
                   10258: crash). To deal with the @code{throw} problem, I have redefined
                   10259: @code{catch} to save and restore @code{this}; the same
                   10260: should be done with any word that can catch an exception. As for
                   10261: @code{exit}, I simply forbid it (as a replacement, there is
                   10262: @code{exitm}).
1.21      crook    10263: 
1.26      crook    10264: @cindex @code{inst-var} implementation
                   10265: @code{inst-var} is just the same as @code{field}, with
                   10266: a different @code{DOES>} action:
                   10267: @example
                   10268: @@ this +
                   10269: @end example
                   10270: Similar for @code{inst-value}.
1.21      crook    10271: 
1.26      crook    10272: @cindex class scoping implementation
                   10273: Each class also has a word list that contains the words defined with
                   10274: @code{inst-var} and @code{inst-value}, and its protected
                   10275: words. It also has a pointer to its parent. @code{class} pushes
                   10276: the word lists of the class and all its ancestors onto the search order stack,
                   10277: and @code{end-class} drops them.
1.21      crook    10278: 
1.26      crook    10279: @cindex interface implementation
                   10280: An interface is like a class without fields, parent and protected
                   10281: words; i.e., it just has a method map. If a class implements an
                   10282: interface, its method map contains a pointer to the method map of the
                   10283: interface. The positive offsets in the map are reserved for class
                   10284: methods, therefore interface map pointers have negative
                   10285: offsets. Interfaces have offsets that are unique throughout the
                   10286: system, unlike class selectors, whose offsets are only unique for the
                   10287: classes where the selector is available (invokable).
1.21      crook    10288: 
1.26      crook    10289: This structure means that interface selectors have to perform one
                   10290: indirection more than class selectors to find their method. Their body
                   10291: contains the interface map pointer offset in the class method map, and
                   10292: the method offset in the interface method map. The
                   10293: @code{does>} action for an interface selector is, basically:
1.21      crook    10294: 
                   10295: @example
1.26      crook    10296: ( object selector-body )
                   10297: 2dup selector-interface @@ ( object selector-body object interface-offset )
                   10298: swap object-map @@ + @@ ( object selector-body map )
                   10299: swap selector-offset @@ + @@ execute
1.21      crook    10300: @end example
                   10301: 
1.26      crook    10302: where @code{object-map} and @code{selector-offset} are
                   10303: first fields and generate no code.
                   10304: 
                   10305: As a concrete example, consider the following code:
1.21      crook    10306: 
1.26      crook    10307: @example
                   10308: interface
                   10309:   selector if1sel1
                   10310:   selector if1sel2
                   10311: end-interface if1
1.21      crook    10312: 
1.26      crook    10313: object class
                   10314:   if1 implementation
                   10315:   selector cl1sel1
                   10316:   cell% inst-var cl1iv1
1.21      crook    10317: 
1.26      crook    10318: ' m1 overrides construct
                   10319: ' m2 overrides if1sel1
                   10320: ' m3 overrides if1sel2
                   10321: ' m4 overrides cl1sel2
                   10322: end-class cl1
1.21      crook    10323: 
1.26      crook    10324: create obj1 object dict-new drop
                   10325: create obj2 cl1    dict-new drop
                   10326: @end example
1.21      crook    10327: 
1.26      crook    10328: The data structure created by this code (including the data structure
                   10329: for @code{object}) is shown in the <a
                   10330: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
1.29      crook    10331: @comment TODO add this diagram..
1.21      crook    10332: 
1.26      crook    10333: @node Objects Glossary,  , Objects Implementation, Objects
                   10334: @subsubsection @file{objects.fs} Glossary
                   10335: @cindex @file{objects.fs} Glossary
1.21      crook    10336: 
1.44      crook    10337: 
1.26      crook    10338: doc---objects-bind
                   10339: doc---objects-<bind>
                   10340: doc---objects-bind'
                   10341: doc---objects-[bind]
                   10342: doc---objects-class
                   10343: doc---objects-class->map
                   10344: doc---objects-class-inst-size
                   10345: doc---objects-class-override!
                   10346: doc---objects-construct
                   10347: doc---objects-current'
                   10348: doc---objects-[current]
                   10349: doc---objects-current-interface
                   10350: doc---objects-dict-new
                   10351: doc---objects-drop-order
                   10352: doc---objects-end-class
                   10353: doc---objects-end-class-noname
                   10354: doc---objects-end-interface
                   10355: doc---objects-end-interface-noname
1.37      anton    10356: doc---objects-end-methods
1.26      crook    10357: doc---objects-exitm
                   10358: doc---objects-heap-new
                   10359: doc---objects-implementation
                   10360: doc---objects-init-object
                   10361: doc---objects-inst-value
                   10362: doc---objects-inst-var
                   10363: doc---objects-interface
1.38      anton    10364: doc---objects-m:
                   10365: doc---objects-:m
1.26      crook    10366: doc---objects-;m
                   10367: doc---objects-method
1.37      anton    10368: doc---objects-methods
1.26      crook    10369: doc---objects-object
                   10370: doc---objects-overrides
                   10371: doc---objects-[parent]
                   10372: doc---objects-print
                   10373: doc---objects-protected
                   10374: doc---objects-public
                   10375: doc---objects-push-order
                   10376: doc---objects-selector
                   10377: doc---objects-this
                   10378: doc---objects-<to-inst>
                   10379: doc---objects-[to-inst]
                   10380: doc---objects-to-this
                   10381: doc---objects-xt-new
1.21      crook    10382: 
1.44      crook    10383: 
1.26      crook    10384: @c -------------------------------------------------------------
                   10385: @node OOF, Mini-OOF, Objects, Object-oriented Forth
                   10386: @subsection The @file{oof.fs} model
                   10387: @cindex oof
                   10388: @cindex object-oriented programming
1.21      crook    10389: 
1.26      crook    10390: @cindex @file{objects.fs}
                   10391: @cindex @file{oof.fs}
1.21      crook    10392: 
1.26      crook    10393: This section describes the @file{oof.fs} package.
1.21      crook    10394: 
1.26      crook    10395: The package described in this section has been used in bigFORTH since 1991, and
                   10396: used for two large applications: a chromatographic system used to
                   10397: create new medicaments, and a graphic user interface library (MINOS).
1.21      crook    10398: 
1.26      crook    10399: You can find a description (in German) of @file{oof.fs} in @cite{Object
                   10400: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
                   10401: 10(2), 1994.
1.21      crook    10402: 
1.26      crook    10403: @menu
                   10404: * Properties of the OOF model::
                   10405: * Basic OOF Usage::
                   10406: * The OOF base class::
                   10407: * Class Declaration::
                   10408: * Class Implementation::
                   10409: @end menu
1.21      crook    10410: 
1.26      crook    10411: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
                   10412: @subsubsection Properties of the @file{oof.fs} model
                   10413: @cindex @file{oof.fs} properties
1.21      crook    10414: 
1.26      crook    10415: @itemize @bullet
                   10416: @item
                   10417: This model combines object oriented programming with information
                   10418: hiding. It helps you writing large application, where scoping is
                   10419: necessary, because it provides class-oriented scoping.
1.21      crook    10420: 
1.26      crook    10421: @item
                   10422: Named objects, object pointers, and object arrays can be created,
                   10423: selector invocation uses the ``object selector'' syntax. Selector invocation
                   10424: to objects and/or selectors on the stack is a bit less convenient, but
                   10425: possible.
1.21      crook    10426: 
1.26      crook    10427: @item
                   10428: Selector invocation and instance variable usage of the active object is
                   10429: straightforward, since both make use of the active object.
1.21      crook    10430: 
1.26      crook    10431: @item
                   10432: Late binding is efficient and easy to use.
1.21      crook    10433: 
1.26      crook    10434: @item
                   10435: State-smart objects parse selectors. However, extensibility is provided
                   10436: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.21      crook    10437: 
                   10438: @item
1.26      crook    10439: An implementation in ANS Forth is available.
                   10440: 
1.21      crook    10441: @end itemize
                   10442: 
                   10443: 
1.26      crook    10444: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
                   10445: @subsubsection Basic @file{oof.fs} Usage
                   10446: @cindex @file{oof.fs} usage
                   10447: 
                   10448: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.21      crook    10449: 
1.26      crook    10450: You can define a class for graphical objects like this:
1.21      crook    10451: 
1.26      crook    10452: @cindex @code{class} usage
                   10453: @cindex @code{class;} usage
                   10454: @cindex @code{method} usage
                   10455: @example
                   10456: object class graphical \ "object" is the parent class
                   10457:   method draw ( x y graphical -- )
                   10458: class;
                   10459: @end example
1.21      crook    10460: 
1.26      crook    10461: This code defines a class @code{graphical} with an
                   10462: operation @code{draw}.  We can perform the operation
                   10463: @code{draw} on any @code{graphical} object, e.g.:
1.21      crook    10464: 
1.26      crook    10465: @example
                   10466: 100 100 t-rex draw
                   10467: @end example
1.21      crook    10468: 
1.26      crook    10469: @noindent
                   10470: where @code{t-rex} is an object or object pointer, created with e.g.
                   10471: @code{graphical : t-rex}.
1.21      crook    10472: 
1.26      crook    10473: @cindex abstract class
                   10474: How do we create a graphical object? With the present definitions,
                   10475: we cannot create a useful graphical object. The class
                   10476: @code{graphical} describes graphical objects in general, but not
                   10477: any concrete graphical object type (C++ users would call it an
                   10478: @emph{abstract class}); e.g., there is no method for the selector
                   10479: @code{draw} in the class @code{graphical}.
1.21      crook    10480: 
1.26      crook    10481: For concrete graphical objects, we define child classes of the
                   10482: class @code{graphical}, e.g.:
1.21      crook    10483: 
                   10484: @example
1.26      crook    10485: graphical class circle \ "graphical" is the parent class
                   10486:   cell var circle-radius
                   10487: how:
                   10488:   : draw ( x y -- )
                   10489:     circle-radius @@ draw-circle ;
                   10490: 
                   10491:   : init ( n-radius -- (
                   10492:     circle-radius ! ;
                   10493: class;
                   10494: @end example
                   10495: 
                   10496: Here we define a class @code{circle} as a child of @code{graphical},
                   10497: with a field @code{circle-radius}; it defines new methods for the
                   10498: selectors @code{draw} and @code{init} (@code{init} is defined in
                   10499: @code{object}, the parent class of @code{graphical}).
1.21      crook    10500: 
1.26      crook    10501: Now we can create a circle in the dictionary with:
1.21      crook    10502: 
1.26      crook    10503: @example
                   10504: 50 circle : my-circle
1.21      crook    10505: @end example
                   10506: 
1.26      crook    10507: @noindent
                   10508: @code{:} invokes @code{init}, thus initializing the field
                   10509: @code{circle-radius} with 50. We can draw this new circle at (100,100)
                   10510: with:
1.21      crook    10511: 
                   10512: @example
1.26      crook    10513: 100 100 my-circle draw
1.21      crook    10514: @end example
                   10515: 
1.26      crook    10516: @cindex selector invocation, restrictions
                   10517: @cindex class definition, restrictions
                   10518: Note: You can only invoke a selector if the receiving object belongs to
                   10519: the class where the selector was defined or one of its descendents;
                   10520: e.g., you can invoke @code{draw} only for objects belonging to
                   10521: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
                   10522: mechanism will check if you try to invoke a selector that is not
                   10523: defined in this class hierarchy, so you'll get an error at compilation
                   10524: time.
                   10525: 
                   10526: 
                   10527: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
                   10528: @subsubsection The @file{oof.fs} base class
                   10529: @cindex @file{oof.fs} base class
                   10530: 
                   10531: When you define a class, you have to specify a parent class.  So how do
                   10532: you start defining classes? There is one class available from the start:
                   10533: @code{object}. You have to use it as ancestor for all classes. It is the
                   10534: only class that has no parent. Classes are also objects, except that
                   10535: they don't have instance variables; class manipulation such as
                   10536: inheritance or changing definitions of a class is handled through
                   10537: selectors of the class @code{object}.
                   10538: 
                   10539: @code{object} provides a number of selectors:
                   10540: 
1.21      crook    10541: @itemize @bullet
                   10542: @item
1.26      crook    10543: @code{class} for subclassing, @code{definitions} to add definitions
                   10544: later on, and @code{class?} to get type informations (is the class a
                   10545: subclass of the class passed on the stack?).
1.44      crook    10546: 
1.26      crook    10547: doc---object-class
                   10548: doc---object-definitions
                   10549: doc---object-class?
                   10550: 
1.44      crook    10551: 
1.21      crook    10552: @item
1.26      crook    10553: @code{init} and @code{dispose} as constructor and destructor of the
                   10554: object. @code{init} is invocated after the object's memory is allocated,
                   10555: while @code{dispose} also handles deallocation. Thus if you redefine
                   10556: @code{dispose}, you have to call the parent's dispose with @code{super
                   10557: dispose}, too.
1.44      crook    10558: 
1.26      crook    10559: doc---object-init
                   10560: doc---object-dispose
                   10561: 
1.44      crook    10562: 
1.21      crook    10563: @item
1.26      crook    10564: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
                   10565: @code{[]} to create named and unnamed objects and object arrays or
                   10566: object pointers.
1.44      crook    10567: 
1.26      crook    10568: doc---object-new
                   10569: doc---object-new[]
                   10570: doc---object-:
                   10571: doc---object-ptr
                   10572: doc---object-asptr
                   10573: doc---object-[]
1.21      crook    10574: 
1.44      crook    10575: 
1.26      crook    10576: @item
                   10577: @code{::} and @code{super} for explicit scoping. You should use explicit
                   10578: scoping only for super classes or classes with the same set of instance
                   10579: variables. Explicitly-scoped selectors use early binding.
1.44      crook    10580: 
1.26      crook    10581: doc---object-::
                   10582: doc---object-super
1.21      crook    10583: 
1.44      crook    10584: 
1.26      crook    10585: @item
                   10586: @code{self} to get the address of the object
1.44      crook    10587: 
1.26      crook    10588: doc---object-self
1.21      crook    10589: 
1.44      crook    10590: 
1.21      crook    10591: @item
1.26      crook    10592: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
                   10593: pointers and instance defers.
1.44      crook    10594: 
1.26      crook    10595: doc---object-bind
                   10596: doc---object-bound
                   10597: doc---object-link
                   10598: doc---object-is
                   10599: 
1.44      crook    10600: 
1.21      crook    10601: @item
1.26      crook    10602: @code{'} to obtain selector tokens, @code{send} to invocate selectors
                   10603: form the stack, and @code{postpone} to generate selector invocation code.
1.44      crook    10604: 
1.26      crook    10605: doc---object-'
                   10606: doc---object-postpone
                   10607: 
1.44      crook    10608: 
1.21      crook    10609: @item
1.26      crook    10610: @code{with} and @code{endwith} to select the active object from the
                   10611: stack, and enable its scope. Using @code{with} and @code{endwith}
                   10612: also allows you to create code using selector @code{postpone} without being
                   10613: trapped by the state-smart objects.
1.44      crook    10614: 
1.26      crook    10615: doc---object-with
                   10616: doc---object-endwith
                   10617: 
1.44      crook    10618: 
1.21      crook    10619: @end itemize
                   10620: 
1.26      crook    10621: @node Class Declaration, Class Implementation, The OOF base class, OOF
                   10622: @subsubsection Class Declaration
                   10623: @cindex class declaration
                   10624: 
                   10625: @itemize @bullet
                   10626: @item
                   10627: Instance variables
1.44      crook    10628: 
1.26      crook    10629: doc---oof-var
1.21      crook    10630: 
1.44      crook    10631: 
1.26      crook    10632: @item
                   10633: Object pointers
1.44      crook    10634: 
1.26      crook    10635: doc---oof-ptr
                   10636: doc---oof-asptr
1.21      crook    10637: 
1.44      crook    10638: 
1.26      crook    10639: @item
                   10640: Instance defers
1.44      crook    10641: 
1.26      crook    10642: doc---oof-defer
1.21      crook    10643: 
1.44      crook    10644: 
1.26      crook    10645: @item
                   10646: Method selectors
1.44      crook    10647: 
1.26      crook    10648: doc---oof-early
                   10649: doc---oof-method
1.21      crook    10650: 
1.44      crook    10651: 
1.26      crook    10652: @item
                   10653: Class-wide variables
1.44      crook    10654: 
1.26      crook    10655: doc---oof-static
1.21      crook    10656: 
1.44      crook    10657: 
1.26      crook    10658: @item
                   10659: End declaration
1.44      crook    10660: 
1.26      crook    10661: doc---oof-how:
                   10662: doc---oof-class;
1.21      crook    10663: 
1.44      crook    10664: 
1.26      crook    10665: @end itemize
1.21      crook    10666: 
1.26      crook    10667: @c -------------------------------------------------------------
                   10668: @node Class Implementation,  , Class Declaration, OOF
                   10669: @subsubsection Class Implementation
                   10670: @cindex class implementation
1.21      crook    10671: 
1.26      crook    10672: @c -------------------------------------------------------------
                   10673: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
                   10674: @subsection The @file{mini-oof.fs} model
                   10675: @cindex mini-oof
1.1       anton    10676: 
1.26      crook    10677: Gforth's third object oriented Forth package is a 12-liner. It uses a
                   10678: mixture of the @file{object.fs} and the @file{oof.fs} syntax,
                   10679: and reduces to the bare minimum of features. This is based on a posting
                   10680: of Bernd Paysan in comp.arch.
1.1       anton    10681: 
                   10682: @menu
1.48    ! anton    10683: * Basic Mini-OOF Usage::        
        !          10684: * Mini-OOF Example::            
        !          10685: * Mini-OOF Implementation::     
        !          10686: * Comparison with other object models::  
1.1       anton    10687: @end menu
                   10688: 
1.26      crook    10689: @c -------------------------------------------------------------
1.48    ! anton    10690: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
1.26      crook    10691: @subsubsection Basic @file{mini-oof.fs} Usage
                   10692: @cindex mini-oof usage
1.1       anton    10693: 
1.28      crook    10694: There is a base class (@code{class}, which allocates one cell for the
                   10695: object pointer) plus seven other words: to define a method, a variable,
                   10696: a class; to end a class, to resolve binding, to allocate an object and
                   10697: to compile a class method.
1.26      crook    10698: @comment TODO better description of the last one
1.1       anton    10699: 
1.44      crook    10700: 
1.26      crook    10701: doc-object
                   10702: doc-method
                   10703: doc-var
                   10704: doc-class
                   10705: doc-end-class
                   10706: doc-defines
                   10707: doc-new
                   10708: doc-::
1.1       anton    10709: 
1.21      crook    10710: 
1.44      crook    10711: 
1.26      crook    10712: @c -------------------------------------------------------------
                   10713: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
                   10714: @subsubsection Mini-OOF Example
                   10715: @cindex mini-oof example
1.21      crook    10716: 
1.26      crook    10717: A short example shows how to use this package. This example, in slightly
                   10718: extended form, is supplied as @file{moof-exm.fs}
1.29      crook    10719: @comment TODO could flesh this out with some comments from the Forthwrite article
1.21      crook    10720: 
1.26      crook    10721: @example
                   10722: object class
                   10723:   method init
                   10724:   method draw
                   10725: end-class graphical
                   10726: @end example
1.21      crook    10727: 
1.26      crook    10728: This code defines a class @code{graphical} with an
                   10729: operation @code{draw}.  We can perform the operation
                   10730: @code{draw} on any @code{graphical} object, e.g.:
1.1       anton    10731: 
1.26      crook    10732: @example
                   10733: 100 100 t-rex draw
                   10734: @end example
1.1       anton    10735: 
1.26      crook    10736: where @code{t-rex} is an object or object pointer, created with e.g.
                   10737: @code{graphical new Constant t-rex}.
1.1       anton    10738: 
1.26      crook    10739: For concrete graphical objects, we define child classes of the
                   10740: class @code{graphical}, e.g.:
1.21      crook    10741: 
                   10742: @example
1.26      crook    10743: graphical class
                   10744:   cell var circle-radius
                   10745: end-class circle \ "graphical" is the parent class
1.21      crook    10746: 
1.26      crook    10747: :noname ( x y -- )
                   10748:   circle-radius @@ draw-circle ; circle defines draw
                   10749: :noname ( r -- )
                   10750:   circle-radius ! ; circle defines init
1.21      crook    10751: @end example
                   10752: 
1.26      crook    10753: There is no implicit init method, so we have to define one. The creation
                   10754: code of the object now has to call init explicitely.
1.21      crook    10755: 
1.26      crook    10756: @example
                   10757: circle new Constant my-circle
                   10758: 50 my-circle init
                   10759: @end example
1.21      crook    10760: 
1.26      crook    10761: It is also possible to add a function to create named objects with
                   10762: automatic call of @code{init}, given that all objects have @code{init}
                   10763: on the same place:
1.1       anton    10764: 
                   10765: @example
1.26      crook    10766: : new: ( .. o "name" -- )
                   10767:     new dup Constant init ;
                   10768: 80 circle new: large-circle
1.1       anton    10769: @end example
                   10770: 
1.26      crook    10771: We can draw this new circle at (100,100) with:
1.1       anton    10772: 
                   10773: @example
1.26      crook    10774: 100 100 my-circle draw
1.1       anton    10775: @end example
                   10776: 
1.48    ! anton    10777: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
1.26      crook    10778: @subsubsection @file{mini-oof.fs} Implementation
1.1       anton    10779: 
1.26      crook    10780: Object-oriented systems with late binding typically use a
                   10781: ``vtable''-approach: the first variable in each object is a pointer to a
                   10782: table, which contains the methods as function pointers. The vtable
                   10783: may also contain other information.
1.1       anton    10784: 
1.26      crook    10785: So first, let's declare methods:
1.1       anton    10786: 
1.26      crook    10787: @example
                   10788: : method ( m v -- m' v ) Create  over , swap cell+ swap
                   10789:   DOES> ( ... o -- ... ) @ over @ + @ execute ;
                   10790: @end example
1.1       anton    10791: 
1.26      crook    10792: During method declaration, the number of methods and instance
                   10793: variables is on the stack (in address units). @code{method} creates
                   10794: one method and increments the method number. To execute a method, it
                   10795: takes the object, fetches the vtable pointer, adds the offset, and
1.29      crook    10796: executes the @i{xt} stored there. Each method takes the object it is
1.26      crook    10797: invoked from as top of stack parameter. The method itself should
                   10798: consume that object.
1.1       anton    10799: 
1.26      crook    10800: Now, we also have to declare instance variables
1.21      crook    10801: 
1.26      crook    10802: @example
                   10803: : var ( m v size -- m v' ) Create  over , +
                   10804:   DOES> ( o -- addr ) @ + ;
                   10805: @end example
1.21      crook    10806: 
1.26      crook    10807: As before, a word is created with the current offset. Instance
                   10808: variables can have different sizes (cells, floats, doubles, chars), so
                   10809: all we do is take the size and add it to the offset. If your machine
                   10810: has alignment restrictions, put the proper @code{aligned} or
                   10811: @code{faligned} before the variable, to adjust the variable
                   10812: offset. That's why it is on the top of stack.
1.2       jwilke   10813: 
1.26      crook    10814: We need a starting point (the base object) and some syntactic sugar:
1.21      crook    10815: 
1.26      crook    10816: @example
                   10817: Create object  1 cells , 2 cells ,
                   10818: : class ( class -- class methods vars ) dup 2@ ;
                   10819: @end example
1.21      crook    10820: 
1.26      crook    10821: For inheritance, the vtable of the parent object has to be
                   10822: copied when a new, derived class is declared. This gives all the
                   10823: methods of the parent class, which can be overridden, though.
1.21      crook    10824: 
1.2       jwilke   10825: @example
1.26      crook    10826: : end-class  ( class methods vars -- )
                   10827:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
                   10828:   cell+ dup cell+ r> rot @ 2 cells /string move ;
                   10829: @end example
                   10830: 
                   10831: The first line creates the vtable, initialized with
                   10832: @code{noop}s. The second line is the inheritance mechanism, it
                   10833: copies the xts from the parent vtable.
1.2       jwilke   10834: 
1.26      crook    10835: We still have no way to define new methods, let's do that now:
1.2       jwilke   10836: 
1.26      crook    10837: @example
                   10838: : defines ( xt class -- ) ' >body @ + ! ;
1.2       jwilke   10839: @end example
                   10840: 
1.26      crook    10841: To allocate a new object, we need a word, too:
1.2       jwilke   10842: 
1.26      crook    10843: @example
                   10844: : new ( class -- o )  here over @ allot swap over ! ;
                   10845: @end example
1.2       jwilke   10846: 
1.26      crook    10847: Sometimes derived classes want to access the method of the
                   10848: parent object. There are two ways to achieve this with Mini-OOF:
                   10849: first, you could use named words, and second, you could look up the
                   10850: vtable of the parent object.
1.2       jwilke   10851: 
1.26      crook    10852: @example
                   10853: : :: ( class "name" -- ) ' >body @ + @ compile, ;
                   10854: @end example
1.2       jwilke   10855: 
                   10856: 
1.26      crook    10857: Nothing can be more confusing than a good example, so here is
                   10858: one. First let's declare a text object (called
                   10859: @code{button}), that stores text and position:
1.2       jwilke   10860: 
1.26      crook    10861: @example
                   10862: object class
                   10863:   cell var text
                   10864:   cell var len
                   10865:   cell var x
                   10866:   cell var y
                   10867:   method init
                   10868:   method draw
                   10869: end-class button
                   10870: @end example
1.2       jwilke   10871: 
1.26      crook    10872: @noindent
                   10873: Now, implement the two methods, @code{draw} and @code{init}:
1.2       jwilke   10874: 
1.26      crook    10875: @example
                   10876: :noname ( o -- )
                   10877:  >r r@ x @ r@ y @ at-xy  r@ text @ r> len @ type ;
                   10878:  button defines draw
                   10879: :noname ( addr u o -- )
                   10880:  >r 0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
                   10881:  button defines init
                   10882: @end example
1.2       jwilke   10883: 
1.26      crook    10884: @noindent
                   10885: To demonstrate inheritance, we define a class @code{bold-button}, with no
                   10886: new data and no new methods:
1.2       jwilke   10887: 
1.26      crook    10888: @example
                   10889: button class
                   10890: end-class bold-button
1.1       anton    10891: 
1.26      crook    10892: : bold   27 emit ." [1m" ;
                   10893: : normal 27 emit ." [0m" ;
                   10894: @end example
1.1       anton    10895: 
1.26      crook    10896: @noindent
                   10897: The class @code{bold-button} has a different draw method to
                   10898: @code{button}, but the new method is defined in terms of the draw method
                   10899: for @code{button}:
1.1       anton    10900: 
1.26      crook    10901: @example
                   10902: :noname bold [ button :: draw ] normal ; bold-button defines draw
                   10903: @end example
1.1       anton    10904: 
1.26      crook    10905: @noindent
                   10906: Finally, create two objects and apply methods:
1.1       anton    10907: 
1.26      crook    10908: @example
                   10909: button new Constant foo
                   10910: s" thin foo" foo init
                   10911: page
                   10912: foo draw
                   10913: bold-button new Constant bar
                   10914: s" fat bar" bar init
                   10915: 1 bar y !
                   10916: bar draw
                   10917: @end example
1.1       anton    10918: 
                   10919: 
1.48    ! anton    10920: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
        !          10921: @subsection Comparison with other object models
1.26      crook    10922: @cindex comparison of object models
                   10923: @cindex object models, comparison
1.1       anton    10924: 
1.26      crook    10925: Many object-oriented Forth extensions have been proposed (@cite{A survey
                   10926: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
                   10927: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
                   10928: relation of the object models described here to two well-known and two
                   10929: closely-related (by the use of method maps) models.
1.1       anton    10930: 
1.26      crook    10931: @cindex Neon model
                   10932: The most popular model currently seems to be the Neon model (see
                   10933: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
                   10934: 1997) by Andrew McKewan) but this model has a number of limitations
                   10935: @footnote{A longer version of this critique can be
                   10936: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
                   10937: Dimensions, May 1997) by Anton Ertl.}:
1.1       anton    10938: 
1.26      crook    10939: @itemize @bullet
                   10940: @item
1.48    ! anton    10941: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
        !          10942: to pass objects on the stack.
1.1       anton    10943: 
1.26      crook    10944: @item
                   10945: It requires that the selector parses the input stream (at
                   10946: compile time); this leads to reduced extensibility and to bugs that are+
                   10947: hard to find.
1.1       anton    10948: 
1.26      crook    10949: @item
                   10950: It allows using every selector to every object;
                   10951: this eliminates the need for classes, but makes it harder to create
                   10952: efficient implementations. 
                   10953: @end itemize
1.1       anton    10954: 
1.26      crook    10955: @cindex Pountain's object-oriented model
                   10956: Another well-known publication is @cite{Object-Oriented Forth} (Academic
                   10957: Press, London, 1987) by Dick Pountain. However, it is not really about
                   10958: object-oriented programming, because it hardly deals with late
                   10959: binding. Instead, it focuses on features like information hiding and
                   10960: overloading that are characteristic of modular languages like Ada (83).
1.1       anton    10961: 
1.26      crook    10962: @cindex Zsoter's object-oriented model
1.48    ! anton    10963: In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1)
        !          10964: 1996, pages 31-35) Andras Zsoter describes a model that makes heavy use
        !          10965: of an active object (like @code{this} in @file{objects.fs}): The active
        !          10966: object is not only used for accessing all fields, but also specifies the
        !          10967: receiving object of every selector invocation; you have to change the
        !          10968: active object explicitly with @code{@{ ... @}}, whereas in
        !          10969: @file{objects.fs} it changes more or less implicitly at @code{m:
        !          10970: ... ;m}. Such a change at the method entry point is unnecessary with the
        !          10971: Zsoter's model, because the receiving object is the active object
        !          10972: already. On the other hand, the explicit change is absolutely necessary
        !          10973: in that model, because otherwise no one could ever change the active
        !          10974: object. An ANS Forth implementation of this model is available at
        !          10975: @uref{http://www.forth.org/fig/oopf.html}.
1.1       anton    10976: 
1.26      crook    10977: @cindex @file{oof.fs}, differences to other models
                   10978: The @file{oof.fs} model combines information hiding and overloading
                   10979: resolution (by keeping names in various word lists) with object-oriented
                   10980: programming. It sets the active object implicitly on method entry, but
                   10981: also allows explicit changing (with @code{>o...o>} or with
                   10982: @code{with...endwith}). It uses parsing and state-smart objects and
                   10983: classes for resolving overloading and for early binding: the object or
                   10984: class parses the selector and determines the method from this. If the
                   10985: selector is not parsed by an object or class, it performs a call to the
                   10986: selector for the active object (late binding), like Zsoter's model.
                   10987: Fields are always accessed through the active object. The big
                   10988: disadvantage of this model is the parsing and the state-smartness, which
                   10989: reduces extensibility and increases the opportunities for subtle bugs;
                   10990: essentially, you are only safe if you never tick or @code{postpone} an
                   10991: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.1       anton    10992: 
1.26      crook    10993: @cindex @file{mini-oof.fs}, differences to other models
1.48    ! anton    10994: The @file{mini-oof.fs} model is quite similar to a very stripped-down
        !          10995: version of the @file{objects.fs} model, but syntactically it is a
        !          10996: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.1       anton    10997: 
1.26      crook    10998: @c -------------------------------------------------------------
1.47      crook    10999: @node Passing Commands to the OS, Keeping track of Time, Object-oriented Forth, Words
1.21      crook    11000: @section Passing Commands to the Operating System
                   11001: @cindex operating system - passing commands
                   11002: @cindex shell commands
                   11003: 
                   11004: Gforth allows you to pass an arbitrary string to the host operating
                   11005: system shell (if such a thing exists) for execution.
                   11006: 
1.44      crook    11007: 
1.21      crook    11008: doc-sh
                   11009: doc-system
                   11010: doc-$?
1.23      crook    11011: doc-getenv
1.21      crook    11012: 
1.44      crook    11013: 
1.26      crook    11014: @c -------------------------------------------------------------
1.47      crook    11015: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
                   11016: @section Keeping track of Time
                   11017: @cindex time-related words
                   11018: 
                   11019: Gforth implements time-related operations by making calls to the C
                   11020: library function, @code{gettimeofday}.
                   11021: 
                   11022: doc-ms
                   11023: doc-time&date
                   11024: 
                   11025: 
                   11026: 
                   11027: @c -------------------------------------------------------------
                   11028: @node Miscellaneous Words,  , Keeping track of Time, Words
1.21      crook    11029: @section Miscellaneous Words
                   11030: @cindex miscellaneous words
                   11031: 
1.29      crook    11032: @comment TODO find homes for these
                   11033: 
1.26      crook    11034: These section lists the ANS Forth words that are not documented
1.21      crook    11035: elsewhere in this manual. Ultimately, they all need proper homes.
                   11036: 
                   11037: doc-[compile]
                   11038: 
1.44      crook    11039: 
1.26      crook    11040: The following ANS Forth words are not currently supported by Gforth 
1.27      crook    11041: (@pxref{ANS conformance}):
1.21      crook    11042: 
                   11043: @code{EDITOR} 
                   11044: @code{EMIT?} 
                   11045: @code{FORGET} 
                   11046: 
1.24      anton    11047: @c ******************************************************************
                   11048: @node Error messages, Tools, Words, Top
                   11049: @chapter Error messages
                   11050: @cindex error messages
                   11051: @cindex backtrace
                   11052: 
                   11053: A typical Gforth error message looks like this:
                   11054: 
                   11055: @example
                   11056: in file included from :-1
                   11057: in file included from ./yyy.fs:1
                   11058: ./xxx.fs:4: Invalid memory address
                   11059: bar
                   11060: ^^^
1.25      anton    11061: $400E664C @@
                   11062: $400E6664 foo
1.24      anton    11063: @end example
                   11064: 
                   11065: The message identifying the error is @code{Invalid memory address}.  The
                   11066: error happened when text-interpreting line 4 of the file
                   11067: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
                   11068: word on the line where the error happened, is pointed out (with
                   11069: @code{^^^}).
                   11070: 
                   11071: The file containing the error was included in line 1 of @file{./yyy.fs},
                   11072: and @file{yyy.fs} was included from a non-file (in this case, by giving
                   11073: @file{yyy.fs} as command-line parameter to Gforth).
                   11074: 
                   11075: At the end of the error message you find a return stack dump that can be
                   11076: interpreted as a backtrace (possibly empty). On top you find the top of
                   11077: the return stack when the @code{throw} happened, and at the bottom you
                   11078: find the return stack entry just above the return stack of the topmost
                   11079: text interpreter.
                   11080: 
                   11081: To the right of most return stack entries you see a guess for the word
                   11082: that pushed that return stack entry as its return address. This gives a
                   11083: backtrace. In our case we see that @code{bar} called @code{foo}, and
                   11084: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
                   11085: address} exception).
                   11086: 
                   11087: Note that the backtrace is not perfect: We don't know which return stack
                   11088: entries are return addresses (so we may get false positives); and in
                   11089: some cases (e.g., for @code{abort"}) we cannot determine from the return
                   11090: address the word that pushed the return address, so for some return
                   11091: addresses you see no names in the return stack dump.
1.25      anton    11092: 
                   11093: @cindex @code{catch} and backtraces
                   11094: The return stack dump represents the return stack at the time when a
                   11095: specific @code{throw} was executed.  In programs that make use of
                   11096: @code{catch}, it is not necessarily clear which @code{throw} should be
                   11097: used for the return stack dump (e.g., consider one @code{throw} that
                   11098: indicates an error, which is caught, and during recovery another error
1.42      anton    11099: happens; which @code{throw} should be used for the stack dump?).  Gforth
1.25      anton    11100: presents the return stack dump for the first @code{throw} after the last
                   11101: executed (not returned-to) @code{catch}; this works well in the usual
                   11102: case.
                   11103: 
                   11104: @cindex @code{gforth-fast} and backtraces
                   11105: @cindex @code{gforth-fast}, difference from @code{gforth}
                   11106: @cindex backtraces with @code{gforth-fast}
                   11107: @cindex return stack dump with @code{gforth-fast}
                   11108: @code{gforth} is able to do a return stack dump for throws generated
                   11109: from primitives (e.g., invalid memory address, stack empty etc.);
                   11110: @code{gforth-fast} is only able to do a return stack dump from a
                   11111: directly called @code{throw} (including @code{abort} etc.).  This is the
1.30      anton    11112: only difference (apart from a speed factor of between 1.15 (K6-2) and
                   11113: 1.6 (21164A)) between @code{gforth} and @code{gforth-fast}.  Given an
                   11114: exception caused by a primitive in @code{gforth-fast}, you will
                   11115: typically see no return stack dump at all; however, if the exception is
                   11116: caught by @code{catch} (e.g., for restoring some state), and then
                   11117: @code{throw}n again, the return stack dump will be for the first such
                   11118: @code{throw}.
1.2       jwilke   11119: 
1.5       anton    11120: @c ******************************************************************
1.24      anton    11121: @node Tools, ANS conformance, Error messages, Top
1.1       anton    11122: @chapter Tools
                   11123: 
                   11124: @menu
                   11125: * ANS Report::                  Report the words used, sorted by wordset.
                   11126: @end menu
                   11127: 
                   11128: See also @ref{Emacs and Gforth}.
                   11129: 
                   11130: @node ANS Report,  , Tools, Tools
                   11131: @section @file{ans-report.fs}: Report the words used, sorted by wordset
                   11132: @cindex @file{ans-report.fs}
                   11133: @cindex report the words used in your program
                   11134: @cindex words used in your program
                   11135: 
                   11136: If you want to label a Forth program as ANS Forth Program, you must
                   11137: document which wordsets the program uses; for extension wordsets, it is
                   11138: helpful to list the words the program requires from these wordsets
                   11139: (because Forth systems are allowed to provide only some words of them).
                   11140: 
                   11141: The @file{ans-report.fs} tool makes it easy for you to determine which
                   11142: words from which wordset and which non-ANS words your application
                   11143: uses. You simply have to include @file{ans-report.fs} before loading the
                   11144: program you want to check. After loading your program, you can get the
                   11145: report with @code{print-ans-report}. A typical use is to run this as
                   11146: batch job like this:
                   11147: @example
                   11148: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
                   11149: @end example
                   11150: 
                   11151: The output looks like this (for @file{compat/control.fs}):
                   11152: @example
                   11153: The program uses the following words
                   11154: from CORE :
                   11155: : POSTPONE THEN ; immediate ?dup IF 0= 
                   11156: from BLOCK-EXT :
                   11157: \ 
                   11158: from FILE :
                   11159: ( 
                   11160: @end example
                   11161: 
                   11162: @subsection Caveats
                   11163: 
                   11164: Note that @file{ans-report.fs} just checks which words are used, not whether
                   11165: they are used in an ANS Forth conforming way!
                   11166: 
                   11167: Some words are defined in several wordsets in the
                   11168: standard. @file{ans-report.fs} reports them for only one of the
                   11169: wordsets, and not necessarily the one you expect. It depends on usage
                   11170: which wordset is the right one to specify. E.g., if you only use the
                   11171: compilation semantics of @code{S"}, it is a Core word; if you also use
                   11172: its interpretation semantics, it is a File word.
                   11173: 
                   11174: @c ******************************************************************
                   11175: @node ANS conformance, Model, Tools, Top
                   11176: @chapter ANS conformance
                   11177: @cindex ANS conformance of Gforth
                   11178: 
                   11179: To the best of our knowledge, Gforth is an
                   11180: 
                   11181: ANS Forth System
                   11182: @itemize @bullet
                   11183: @item providing the Core Extensions word set
                   11184: @item providing the Block word set
                   11185: @item providing the Block Extensions word set
                   11186: @item providing the Double-Number word set
                   11187: @item providing the Double-Number Extensions word set
                   11188: @item providing the Exception word set
                   11189: @item providing the Exception Extensions word set
                   11190: @item providing the Facility word set
1.40      anton    11191: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1       anton    11192: @item providing the File Access word set
                   11193: @item providing the File Access Extensions word set
                   11194: @item providing the Floating-Point word set
                   11195: @item providing the Floating-Point Extensions word set
                   11196: @item providing the Locals word set
                   11197: @item providing the Locals Extensions word set
                   11198: @item providing the Memory-Allocation word set
                   11199: @item providing the Memory-Allocation Extensions word set (that one's easy)
                   11200: @item providing the Programming-Tools word set
                   11201: @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
                   11202: @item providing the Search-Order word set
                   11203: @item providing the Search-Order Extensions word set
                   11204: @item providing the String word set
                   11205: @item providing the String Extensions word set (another easy one)
                   11206: @end itemize
                   11207: 
                   11208: @cindex system documentation
                   11209: In addition, ANS Forth systems are required to document certain
                   11210: implementation choices. This chapter tries to meet these
                   11211: requirements. In many cases it gives a way to ask the system for the
                   11212: information instead of providing the information directly, in
                   11213: particular, if the information depends on the processor, the operating
                   11214: system or the installation options chosen, or if they are likely to
                   11215: change during the maintenance of Gforth.
                   11216: 
                   11217: @comment The framework for the rest has been taken from pfe.
                   11218: 
                   11219: @menu
                   11220: * The Core Words::              
                   11221: * The optional Block word set::  
                   11222: * The optional Double Number word set::  
                   11223: * The optional Exception word set::  
                   11224: * The optional Facility word set::  
                   11225: * The optional File-Access word set::  
                   11226: * The optional Floating-Point word set::  
                   11227: * The optional Locals word set::  
                   11228: * The optional Memory-Allocation word set::  
                   11229: * The optional Programming-Tools word set::  
                   11230: * The optional Search-Order word set::  
                   11231: @end menu
                   11232: 
                   11233: 
                   11234: @c =====================================================================
                   11235: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
                   11236: @comment  node-name,  next,  previous,  up
                   11237: @section The Core Words
                   11238: @c =====================================================================
                   11239: @cindex core words, system documentation
                   11240: @cindex system documentation, core words
                   11241: 
                   11242: @menu
                   11243: * core-idef::                   Implementation Defined Options                   
                   11244: * core-ambcond::                Ambiguous Conditions                
                   11245: * core-other::                  Other System Documentation                  
                   11246: @end menu
                   11247: 
                   11248: @c ---------------------------------------------------------------------
                   11249: @node core-idef, core-ambcond, The Core Words, The Core Words
                   11250: @subsection Implementation Defined Options
                   11251: @c ---------------------------------------------------------------------
                   11252: @cindex core words, implementation-defined options
                   11253: @cindex implementation-defined options, core words
                   11254: 
                   11255: 
                   11256: @table @i
                   11257: @item (Cell) aligned addresses:
                   11258: @cindex cell-aligned addresses
                   11259: @cindex aligned addresses
                   11260: processor-dependent. Gforth's alignment words perform natural alignment
                   11261: (e.g., an address aligned for a datum of size 8 is divisible by
                   11262: 8). Unaligned accesses usually result in a @code{-23 THROW}.
                   11263: 
                   11264: @item @code{EMIT} and non-graphic characters:
                   11265: @cindex @code{EMIT} and non-graphic characters
                   11266: @cindex non-graphic characters and @code{EMIT}
                   11267: The character is output using the C library function (actually, macro)
                   11268: @code{putc}.
                   11269: 
                   11270: @item character editing of @code{ACCEPT} and @code{EXPECT}:
                   11271: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
                   11272: @cindex editing in @code{ACCEPT} and @code{EXPECT}
                   11273: @cindex @code{ACCEPT}, editing
                   11274: @cindex @code{EXPECT}, editing
                   11275: This is modeled on the GNU readline library (@pxref{Readline
                   11276: Interaction, , Command Line Editing, readline, The GNU Readline
                   11277: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
                   11278: producing a full word completion every time you type it (instead of
1.28      crook    11279: producing the common prefix of all completions). @xref{Command-line editing}.
1.1       anton    11280: 
                   11281: @item character set:
                   11282: @cindex character set
                   11283: The character set of your computer and display device. Gforth is
                   11284: 8-bit-clean (but some other component in your system may make trouble).
                   11285: 
                   11286: @item Character-aligned address requirements:
                   11287: @cindex character-aligned address requirements
                   11288: installation-dependent. Currently a character is represented by a C
                   11289: @code{unsigned char}; in the future we might switch to @code{wchar_t}
                   11290: (Comments on that requested).
                   11291: 
                   11292: @item character-set extensions and matching of names:
                   11293: @cindex character-set extensions and matching of names
1.26      crook    11294: @cindex case-sensitivity for name lookup
                   11295: @cindex name lookup, case-sensitivity
                   11296: @cindex locale and case-sensitivity
1.21      crook    11297: Any character except the ASCII NUL character can be used in a
1.1       anton    11298: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47      crook    11299: matching is performed using the C library function @code{strncasecmp}, whose
1.1       anton    11300: function is probably influenced by the locale. E.g., the @code{C} locale
                   11301: does not know about accents and umlauts, so they are matched
                   11302: case-sensitively in that locale. For portability reasons it is best to
                   11303: write programs such that they work in the @code{C} locale. Then one can
                   11304: use libraries written by a Polish programmer (who might use words
                   11305: containing ISO Latin-2 encoded characters) and by a French programmer
                   11306: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
                   11307: funny results for some of the words (which ones, depends on the font you
                   11308: are using)). Also, the locale you prefer may not be available in other
                   11309: operating systems. Hopefully, Unicode will solve these problems one day.
                   11310: 
                   11311: @item conditions under which control characters match a space delimiter:
                   11312: @cindex space delimiters
                   11313: @cindex control characters as delimiters
                   11314: If @code{WORD} is called with the space character as a delimiter, all
                   11315: white-space characters (as identified by the C macro @code{isspace()})
                   11316: are delimiters. @code{PARSE}, on the other hand, treats space like other
1.44      crook    11317: delimiters. @code{SWORD} treats space like @code{WORD}, but behaves
1.1       anton    11318: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
                   11319: interpreter (aka text interpreter) by default, treats all white-space
                   11320: characters as delimiters.
                   11321: 
1.26      crook    11322: @item format of the control-flow stack:
                   11323: @cindex control-flow stack, format
                   11324: The data stack is used as control-flow stack. The size of a control-flow
1.1       anton    11325: stack item in cells is given by the constant @code{cs-item-size}. At the
                   11326: time of this writing, an item consists of a (pointer to a) locals list
                   11327: (third), an address in the code (second), and a tag for identifying the
                   11328: item (TOS). The following tags are used: @code{defstart},
                   11329: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
                   11330: @code{scopestart}.
                   11331: 
                   11332: @item conversion of digits > 35
                   11333: @cindex digits > 35
                   11334: The characters @code{[\]^_'} are the digits with the decimal value
                   11335: 36@minus{}41. There is no way to input many of the larger digits.
                   11336: 
                   11337: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
                   11338: @cindex @code{EXPECT}, display after end of input
                   11339: @cindex @code{ACCEPT}, display after end of input
                   11340: The cursor is moved to the end of the entered string. If the input is
                   11341: terminated using the @kbd{Return} key, a space is typed.
                   11342: 
                   11343: @item exception abort sequence of @code{ABORT"}:
                   11344: @cindex exception abort sequence of @code{ABORT"}
                   11345: @cindex @code{ABORT"}, exception abort sequence
                   11346: The error string is stored into the variable @code{"error} and a
                   11347: @code{-2 throw} is performed.
                   11348: 
                   11349: @item input line terminator:
                   11350: @cindex input line terminator
                   11351: @cindex line terminator on input
1.26      crook    11352: @cindex newline character on input
1.1       anton    11353: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
                   11354: lines. One of these characters is typically produced when you type the
                   11355: @kbd{Enter} or @kbd{Return} key.
                   11356: 
                   11357: @item maximum size of a counted string:
                   11358: @cindex maximum size of a counted string
                   11359: @cindex counted string, maximum size
                   11360: @code{s" /counted-string" environment? drop .}. Currently 255 characters
                   11361: on all ports, but this may change.
                   11362: 
                   11363: @item maximum size of a parsed string:
                   11364: @cindex maximum size of a parsed string
                   11365: @cindex parsed string, maximum size
                   11366: Given by the constant @code{/line}. Currently 255 characters.
                   11367: 
                   11368: @item maximum size of a definition name, in characters:
                   11369: @cindex maximum size of a definition name, in characters
                   11370: @cindex name, maximum length
                   11371: 31
                   11372: 
                   11373: @item maximum string length for @code{ENVIRONMENT?}, in characters:
                   11374: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
                   11375: @cindex @code{ENVIRONMENT?} string length, maximum
                   11376: 31
                   11377: 
                   11378: @item method of selecting the user input device:
                   11379: @cindex user input device, method of selecting
                   11380: The user input device is the standard input. There is currently no way to
                   11381: change it from within Gforth. However, the input can typically be
                   11382: redirected in the command line that starts Gforth.
                   11383: 
                   11384: @item method of selecting the user output device:
                   11385: @cindex user output device, method of selecting
                   11386: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10      anton    11387: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
                   11388: output when the user output device is a terminal, otherwise the output
                   11389: is buffered.
1.1       anton    11390: 
                   11391: @item methods of dictionary compilation:
                   11392: What are we expected to document here?
                   11393: 
                   11394: @item number of bits in one address unit:
                   11395: @cindex number of bits in one address unit
                   11396: @cindex address unit, size in bits
                   11397: @code{s" address-units-bits" environment? drop .}. 8 in all current
                   11398: ports.
                   11399: 
                   11400: @item number representation and arithmetic:
                   11401: @cindex number representation and arithmetic
                   11402: Processor-dependent. Binary two's complement on all current ports.
                   11403: 
                   11404: @item ranges for integer types:
                   11405: @cindex ranges for integer types
                   11406: @cindex integer types, ranges
                   11407: Installation-dependent. Make environmental queries for @code{MAX-N},
                   11408: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
                   11409: unsigned (and positive) types is 0. The lower bound for signed types on
                   11410: two's complement and one's complement machines machines can be computed
                   11411: by adding 1 to the upper bound.
                   11412: 
                   11413: @item read-only data space regions:
                   11414: @cindex read-only data space regions
                   11415: @cindex data-space, read-only regions
                   11416: The whole Forth data space is writable.
                   11417: 
                   11418: @item size of buffer at @code{WORD}:
                   11419: @cindex size of buffer at @code{WORD}
                   11420: @cindex @code{WORD} buffer size
                   11421: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   11422: shared with the pictured numeric output string. If overwriting
                   11423: @code{PAD} is acceptable, it is as large as the remaining dictionary
                   11424: space, although only as much can be sensibly used as fits in a counted
                   11425: string.
                   11426: 
                   11427: @item size of one cell in address units:
                   11428: @cindex cell size
                   11429: @code{1 cells .}.
                   11430: 
                   11431: @item size of one character in address units:
                   11432: @cindex char size
                   11433: @code{1 chars .}. 1 on all current ports.
                   11434: 
                   11435: @item size of the keyboard terminal buffer:
                   11436: @cindex size of the keyboard terminal buffer
                   11437: @cindex terminal buffer, size
                   11438: Varies. You can determine the size at a specific time using @code{lp@@
                   11439: tib - .}. It is shared with the locals stack and TIBs of files that
                   11440: include the current file. You can change the amount of space for TIBs
                   11441: and locals stack at Gforth startup with the command line option
                   11442: @code{-l}.
                   11443: 
                   11444: @item size of the pictured numeric output buffer:
                   11445: @cindex size of the pictured numeric output buffer
                   11446: @cindex pictured numeric output buffer, size
                   11447: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   11448: shared with @code{WORD}.
                   11449: 
                   11450: @item size of the scratch area returned by @code{PAD}:
                   11451: @cindex size of the scratch area returned by @code{PAD}
                   11452: @cindex @code{PAD} size
                   11453: The remainder of dictionary space. @code{unused pad here - - .}.
                   11454: 
                   11455: @item system case-sensitivity characteristics:
                   11456: @cindex case-sensitivity characteristics
1.26      crook    11457: Dictionary searches are case-insensitive (except in
1.1       anton    11458: @code{TABLE}s). However, as explained above under @i{character-set
                   11459: extensions}, the matching for non-ASCII characters is determined by the
                   11460: locale you are using. In the default @code{C} locale all non-ASCII
                   11461: characters are matched case-sensitively.
                   11462: 
                   11463: @item system prompt:
                   11464: @cindex system prompt
                   11465: @cindex prompt
                   11466: @code{ ok} in interpret state, @code{ compiled} in compile state.
                   11467: 
                   11468: @item division rounding:
                   11469: @cindex division rounding
                   11470: installation dependent. @code{s" floored" environment? drop .}. We leave
                   11471: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
                   11472: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
                   11473: 
                   11474: @item values of @code{STATE} when true:
                   11475: @cindex @code{STATE} values
                   11476: -1.
                   11477: 
                   11478: @item values returned after arithmetic overflow:
                   11479: On two's complement machines, arithmetic is performed modulo
                   11480: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   11481: arithmetic (with appropriate mapping for signed types). Division by zero
                   11482: typically results in a @code{-55 throw} (Floating-point unidentified
                   11483: fault), although a @code{-10 throw} (divide by zero) would be more
                   11484: appropriate.
                   11485: 
                   11486: @item whether the current definition can be found after @t{DOES>}:
                   11487: @cindex @t{DOES>}, visibility of current definition
                   11488: No.
                   11489: 
                   11490: @end table
                   11491: 
                   11492: @c ---------------------------------------------------------------------
                   11493: @node core-ambcond, core-other, core-idef, The Core Words
                   11494: @subsection Ambiguous conditions
                   11495: @c ---------------------------------------------------------------------
                   11496: @cindex core words, ambiguous conditions
                   11497: @cindex ambiguous conditions, core words
                   11498: 
                   11499: @table @i
                   11500: 
                   11501: @item a name is neither a word nor a number:
                   11502: @cindex name not found
1.26      crook    11503: @cindex undefined word
1.1       anton    11504: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
                   11505: preserves the data and FP stack, so you don't lose more work than
                   11506: necessary.
                   11507: 
                   11508: @item a definition name exceeds the maximum length allowed:
1.26      crook    11509: @cindex word name too long
1.1       anton    11510: @code{-19 throw} (Word name too long)
                   11511: 
                   11512: @item addressing a region not inside the various data spaces of the forth system:
                   11513: @cindex Invalid memory address
1.32      anton    11514: The stacks, code space and header space are accessible. Machine code space is
1.1       anton    11515: typically readable. Accessing other addresses gives results dependent on
                   11516: the operating system. On decent systems: @code{-9 throw} (Invalid memory
                   11517: address).
                   11518: 
                   11519: @item argument type incompatible with parameter:
1.26      crook    11520: @cindex argument type mismatch
1.1       anton    11521: This is usually not caught. Some words perform checks, e.g., the control
                   11522: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
                   11523: mismatch).
                   11524: 
                   11525: @item attempting to obtain the execution token of a word with undefined execution semantics:
                   11526: @cindex Interpreting a compile-only word, for @code{'} etc.
                   11527: @cindex execution token of words with undefined execution semantics
                   11528: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
                   11529: get an execution token for @code{compile-only-error} (which performs a
                   11530: @code{-14 throw} when executed).
                   11531: 
                   11532: @item dividing by zero:
                   11533: @cindex dividing by zero
                   11534: @cindex floating point unidentified fault, integer division
1.24      anton    11535: On better platforms, this produces a @code{-10 throw} (Division by
                   11536: zero); on other systems, this typically results in a @code{-55 throw}
                   11537: (Floating-point unidentified fault).
1.1       anton    11538: 
                   11539: @item insufficient data stack or return stack space:
                   11540: @cindex insufficient data stack or return stack space
                   11541: @cindex stack overflow
1.26      crook    11542: @cindex address alignment exception, stack overflow
1.1       anton    11543: @cindex Invalid memory address, stack overflow
                   11544: Depending on the operating system, the installation, and the invocation
                   11545: of Gforth, this is either checked by the memory management hardware, or
1.24      anton    11546: it is not checked. If it is checked, you typically get a @code{-3 throw}
                   11547: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
                   11548: throw} (Invalid memory address) (depending on the platform and how you
                   11549: achieved the overflow) as soon as the overflow happens. If it is not
                   11550: checked, overflows typically result in mysterious illegal memory
                   11551: accesses, producing @code{-9 throw} (Invalid memory address) or
                   11552: @code{-23 throw} (Address alignment exception); they might also destroy
                   11553: the internal data structure of @code{ALLOCATE} and friends, resulting in
                   11554: various errors in these words.
1.1       anton    11555: 
                   11556: @item insufficient space for loop control parameters:
                   11557: @cindex insufficient space for loop control parameters
                   11558: like other return stack overflows.
                   11559: 
                   11560: @item insufficient space in the dictionary:
                   11561: @cindex insufficient space in the dictionary
                   11562: @cindex dictionary overflow
1.12      anton    11563: If you try to allot (either directly with @code{allot}, or indirectly
                   11564: with @code{,}, @code{create} etc.) more memory than available in the
                   11565: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
                   11566: to access memory beyond the end of the dictionary, the results are
                   11567: similar to stack overflows.
1.1       anton    11568: 
                   11569: @item interpreting a word with undefined interpretation semantics:
                   11570: @cindex interpreting a word with undefined interpretation semantics
                   11571: @cindex Interpreting a compile-only word
                   11572: For some words, we have defined interpretation semantics. For the
                   11573: others: @code{-14 throw} (Interpreting a compile-only word).
                   11574: 
                   11575: @item modifying the contents of the input buffer or a string literal:
                   11576: @cindex modifying the contents of the input buffer or a string literal
                   11577: These are located in writable memory and can be modified.
                   11578: 
                   11579: @item overflow of the pictured numeric output string:
                   11580: @cindex overflow of the pictured numeric output string
                   11581: @cindex pictured numeric output string, overflow
1.24      anton    11582: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1       anton    11583: 
                   11584: @item parsed string overflow:
                   11585: @cindex parsed string overflow
                   11586: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
                   11587: 
                   11588: @item producing a result out of range:
                   11589: @cindex result out of range
                   11590: On two's complement machines, arithmetic is performed modulo
                   11591: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   11592: arithmetic (with appropriate mapping for signed types). Division by zero
1.24      anton    11593: typically results in a @code{-10 throw} (divide by zero) or @code{-55
                   11594: throw} (floating point unidentified fault). @code{convert} and
                   11595: @code{>number} currently overflow silently.
1.1       anton    11596: 
                   11597: @item reading from an empty data or return stack:
                   11598: @cindex stack empty
                   11599: @cindex stack underflow
1.24      anton    11600: @cindex return stack underflow
1.1       anton    11601: The data stack is checked by the outer (aka text) interpreter after
                   11602: every word executed. If it has underflowed, a @code{-4 throw} (Stack
                   11603: underflow) is performed. Apart from that, stacks may be checked or not,
1.24      anton    11604: depending on operating system, installation, and invocation. If they are
                   11605: caught by a check, they typically result in @code{-4 throw} (Stack
                   11606: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
                   11607: (Invalid memory address), depending on the platform and which stack
                   11608: underflows and by how much. Note that even if the system uses checking
                   11609: (through the MMU), your program may have to underflow by a significant
                   11610: number of stack items to trigger the reaction (the reason for this is
                   11611: that the MMU, and therefore the checking, works with a page-size
                   11612: granularity).  If there is no checking, the symptoms resulting from an
                   11613: underflow are similar to those from an overflow.  Unbalanced return
                   11614: stack errors result in a variaty of symptoms, including @code{-9 throw}
                   11615: (Invalid memory address) and Illegal Instruction (typically @code{-260
                   11616: throw}).
1.1       anton    11617: 
                   11618: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
                   11619: @cindex unexpected end of the input buffer
                   11620: @cindex zero-length string as a name
                   11621: @cindex Attempt to use zero-length string as a name
                   11622: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
                   11623: use zero-length string as a name). Words like @code{'} probably will not
                   11624: find what they search. Note that it is possible to create zero-length
                   11625: names with @code{nextname} (should it not?).
                   11626: 
                   11627: @item @code{>IN} greater than input buffer:
                   11628: @cindex @code{>IN} greater than input buffer
                   11629: The next invocation of a parsing word returns a string with length 0.
                   11630: 
                   11631: @item @code{RECURSE} appears after @code{DOES>}:
                   11632: @cindex @code{RECURSE} appears after @code{DOES>}
                   11633: Compiles a recursive call to the defining word, not to the defined word.
                   11634: 
                   11635: @item argument input source different than current input source for @code{RESTORE-INPUT}:
                   11636: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26      crook    11637: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1       anton    11638: @cindex @code{RESTORE-INPUT}, Argument type mismatch
                   11639: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
                   11640: the end of the file was reached), its source-id may be
                   11641: reused. Therefore, restoring an input source specification referencing a
                   11642: closed file may lead to unpredictable results instead of a @code{-12
                   11643: THROW}.
                   11644: 
                   11645: In the future, Gforth may be able to restore input source specifications
                   11646: from other than the current input source.
                   11647: 
                   11648: @item data space containing definitions gets de-allocated:
                   11649: @cindex data space containing definitions gets de-allocated
                   11650: Deallocation with @code{allot} is not checked. This typically results in
                   11651: memory access faults or execution of illegal instructions.
                   11652: 
                   11653: @item data space read/write with incorrect alignment:
                   11654: @cindex data space read/write with incorrect alignment
                   11655: @cindex alignment faults
1.26      crook    11656: @cindex address alignment exception
1.1       anton    11657: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12      anton    11658: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1       anton    11659: alignment turned on, incorrect alignment results in a @code{-9 throw}
                   11660: (Invalid memory address). There are reportedly some processors with
1.12      anton    11661: alignment restrictions that do not report violations.
1.1       anton    11662: 
                   11663: @item data space pointer not properly aligned, @code{,}, @code{C,}:
                   11664: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
                   11665: Like other alignment errors.
                   11666: 
                   11667: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
                   11668: Like other stack underflows.
                   11669: 
                   11670: @item loop control parameters not available:
                   11671: @cindex loop control parameters not available
                   11672: Not checked. The counted loop words simply assume that the top of return
                   11673: stack items are loop control parameters and behave accordingly.
                   11674: 
                   11675: @item most recent definition does not have a name (@code{IMMEDIATE}):
                   11676: @cindex most recent definition does not have a name (@code{IMMEDIATE})
                   11677: @cindex last word was headerless
                   11678: @code{abort" last word was headerless"}.
                   11679: 
                   11680: @item name not defined by @code{VALUE} used by @code{TO}:
                   11681: @cindex name not defined by @code{VALUE} used by @code{TO}
                   11682: @cindex @code{TO} on non-@code{VALUE}s
                   11683: @cindex Invalid name argument, @code{TO}
                   11684: @code{-32 throw} (Invalid name argument) (unless name is a local or was
                   11685: defined by @code{CONSTANT}; in the latter case it just changes the constant).
                   11686: 
                   11687: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
                   11688: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26      crook    11689: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1       anton    11690: @code{-13 throw} (Undefined word)
                   11691: 
                   11692: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
                   11693: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
                   11694: Gforth behaves as if they were of the same type. I.e., you can predict
                   11695: the behaviour by interpreting all parameters as, e.g., signed.
                   11696: 
                   11697: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
                   11698: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
                   11699: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
                   11700: compilation semantics of @code{TO}.
                   11701: 
                   11702: @item String longer than a counted string returned by @code{WORD}:
1.26      crook    11703: @cindex string longer than a counted string returned by @code{WORD}
1.1       anton    11704: @cindex @code{WORD}, string overflow
                   11705: Not checked. The string will be ok, but the count will, of course,
                   11706: contain only the least significant bits of the length.
                   11707: 
                   11708: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
                   11709: @cindex @code{LSHIFT}, large shift counts
                   11710: @cindex @code{RSHIFT}, large shift counts
                   11711: Processor-dependent. Typical behaviours are returning 0 and using only
                   11712: the low bits of the shift count.
                   11713: 
                   11714: @item word not defined via @code{CREATE}:
                   11715: @cindex @code{>BODY} of non-@code{CREATE}d words
                   11716: @code{>BODY} produces the PFA of the word no matter how it was defined.
                   11717: 
                   11718: @cindex @code{DOES>} of non-@code{CREATE}d words
                   11719: @code{DOES>} changes the execution semantics of the last defined word no
                   11720: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
                   11721: @code{CREATE , DOES>}.
                   11722: 
                   11723: @item words improperly used outside @code{<#} and @code{#>}:
                   11724: Not checked. As usual, you can expect memory faults.
                   11725: 
                   11726: @end table
                   11727: 
                   11728: 
                   11729: @c ---------------------------------------------------------------------
                   11730: @node core-other,  , core-ambcond, The Core Words
                   11731: @subsection Other system documentation
                   11732: @c ---------------------------------------------------------------------
                   11733: @cindex other system documentation, core words
                   11734: @cindex core words, other system documentation
                   11735: 
                   11736: @table @i
                   11737: @item nonstandard words using @code{PAD}:
                   11738: @cindex @code{PAD} use by nonstandard words
                   11739: None.
                   11740: 
                   11741: @item operator's terminal facilities available:
                   11742: @cindex operator's terminal facilities available
                   11743: After processing the command line, Gforth goes into interactive mode,
                   11744: and you can give commands to Gforth interactively. The actual facilities
                   11745: available depend on how you invoke Gforth.
                   11746: 
                   11747: @item program data space available:
                   11748: @cindex program data space available
                   11749: @cindex data space available
                   11750: @code{UNUSED .} gives the remaining dictionary space. The total
                   11751: dictionary space can be specified with the @code{-m} switch
                   11752: (@pxref{Invoking Gforth}) when Gforth starts up.
                   11753: 
                   11754: @item return stack space available:
                   11755: @cindex return stack space available
                   11756: You can compute the total return stack space in cells with
                   11757: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
                   11758: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
                   11759: 
                   11760: @item stack space available:
                   11761: @cindex stack space available
                   11762: You can compute the total data stack space in cells with
                   11763: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
                   11764: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
                   11765: 
                   11766: @item system dictionary space required, in address units:
                   11767: @cindex system dictionary space required, in address units
                   11768: Type @code{here forthstart - .} after startup. At the time of this
                   11769: writing, this gives 80080 (bytes) on a 32-bit system.
                   11770: @end table
                   11771: 
                   11772: 
                   11773: @c =====================================================================
                   11774: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
                   11775: @section The optional Block word set
                   11776: @c =====================================================================
                   11777: @cindex system documentation, block words
                   11778: @cindex block words, system documentation
                   11779: 
                   11780: @menu
                   11781: * block-idef::                  Implementation Defined Options
                   11782: * block-ambcond::               Ambiguous Conditions               
                   11783: * block-other::                 Other System Documentation                 
                   11784: @end menu
                   11785: 
                   11786: 
                   11787: @c ---------------------------------------------------------------------
                   11788: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
                   11789: @subsection Implementation Defined Options
                   11790: @c ---------------------------------------------------------------------
                   11791: @cindex implementation-defined options, block words
                   11792: @cindex block words, implementation-defined options
                   11793: 
                   11794: @table @i
                   11795: @item the format for display by @code{LIST}:
                   11796: @cindex @code{LIST} display format
                   11797: First the screen number is displayed, then 16 lines of 64 characters,
                   11798: each line preceded by the line number.
                   11799: 
                   11800: @item the length of a line affected by @code{\}:
                   11801: @cindex length of a line affected by @code{\}
                   11802: @cindex @code{\}, line length in blocks
                   11803: 64 characters.
                   11804: @end table
                   11805: 
                   11806: 
                   11807: @c ---------------------------------------------------------------------
                   11808: @node block-ambcond, block-other, block-idef, The optional Block word set
                   11809: @subsection Ambiguous conditions
                   11810: @c ---------------------------------------------------------------------
                   11811: @cindex block words, ambiguous conditions
                   11812: @cindex ambiguous conditions, block words
                   11813: 
                   11814: @table @i
                   11815: @item correct block read was not possible:
                   11816: @cindex block read not possible
                   11817: Typically results in a @code{throw} of some OS-derived value (between
                   11818: -512 and -2048). If the blocks file was just not long enough, blanks are
                   11819: supplied for the missing portion.
                   11820: 
                   11821: @item I/O exception in block transfer:
                   11822: @cindex I/O exception in block transfer
                   11823: @cindex block transfer, I/O exception
                   11824: Typically results in a @code{throw} of some OS-derived value (between
                   11825: -512 and -2048).
                   11826: 
                   11827: @item invalid block number:
                   11828: @cindex invalid block number
                   11829: @cindex block number invalid
                   11830: @code{-35 throw} (Invalid block number)
                   11831: 
                   11832: @item a program directly alters the contents of @code{BLK}:
                   11833: @cindex @code{BLK}, altering @code{BLK}
                   11834: The input stream is switched to that other block, at the same
                   11835: position. If the storing to @code{BLK} happens when interpreting
                   11836: non-block input, the system will get quite confused when the block ends.
                   11837: 
                   11838: @item no current block buffer for @code{UPDATE}:
                   11839: @cindex @code{UPDATE}, no current block buffer
                   11840: @code{UPDATE} has no effect.
                   11841: 
                   11842: @end table
                   11843: 
                   11844: @c ---------------------------------------------------------------------
                   11845: @node block-other,  , block-ambcond, The optional Block word set
                   11846: @subsection Other system documentation
                   11847: @c ---------------------------------------------------------------------
                   11848: @cindex other system documentation, block words
                   11849: @cindex block words, other system documentation
                   11850: 
                   11851: @table @i
                   11852: @item any restrictions a multiprogramming system places on the use of buffer addresses:
                   11853: No restrictions (yet).
                   11854: 
                   11855: @item the number of blocks available for source and data:
                   11856: depends on your disk space.
                   11857: 
                   11858: @end table
                   11859: 
                   11860: 
                   11861: @c =====================================================================
                   11862: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
                   11863: @section The optional Double Number word set
                   11864: @c =====================================================================
                   11865: @cindex system documentation, double words
                   11866: @cindex double words, system documentation
                   11867: 
                   11868: @menu
                   11869: * double-ambcond::              Ambiguous Conditions              
                   11870: @end menu
                   11871: 
                   11872: 
                   11873: @c ---------------------------------------------------------------------
                   11874: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
                   11875: @subsection Ambiguous conditions
                   11876: @c ---------------------------------------------------------------------
                   11877: @cindex double words, ambiguous conditions
                   11878: @cindex ambiguous conditions, double words
                   11879: 
                   11880: @table @i
1.29      crook    11881: @item @i{d} outside of range of @i{n} in @code{D>S}:
                   11882: @cindex @code{D>S}, @i{d} out of range of @i{n} 
                   11883: The least significant cell of @i{d} is produced.
1.1       anton    11884: 
                   11885: @end table
                   11886: 
                   11887: 
                   11888: @c =====================================================================
                   11889: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
                   11890: @section The optional Exception word set
                   11891: @c =====================================================================
                   11892: @cindex system documentation, exception words
                   11893: @cindex exception words, system documentation
                   11894: 
                   11895: @menu
                   11896: * exception-idef::              Implementation Defined Options              
                   11897: @end menu
                   11898: 
                   11899: 
                   11900: @c ---------------------------------------------------------------------
                   11901: @node exception-idef,  , The optional Exception word set, The optional Exception word set
                   11902: @subsection Implementation Defined Options
                   11903: @c ---------------------------------------------------------------------
                   11904: @cindex implementation-defined options, exception words
                   11905: @cindex exception words, implementation-defined options
                   11906: 
                   11907: @table @i
                   11908: @item @code{THROW}-codes used in the system:
                   11909: @cindex @code{THROW}-codes used in the system
                   11910: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29      crook    11911: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1       anton    11912: codes -512@minus{}-2047 are used for OS errors (for file and memory
                   11913: allocation operations). The mapping from OS error numbers to throw codes
                   11914: is -512@minus{}@code{errno}. One side effect of this mapping is that
                   11915: undefined OS errors produce a message with a strange number; e.g.,
                   11916: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
                   11917: @end table
                   11918: 
                   11919: @c =====================================================================
                   11920: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
                   11921: @section The optional Facility word set
                   11922: @c =====================================================================
                   11923: @cindex system documentation, facility words
                   11924: @cindex facility words, system documentation
                   11925: 
                   11926: @menu
                   11927: * facility-idef::               Implementation Defined Options               
                   11928: * facility-ambcond::            Ambiguous Conditions            
                   11929: @end menu
                   11930: 
                   11931: 
                   11932: @c ---------------------------------------------------------------------
                   11933: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
                   11934: @subsection Implementation Defined Options
                   11935: @c ---------------------------------------------------------------------
                   11936: @cindex implementation-defined options, facility words
                   11937: @cindex facility words, implementation-defined options
                   11938: 
                   11939: @table @i
                   11940: @item encoding of keyboard events (@code{EKEY}):
                   11941: @cindex keyboard events, encoding in @code{EKEY}
                   11942: @cindex @code{EKEY}, encoding of keyboard events
1.40      anton    11943: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41      anton    11944: Other keys are encoded with the constants @code{k-left}, @code{k-right},
                   11945: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
                   11946: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
                   11947: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40      anton    11948: 
1.1       anton    11949: 
                   11950: @item duration of a system clock tick:
                   11951: @cindex duration of a system clock tick
                   11952: @cindex clock tick duration
                   11953: System dependent. With respect to @code{MS}, the time is specified in
                   11954: microseconds. How well the OS and the hardware implement this, is
                   11955: another question.
                   11956: 
                   11957: @item repeatability to be expected from the execution of @code{MS}:
                   11958: @cindex repeatability to be expected from the execution of @code{MS}
                   11959: @cindex @code{MS}, repeatability to be expected
                   11960: System dependent. On Unix, a lot depends on load. If the system is
                   11961: lightly loaded, and the delay is short enough that Gforth does not get
                   11962: swapped out, the performance should be acceptable. Under MS-DOS and
                   11963: other single-tasking systems, it should be good.
                   11964: 
                   11965: @end table
                   11966: 
                   11967: 
                   11968: @c ---------------------------------------------------------------------
                   11969: @node facility-ambcond,  , facility-idef, The optional Facility word set
                   11970: @subsection Ambiguous conditions
                   11971: @c ---------------------------------------------------------------------
                   11972: @cindex facility words, ambiguous conditions
                   11973: @cindex ambiguous conditions, facility words
                   11974: 
                   11975: @table @i
                   11976: @item @code{AT-XY} can't be performed on user output device:
                   11977: @cindex @code{AT-XY} can't be performed on user output device
                   11978: Largely terminal dependent. No range checks are done on the arguments.
                   11979: No errors are reported. You may see some garbage appearing, you may see
                   11980: simply nothing happen.
                   11981: 
                   11982: @end table
                   11983: 
                   11984: 
                   11985: @c =====================================================================
                   11986: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
                   11987: @section The optional File-Access word set
                   11988: @c =====================================================================
                   11989: @cindex system documentation, file words
                   11990: @cindex file words, system documentation
                   11991: 
                   11992: @menu
                   11993: * file-idef::                   Implementation Defined Options
                   11994: * file-ambcond::                Ambiguous Conditions                
                   11995: @end menu
                   11996: 
                   11997: @c ---------------------------------------------------------------------
                   11998: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
                   11999: @subsection Implementation Defined Options
                   12000: @c ---------------------------------------------------------------------
                   12001: @cindex implementation-defined options, file words
                   12002: @cindex file words, implementation-defined options
                   12003: 
                   12004: @table @i
                   12005: @item file access methods used:
                   12006: @cindex file access methods used
                   12007: @code{R/O}, @code{R/W} and @code{BIN} work as you would
                   12008: expect. @code{W/O} translates into the C file opening mode @code{w} (or
                   12009: @code{wb}): The file is cleared, if it exists, and created, if it does
                   12010: not (with both @code{open-file} and @code{create-file}).  Under Unix
                   12011: @code{create-file} creates a file with 666 permissions modified by your
                   12012: umask.
                   12013: 
                   12014: @item file exceptions:
                   12015: @cindex file exceptions
                   12016: The file words do not raise exceptions (except, perhaps, memory access
                   12017: faults when you pass illegal addresses or file-ids).
                   12018: 
                   12019: @item file line terminator:
                   12020: @cindex file line terminator
                   12021: System-dependent. Gforth uses C's newline character as line
                   12022: terminator. What the actual character code(s) of this are is
                   12023: system-dependent.
                   12024: 
                   12025: @item file name format:
                   12026: @cindex file name format
                   12027: System dependent. Gforth just uses the file name format of your OS.
                   12028: 
                   12029: @item information returned by @code{FILE-STATUS}:
                   12030: @cindex @code{FILE-STATUS}, returned information
                   12031: @code{FILE-STATUS} returns the most powerful file access mode allowed
                   12032: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
                   12033: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
                   12034: along with the returned mode.
                   12035: 
                   12036: @item input file state after an exception when including source:
                   12037: @cindex exception when including source
                   12038: All files that are left via the exception are closed.
                   12039: 
1.29      crook    12040: @item @i{ior} values and meaning:
                   12041: @cindex @i{ior} values and meaning
                   12042: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    12043: intended as throw codes. They typically are in the range
                   12044: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    12045: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    12046: 
                   12047: @item maximum depth of file input nesting:
                   12048: @cindex maximum depth of file input nesting
                   12049: @cindex file input nesting, maximum depth
                   12050: limited by the amount of return stack, locals/TIB stack, and the number
                   12051: of open files available. This should not give you troubles.
                   12052: 
                   12053: @item maximum size of input line:
                   12054: @cindex maximum size of input line
                   12055: @cindex input line size, maximum
                   12056: @code{/line}. Currently 255.
                   12057: 
                   12058: @item methods of mapping block ranges to files:
                   12059: @cindex mapping block ranges to files
                   12060: @cindex files containing blocks
                   12061: @cindex blocks in files
                   12062: By default, blocks are accessed in the file @file{blocks.fb} in the
                   12063: current working directory. The file can be switched with @code{USE}.
                   12064: 
                   12065: @item number of string buffers provided by @code{S"}:
                   12066: @cindex @code{S"}, number of string buffers
                   12067: 1
                   12068: 
                   12069: @item size of string buffer used by @code{S"}:
                   12070: @cindex @code{S"}, size of string buffer
                   12071: @code{/line}. currently 255.
                   12072: 
                   12073: @end table
                   12074: 
                   12075: @c ---------------------------------------------------------------------
                   12076: @node file-ambcond,  , file-idef, The optional File-Access word set
                   12077: @subsection Ambiguous conditions
                   12078: @c ---------------------------------------------------------------------
                   12079: @cindex file words, ambiguous conditions
                   12080: @cindex ambiguous conditions, file words
                   12081: 
                   12082: @table @i
                   12083: @item attempting to position a file outside its boundaries:
                   12084: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
                   12085: @code{REPOSITION-FILE} is performed as usual: Afterwards,
                   12086: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
                   12087: 
                   12088: @item attempting to read from file positions not yet written:
                   12089: @cindex reading from file positions not yet written
                   12090: End-of-file, i.e., zero characters are read and no error is reported.
                   12091: 
1.29      crook    12092: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
                   12093: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
1.1       anton    12094: An appropriate exception may be thrown, but a memory fault or other
                   12095: problem is more probable.
                   12096: 
1.29      crook    12097: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
                   12098: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
                   12099: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
                   12100: The @i{ior} produced by the operation, that discovered the problem, is
1.1       anton    12101: thrown.
                   12102: 
                   12103: @item named file cannot be opened (@code{INCLUDED}):
                   12104: @cindex @code{INCLUDED}, named file cannot be opened
1.29      crook    12105: The @i{ior} produced by @code{open-file} is thrown.
1.1       anton    12106: 
                   12107: @item requesting an unmapped block number:
                   12108: @cindex unmapped block numbers
                   12109: There are no unmapped legal block numbers. On some operating systems,
                   12110: writing a block with a large number may overflow the file system and
                   12111: have an error message as consequence.
                   12112: 
                   12113: @item using @code{source-id} when @code{blk} is non-zero:
                   12114: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
                   12115: @code{source-id} performs its function. Typically it will give the id of
                   12116: the source which loaded the block. (Better ideas?)
                   12117: 
                   12118: @end table
                   12119: 
                   12120: 
                   12121: @c =====================================================================
                   12122: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
                   12123: @section The optional Floating-Point word set
                   12124: @c =====================================================================
                   12125: @cindex system documentation, floating-point words
                   12126: @cindex floating-point words, system documentation
                   12127: 
                   12128: @menu
                   12129: * floating-idef::               Implementation Defined Options
                   12130: * floating-ambcond::            Ambiguous Conditions            
                   12131: @end menu
                   12132: 
                   12133: 
                   12134: @c ---------------------------------------------------------------------
                   12135: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
                   12136: @subsection Implementation Defined Options
                   12137: @c ---------------------------------------------------------------------
                   12138: @cindex implementation-defined options, floating-point words
                   12139: @cindex floating-point words, implementation-defined options
                   12140: 
                   12141: @table @i
                   12142: @item format and range of floating point numbers:
                   12143: @cindex format and range of floating point numbers
                   12144: @cindex floating point numbers, format and range
                   12145: System-dependent; the @code{double} type of C.
                   12146: 
1.29      crook    12147: @item results of @code{REPRESENT} when @i{float} is out of range:
                   12148: @cindex  @code{REPRESENT}, results when @i{float} is out of range
1.1       anton    12149: System dependent; @code{REPRESENT} is implemented using the C library
                   12150: function @code{ecvt()} and inherits its behaviour in this respect.
                   12151: 
                   12152: @item rounding or truncation of floating-point numbers:
                   12153: @cindex rounding of floating-point numbers
                   12154: @cindex truncation of floating-point numbers
                   12155: @cindex floating-point numbers, rounding or truncation
                   12156: System dependent; the rounding behaviour is inherited from the hosting C
                   12157: compiler. IEEE-FP-based (i.e., most) systems by default round to
                   12158: nearest, and break ties by rounding to even (i.e., such that the last
                   12159: bit of the mantissa is 0).
                   12160: 
                   12161: @item size of floating-point stack:
                   12162: @cindex floating-point stack size
                   12163: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
                   12164: the floating-point stack (in floats). You can specify this on startup
                   12165: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
                   12166: 
                   12167: @item width of floating-point stack:
                   12168: @cindex floating-point stack width 
                   12169: @code{1 floats}.
                   12170: 
                   12171: @end table
                   12172: 
                   12173: 
                   12174: @c ---------------------------------------------------------------------
                   12175: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
                   12176: @subsection Ambiguous conditions
                   12177: @c ---------------------------------------------------------------------
                   12178: @cindex floating-point words, ambiguous conditions
                   12179: @cindex ambiguous conditions, floating-point words
                   12180: 
                   12181: @table @i
                   12182: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
                   12183: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
                   12184: System-dependent. Typically results in a @code{-23 THROW} like other
                   12185: alignment violations.
                   12186: 
                   12187: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
                   12188: @cindex @code{f@@} used with an address that is not float aligned
                   12189: @cindex @code{f!} used with an address that is not float aligned
                   12190: System-dependent. Typically results in a @code{-23 THROW} like other
                   12191: alignment violations.
                   12192: 
                   12193: @item floating-point result out of range:
                   12194: @cindex floating-point result out of range
                   12195: System-dependent. Can result in a @code{-55 THROW} (Floating-point
                   12196: unidentified fault), or can produce a special value representing, e.g.,
                   12197: Infinity.
                   12198: 
                   12199: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
                   12200: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
                   12201: System-dependent. Typically results in an alignment fault like other
                   12202: alignment violations.
                   12203: 
1.35      anton    12204: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
                   12205: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1       anton    12206: The floating-point number is converted into decimal nonetheless.
                   12207: 
                   12208: @item Both arguments are equal to zero (@code{FATAN2}):
                   12209: @cindex @code{FATAN2}, both arguments are equal to zero
                   12210: System-dependent. @code{FATAN2} is implemented using the C library
                   12211: function @code{atan2()}.
                   12212: 
1.29      crook    12213: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
                   12214: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
                   12215: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1       anton    12216: because of small errors and the tan will be a very large (or very small)
                   12217: but finite number.
                   12218: 
1.29      crook    12219: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
                   12220: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1       anton    12221: The result is rounded to the nearest float.
                   12222: 
                   12223: @item dividing by zero:
                   12224: @cindex dividing by zero, floating-point
                   12225: @cindex floating-point dividing by zero
                   12226: @cindex floating-point unidentified fault, FP divide-by-zero
                   12227: @code{-55 throw} (Floating-point unidentified fault)
                   12228: 
                   12229: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
                   12230: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
                   12231: System dependent. On IEEE-FP based systems the number is converted into
                   12232: an infinity.
                   12233: 
1.29      crook    12234: @item @i{float}<1 (@code{FACOSH}):
                   12235: @cindex @code{FACOSH}, @i{float}<1
1.1       anton    12236: @cindex floating-point unidentified fault, @code{FACOSH}
                   12237: @code{-55 throw} (Floating-point unidentified fault)
                   12238: 
1.29      crook    12239: @item @i{float}=<-1 (@code{FLNP1}):
                   12240: @cindex @code{FLNP1}, @i{float}=<-1
1.1       anton    12241: @cindex floating-point unidentified fault, @code{FLNP1}
                   12242: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29      crook    12243: negative infinity is typically produced for @i{float}=-1.
1.1       anton    12244: 
1.29      crook    12245: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
                   12246: @cindex @code{FLN}, @i{float}=<0
                   12247: @cindex @code{FLOG}, @i{float}=<0
1.1       anton    12248: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
                   12249: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29      crook    12250: negative infinity is typically produced for @i{float}=0.
1.1       anton    12251: 
1.29      crook    12252: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
                   12253: @cindex @code{FASINH}, @i{float}<0
                   12254: @cindex @code{FSQRT}, @i{float}<0
1.1       anton    12255: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
                   12256: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
                   12257: produces values for these inputs on my Linux box (Bug in the C library?)
                   12258: 
1.29      crook    12259: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
                   12260: @cindex @code{FACOS}, |@i{float}|>1
                   12261: @cindex @code{FASIN}, |@i{float}|>1
                   12262: @cindex @code{FATANH}, |@i{float}|>1
1.1       anton    12263: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
                   12264: @code{-55 throw} (Floating-point unidentified fault).
                   12265: 
1.29      crook    12266: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
                   12267: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1       anton    12268: @cindex floating-point unidentified fault, @code{F>D}
                   12269: @code{-55 throw} (Floating-point unidentified fault).
                   12270: 
                   12271: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
                   12272: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
                   12273: This does not happen.
                   12274: @end table
                   12275: 
                   12276: @c =====================================================================
                   12277: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
                   12278: @section The optional Locals word set
                   12279: @c =====================================================================
                   12280: @cindex system documentation, locals words
                   12281: @cindex locals words, system documentation
                   12282: 
                   12283: @menu
                   12284: * locals-idef::                 Implementation Defined Options                 
                   12285: * locals-ambcond::              Ambiguous Conditions              
                   12286: @end menu
                   12287: 
                   12288: 
                   12289: @c ---------------------------------------------------------------------
                   12290: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
                   12291: @subsection Implementation Defined Options
                   12292: @c ---------------------------------------------------------------------
                   12293: @cindex implementation-defined options, locals words
                   12294: @cindex locals words, implementation-defined options
                   12295: 
                   12296: @table @i
                   12297: @item maximum number of locals in a definition:
                   12298: @cindex maximum number of locals in a definition
                   12299: @cindex locals, maximum number in a definition
                   12300: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
                   12301: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
                   12302: characters. The number of locals in a definition is bounded by the size
                   12303: of locals-buffer, which contains the names of the locals.
                   12304: 
                   12305: @end table
                   12306: 
                   12307: 
                   12308: @c ---------------------------------------------------------------------
                   12309: @node locals-ambcond,  , locals-idef, The optional Locals word set
                   12310: @subsection Ambiguous conditions
                   12311: @c ---------------------------------------------------------------------
                   12312: @cindex locals words, ambiguous conditions
                   12313: @cindex ambiguous conditions, locals words
                   12314: 
                   12315: @table @i
                   12316: @item executing a named local in interpretation state:
                   12317: @cindex local in interpretation state
                   12318: @cindex Interpreting a compile-only word, for a local
                   12319: Locals have no interpretation semantics. If you try to perform the
                   12320: interpretation semantics, you will get a @code{-14 throw} somewhere
                   12321: (Interpreting a compile-only word). If you perform the compilation
                   12322: semantics, the locals access will be compiled (irrespective of state).
                   12323: 
1.29      crook    12324: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1       anton    12325: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
                   12326: @cindex @code{TO} on non-@code{VALUE}s and non-locals
                   12327: @cindex Invalid name argument, @code{TO}
                   12328: @code{-32 throw} (Invalid name argument)
                   12329: 
                   12330: @end table
                   12331: 
                   12332: 
                   12333: @c =====================================================================
                   12334: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
                   12335: @section The optional Memory-Allocation word set
                   12336: @c =====================================================================
                   12337: @cindex system documentation, memory-allocation words
                   12338: @cindex memory-allocation words, system documentation
                   12339: 
                   12340: @menu
                   12341: * memory-idef::                 Implementation Defined Options                 
                   12342: @end menu
                   12343: 
                   12344: 
                   12345: @c ---------------------------------------------------------------------
                   12346: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
                   12347: @subsection Implementation Defined Options
                   12348: @c ---------------------------------------------------------------------
                   12349: @cindex implementation-defined options, memory-allocation words
                   12350: @cindex memory-allocation words, implementation-defined options
                   12351: 
                   12352: @table @i
1.29      crook    12353: @item values and meaning of @i{ior}:
                   12354: @cindex  @i{ior} values and meaning
                   12355: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    12356: intended as throw codes. They typically are in the range
                   12357: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    12358: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    12359: 
                   12360: @end table
                   12361: 
                   12362: @c =====================================================================
                   12363: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
                   12364: @section The optional Programming-Tools word set
                   12365: @c =====================================================================
                   12366: @cindex system documentation, programming-tools words
                   12367: @cindex programming-tools words, system documentation
                   12368: 
                   12369: @menu
                   12370: * programming-idef::            Implementation Defined Options            
                   12371: * programming-ambcond::         Ambiguous Conditions         
                   12372: @end menu
                   12373: 
                   12374: 
                   12375: @c ---------------------------------------------------------------------
                   12376: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
                   12377: @subsection Implementation Defined Options
                   12378: @c ---------------------------------------------------------------------
                   12379: @cindex implementation-defined options, programming-tools words
                   12380: @cindex programming-tools words, implementation-defined options
                   12381: 
                   12382: @table @i
                   12383: @item ending sequence for input following @code{;CODE} and @code{CODE}:
                   12384: @cindex @code{;CODE} ending sequence
                   12385: @cindex @code{CODE} ending sequence
                   12386: @code{END-CODE}
                   12387: 
                   12388: @item manner of processing input following @code{;CODE} and @code{CODE}:
                   12389: @cindex @code{;CODE}, processing input
                   12390: @cindex @code{CODE}, processing input
                   12391: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
                   12392: the input is processed by the text interpreter, (starting) in interpret
                   12393: state.
                   12394: 
                   12395: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
                   12396: @cindex @code{ASSEMBLER}, search order capability
                   12397: The ANS Forth search order word set.
                   12398: 
                   12399: @item source and format of display by @code{SEE}:
                   12400: @cindex @code{SEE}, source and format of output
                   12401: The source for @code{see} is the intermediate code used by the inner
                   12402: interpreter.  The current @code{see} tries to output Forth source code
                   12403: as well as possible.
                   12404: 
                   12405: @end table
                   12406: 
                   12407: @c ---------------------------------------------------------------------
                   12408: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
                   12409: @subsection Ambiguous conditions
                   12410: @c ---------------------------------------------------------------------
                   12411: @cindex programming-tools words, ambiguous conditions
                   12412: @cindex ambiguous conditions, programming-tools words
                   12413: 
                   12414: @table @i
                   12415: 
1.21      crook    12416: @item deleting the compilation word list (@code{FORGET}):
                   12417: @cindex @code{FORGET}, deleting the compilation word list
1.1       anton    12418: Not implemented (yet).
                   12419: 
1.29      crook    12420: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
                   12421: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
                   12422: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1       anton    12423: @cindex control-flow stack underflow
                   12424: This typically results in an @code{abort"} with a descriptive error
                   12425: message (may change into a @code{-22 throw} (Control structure mismatch)
                   12426: in the future). You may also get a memory access error. If you are
                   12427: unlucky, this ambiguous condition is not caught.
                   12428: 
1.29      crook    12429: @item @i{name} can't be found (@code{FORGET}):
                   12430: @cindex @code{FORGET}, @i{name} can't be found
1.1       anton    12431: Not implemented (yet).
                   12432: 
1.29      crook    12433: @item @i{name} not defined via @code{CREATE}:
                   12434: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1       anton    12435: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
                   12436: the execution semantics of the last defined word no matter how it was
                   12437: defined.
                   12438: 
                   12439: @item @code{POSTPONE} applied to @code{[IF]}:
                   12440: @cindex @code{POSTPONE} applied to @code{[IF]}
                   12441: @cindex @code{[IF]} and @code{POSTPONE}
                   12442: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
                   12443: equivalent to @code{[IF]}.
                   12444: 
                   12445: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
                   12446: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
                   12447: Continue in the same state of conditional compilation in the next outer
                   12448: input source. Currently there is no warning to the user about this.
                   12449: 
                   12450: @item removing a needed definition (@code{FORGET}):
                   12451: @cindex @code{FORGET}, removing a needed definition
                   12452: Not implemented (yet).
                   12453: 
                   12454: @end table
                   12455: 
                   12456: 
                   12457: @c =====================================================================
                   12458: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
                   12459: @section The optional Search-Order word set
                   12460: @c =====================================================================
                   12461: @cindex system documentation, search-order words
                   12462: @cindex search-order words, system documentation
                   12463: 
                   12464: @menu
                   12465: * search-idef::                 Implementation Defined Options                 
                   12466: * search-ambcond::              Ambiguous Conditions              
                   12467: @end menu
                   12468: 
                   12469: 
                   12470: @c ---------------------------------------------------------------------
                   12471: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
                   12472: @subsection Implementation Defined Options
                   12473: @c ---------------------------------------------------------------------
                   12474: @cindex implementation-defined options, search-order words
                   12475: @cindex search-order words, implementation-defined options
                   12476: 
                   12477: @table @i
                   12478: @item maximum number of word lists in search order:
                   12479: @cindex maximum number of word lists in search order
                   12480: @cindex search order, maximum depth
                   12481: @code{s" wordlists" environment? drop .}. Currently 16.
                   12482: 
                   12483: @item minimum search order:
                   12484: @cindex minimum search order
                   12485: @cindex search order, minimum
                   12486: @code{root root}.
                   12487: 
                   12488: @end table
                   12489: 
                   12490: @c ---------------------------------------------------------------------
                   12491: @node search-ambcond,  , search-idef, The optional Search-Order word set
                   12492: @subsection Ambiguous conditions
                   12493: @c ---------------------------------------------------------------------
                   12494: @cindex search-order words, ambiguous conditions
                   12495: @cindex ambiguous conditions, search-order words
                   12496: 
                   12497: @table @i
1.21      crook    12498: @item changing the compilation word list (during compilation):
                   12499: @cindex changing the compilation word list (during compilation)
                   12500: @cindex compilation word list, change before definition ends
                   12501: The word is entered into the word list that was the compilation word list
1.1       anton    12502: at the start of the definition. Any changes to the name field (e.g.,
                   12503: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
                   12504: are applied to the latest defined word (as reported by @code{last} or
1.21      crook    12505: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1       anton    12506: 
                   12507: @item search order empty (@code{previous}):
                   12508: @cindex @code{previous}, search order empty
1.26      crook    12509: @cindex vocstack empty, @code{previous}
1.1       anton    12510: @code{abort" Vocstack empty"}.
                   12511: 
                   12512: @item too many word lists in search order (@code{also}):
                   12513: @cindex @code{also}, too many word lists in search order
1.26      crook    12514: @cindex vocstack full, @code{also}
1.1       anton    12515: @code{abort" Vocstack full"}.
                   12516: 
                   12517: @end table
                   12518: 
                   12519: @c ***************************************************************
                   12520: @node Model, Integrating Gforth, ANS conformance, Top
                   12521: @chapter Model
                   12522: 
                   12523: This chapter has yet to be written. It will contain information, on
                   12524: which internal structures you can rely.
                   12525: 
                   12526: @c ***************************************************************
                   12527: @node Integrating Gforth, Emacs and Gforth, Model, Top
                   12528: @chapter Integrating Gforth into C programs
                   12529: 
                   12530: This is not yet implemented.
                   12531: 
                   12532: Several people like to use Forth as scripting language for applications
                   12533: that are otherwise written in C, C++, or some other language.
                   12534: 
                   12535: The Forth system ATLAST provides facilities for embedding it into
                   12536: applications; unfortunately it has several disadvantages: most
                   12537: importantly, it is not based on ANS Forth, and it is apparently dead
                   12538: (i.e., not developed further and not supported). The facilities
1.21      crook    12539: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1       anton    12540: making the switch should not be hard.
                   12541: 
                   12542: We also tried to design the interface such that it can easily be
                   12543: implemented by other Forth systems, so that we may one day arrive at a
                   12544: standardized interface. Such a standard interface would allow you to
                   12545: replace the Forth system without having to rewrite C code.
                   12546: 
                   12547: You embed the Gforth interpreter by linking with the library
                   12548: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
                   12549: global symbols in this library that belong to the interface, have the
                   12550: prefix @code{forth_}. (Global symbols that are used internally have the
                   12551: prefix @code{gforth_}).
                   12552: 
                   12553: You can include the declarations of Forth types and the functions and
                   12554: variables of the interface with @code{#include <forth.h>}.
                   12555: 
                   12556: Types.
                   12557: 
                   12558: Variables.
                   12559: 
                   12560: Data and FP Stack pointer. Area sizes.
                   12561: 
                   12562: functions.
                   12563: 
                   12564: forth_init(imagefile)
                   12565: forth_evaluate(string) exceptions?
                   12566: forth_goto(address) (or forth_execute(xt)?)
                   12567: forth_continue() (a corountining mechanism)
                   12568: 
                   12569: Adding primitives.
                   12570: 
                   12571: No checking.
                   12572: 
                   12573: Signals?
                   12574: 
                   12575: Accessing the Stacks
                   12576: 
1.26      crook    12577: @c ******************************************************************
1.1       anton    12578: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
                   12579: @chapter Emacs and Gforth
                   12580: @cindex Emacs and Gforth
                   12581: 
                   12582: @cindex @file{gforth.el}
                   12583: @cindex @file{forth.el}
                   12584: @cindex Rydqvist, Goran
                   12585: @cindex comment editing commands
                   12586: @cindex @code{\}, editing with Emacs
                   12587: @cindex debug tracer editing commands
                   12588: @cindex @code{~~}, removal with Emacs
                   12589: @cindex Forth mode in Emacs
                   12590: Gforth comes with @file{gforth.el}, an improved version of
                   12591: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26      crook    12592: improvements are:
                   12593: 
                   12594: @itemize @bullet
                   12595: @item
                   12596: A better (but still not perfect) handling of indentation.
                   12597: @item
                   12598: Comment paragraph filling (@kbd{M-q})
                   12599: @item
                   12600: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
                   12601: @item
                   12602: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41      anton    12603: @item
                   12604: Support of the @code{info-lookup} feature for looking up the
                   12605: documentation of a word.
1.26      crook    12606: @end itemize
                   12607: 
                   12608: I left the stuff I do not use alone, even though some of it only makes
                   12609: sense for TILE. To get a description of these features, enter Forth mode
                   12610: and type @kbd{C-h m}.
1.1       anton    12611: 
                   12612: @cindex source location of error or debugging output in Emacs
                   12613: @cindex error output, finding the source location in Emacs
                   12614: @cindex debugging output, finding the source location in Emacs
                   12615: In addition, Gforth supports Emacs quite well: The source code locations
                   12616: given in error messages, debugging output (from @code{~~}) and failed
                   12617: assertion messages are in the right format for Emacs' compilation mode
                   12618: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
                   12619: Manual}) so the source location corresponding to an error or other
                   12620: message is only a few keystrokes away (@kbd{C-x `} for the next error,
                   12621: @kbd{C-c C-c} for the error under the cursor).
                   12622: 
                   12623: @cindex @file{TAGS} file
                   12624: @cindex @file{etags.fs}
                   12625: @cindex viewing the source of a word in Emacs
1.43      anton    12626: @cindex @code{require}, placement in files
                   12627: @cindex @code{include}, placement in files
                   12628: Also, if you @code{require} @file{etags.fs}, a new @file{TAGS} file will
1.26      crook    12629: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1       anton    12630: contains the definitions of all words defined afterwards. You can then
                   12631: find the source for a word using @kbd{M-.}. Note that emacs can use
                   12632: several tags files at the same time (e.g., one for the Gforth sources
                   12633: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
                   12634: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
                   12635: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43      anton    12636: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
                   12637: with @file{etags.fs}, you should avoid putting definitions both before
                   12638: and after @code{require} etc., otherwise you will see the same file
                   12639: visited several times by commands like @code{tags-search}.
1.1       anton    12640: 
1.41      anton    12641: @cindex viewing the documentation of a word in Emacs
                   12642: @cindex context-sensitive help
                   12643: Moreover, for words documented in this manual, you can look up the
                   12644: glossary entry quickly by using @kbd{C-h TAB}
                   12645: (@code{info-lookup-symbol}, see @pxref{Documentation, ,Documentation
                   12646: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
1.42      anton    12647: later and does not work for words containing @code{:}.
1.41      anton    12648: 
                   12649: 
1.1       anton    12650: @cindex @file{.emacs}
                   12651: To get all these benefits, add the following lines to your @file{.emacs}
                   12652: file:
                   12653: 
                   12654: @example
                   12655: (autoload 'forth-mode "gforth.el")
                   12656: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
                   12657: @end example
                   12658: 
1.26      crook    12659: @c ******************************************************************
1.1       anton    12660: @node Image Files, Engine, Emacs and Gforth, Top
                   12661: @chapter Image Files
1.26      crook    12662: @cindex image file
                   12663: @cindex @file{.fi} files
1.1       anton    12664: @cindex precompiled Forth code
                   12665: @cindex dictionary in persistent form
                   12666: @cindex persistent form of dictionary
                   12667: 
                   12668: An image file is a file containing an image of the Forth dictionary,
                   12669: i.e., compiled Forth code and data residing in the dictionary.  By
                   12670: convention, we use the extension @code{.fi} for image files.
                   12671: 
                   12672: @menu
1.18      anton    12673: * Image Licensing Issues::      Distribution terms for images.
                   12674: * Image File Background::       Why have image files?
1.29      crook    12675: * Non-Relocatable Image Files::   don't always work.
1.18      anton    12676: * Data-Relocatable Image Files::  are better.
1.29      crook    12677: * Fully Relocatable Image Files:: better yet.
1.18      anton    12678: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.29      crook    12679: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.18      anton    12680: * Modifying the Startup Sequence::  and turnkey applications.
1.1       anton    12681: @end menu
                   12682: 
1.18      anton    12683: @node Image Licensing Issues, Image File Background, Image Files, Image Files
                   12684: @section Image Licensing Issues
                   12685: @cindex license for images
                   12686: @cindex image license
                   12687: 
                   12688: An image created with @code{gforthmi} (@pxref{gforthmi}) or
                   12689: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
                   12690: original image; i.e., according to copyright law it is a derived work of
                   12691: the original image.
                   12692: 
                   12693: Since Gforth is distributed under the GNU GPL, the newly created image
                   12694: falls under the GNU GPL, too. In particular, this means that if you
                   12695: distribute the image, you have to make all of the sources for the image
                   12696: available, including those you wrote.  For details see @ref{License, ,
                   12697: GNU General Public License (Section 3)}.
                   12698: 
                   12699: If you create an image with @code{cross} (@pxref{cross.fs}), the image
                   12700: contains only code compiled from the sources you gave it; if none of
                   12701: these sources is under the GPL, the terms discussed above do not apply
                   12702: to the image. However, if your image needs an engine (a gforth binary)
                   12703: that is under the GPL, you should make sure that you distribute both in
                   12704: a way that is at most a @emph{mere aggregation}, if you don't want the
                   12705: terms of the GPL to apply to the image.
                   12706: 
                   12707: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1       anton    12708: @section Image File Background
                   12709: @cindex image file background
                   12710: 
                   12711: Our Forth system consists not only of primitives, but also of
                   12712: definitions written in Forth. Since the Forth compiler itself belongs to
                   12713: those definitions, it is not possible to start the system with the
                   12714: primitives and the Forth source alone. Therefore we provide the Forth
1.26      crook    12715: code as an image file in nearly executable form. When Gforth starts up,
                   12716: a C routine loads the image file into memory, optionally relocates the
                   12717: addresses, then sets up the memory (stacks etc.) according to
                   12718: information in the image file, and (finally) starts executing Forth
                   12719: code.
1.1       anton    12720: 
                   12721: The image file variants represent different compromises between the
                   12722: goals of making it easy to generate image files and making them
                   12723: portable.
                   12724: 
                   12725: @cindex relocation at run-time
1.26      crook    12726: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1       anton    12727: run-time. This avoids many of the complications discussed below (image
                   12728: files are data relocatable without further ado), but costs performance
                   12729: (one addition per memory access).
                   12730: 
                   12731: @cindex relocation at load-time
1.26      crook    12732: By contrast, the Gforth loader performs relocation at image load time. The
                   12733: loader also has to replace tokens that represent primitive calls with the
1.1       anton    12734: appropriate code-field addresses (or code addresses in the case of
                   12735: direct threading).
                   12736: 
                   12737: There are three kinds of image files, with different degrees of
                   12738: relocatability: non-relocatable, data-relocatable, and fully relocatable
                   12739: image files.
                   12740: 
                   12741: @cindex image file loader
                   12742: @cindex relocating loader
                   12743: @cindex loader for image files
                   12744: These image file variants have several restrictions in common; they are
                   12745: caused by the design of the image file loader:
                   12746: 
                   12747: @itemize @bullet
                   12748: @item
                   12749: There is only one segment; in particular, this means, that an image file
                   12750: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26      crook    12751: them). The contents of the stacks are not represented, either.
1.1       anton    12752: 
                   12753: @item
                   12754: The only kinds of relocation supported are: adding the same offset to
                   12755: all cells that represent data addresses; and replacing special tokens
                   12756: with code addresses or with pieces of machine code.
                   12757: 
                   12758: If any complex computations involving addresses are performed, the
                   12759: results cannot be represented in the image file. Several applications that
                   12760: use such computations come to mind:
                   12761: @itemize @minus
                   12762: @item
                   12763: Hashing addresses (or data structures which contain addresses) for table
                   12764: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
                   12765: purpose, you will have no problem, because the hash tables are
                   12766: recomputed automatically when the system is started. If you use your own
                   12767: hash tables, you will have to do something similar.
                   12768: 
                   12769: @item
                   12770: There's a cute implementation of doubly-linked lists that uses
                   12771: @code{XOR}ed addresses. You could represent such lists as singly-linked
                   12772: in the image file, and restore the doubly-linked representation on
                   12773: startup.@footnote{In my opinion, though, you should think thrice before
                   12774: using a doubly-linked list (whatever implementation).}
                   12775: 
                   12776: @item
                   12777: The code addresses of run-time routines like @code{docol:} cannot be
                   12778: represented in the image file (because their tokens would be replaced by
                   12779: machine code in direct threaded implementations). As a workaround,
                   12780: compute these addresses at run-time with @code{>code-address} from the
                   12781: executions tokens of appropriate words (see the definitions of
                   12782: @code{docol:} and friends in @file{kernel.fs}).
                   12783: 
                   12784: @item
                   12785: On many architectures addresses are represented in machine code in some
                   12786: shifted or mangled form. You cannot put @code{CODE} words that contain
                   12787: absolute addresses in this form in a relocatable image file. Workarounds
                   12788: are representing the address in some relative form (e.g., relative to
                   12789: the CFA, which is present in some register), or loading the address from
                   12790: a place where it is stored in a non-mangled form.
                   12791: @end itemize
                   12792: @end itemize
                   12793: 
                   12794: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
                   12795: @section Non-Relocatable Image Files
                   12796: @cindex non-relocatable image files
1.26      crook    12797: @cindex image file, non-relocatable
1.1       anton    12798: 
                   12799: These files are simple memory dumps of the dictionary. They are specific
                   12800: to the executable (i.e., @file{gforth} file) they were created
                   12801: with. What's worse, they are specific to the place on which the
                   12802: dictionary resided when the image was created. Now, there is no
                   12803: guarantee that the dictionary will reside at the same place the next
                   12804: time you start Gforth, so there's no guarantee that a non-relocatable
                   12805: image will work the next time (Gforth will complain instead of crashing,
                   12806: though).
                   12807: 
                   12808: You can create a non-relocatable image file with
                   12809: 
1.44      crook    12810: 
1.1       anton    12811: doc-savesystem
                   12812: 
1.44      crook    12813: 
1.1       anton    12814: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
                   12815: @section Data-Relocatable Image Files
                   12816: @cindex data-relocatable image files
1.26      crook    12817: @cindex image file, data-relocatable
1.1       anton    12818: 
                   12819: These files contain relocatable data addresses, but fixed code addresses
                   12820: (instead of tokens). They are specific to the executable (i.e.,
                   12821: @file{gforth} file) they were created with. For direct threading on some
                   12822: architectures (e.g., the i386), data-relocatable images do not work. You
                   12823: get a data-relocatable image, if you use @file{gforthmi} with a
                   12824: Gforth binary that is not doubly indirect threaded (@pxref{Fully
                   12825: Relocatable Image Files}).
                   12826: 
                   12827: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
                   12828: @section Fully Relocatable Image Files
                   12829: @cindex fully relocatable image files
1.26      crook    12830: @cindex image file, fully relocatable
1.1       anton    12831: 
                   12832: @cindex @file{kern*.fi}, relocatability
                   12833: @cindex @file{gforth.fi}, relocatability
                   12834: These image files have relocatable data addresses, and tokens for code
                   12835: addresses. They can be used with different binaries (e.g., with and
                   12836: without debugging) on the same machine, and even across machines with
                   12837: the same data formats (byte order, cell size, floating point
                   12838: format). However, they are usually specific to the version of Gforth
                   12839: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
                   12840: are fully relocatable.
                   12841: 
                   12842: There are two ways to create a fully relocatable image file:
                   12843: 
                   12844: @menu
1.29      crook    12845: * gforthmi::                    The normal way
1.1       anton    12846: * cross.fs::                    The hard way
                   12847: @end menu
                   12848: 
                   12849: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
                   12850: @subsection @file{gforthmi}
                   12851: @cindex @file{comp-i.fs}
                   12852: @cindex @file{gforthmi}
                   12853: 
                   12854: You will usually use @file{gforthmi}. If you want to create an
1.29      crook    12855: image @i{file} that contains everything you would load by invoking
                   12856: Gforth with @code{gforth @i{options}}, you simply say:
1.1       anton    12857: @example
1.29      crook    12858: gforthmi @i{file} @i{options}
1.1       anton    12859: @end example
                   12860: 
                   12861: E.g., if you want to create an image @file{asm.fi} that has the file
                   12862: @file{asm.fs} loaded in addition to the usual stuff, you could do it
                   12863: like this:
                   12864: 
                   12865: @example
                   12866: gforthmi asm.fi asm.fs
                   12867: @end example
                   12868: 
1.27      crook    12869: @file{gforthmi} is implemented as a sh script and works like this: It
                   12870: produces two non-relocatable images for different addresses and then
                   12871: compares them. Its output reflects this: first you see the output (if
                   12872: any) of the two Gforth invocations that produce the nonrelocatable image
                   12873: files, then you see the output of the comparing program: It displays the
                   12874: offset used for data addresses and the offset used for code addresses;
1.1       anton    12875: moreover, for each cell that cannot be represented correctly in the
1.44      crook    12876: image files, it displays a line like this:
1.1       anton    12877: 
                   12878: @example
                   12879:      78DC         BFFFFA50         BFFFFA40
                   12880: @end example
                   12881: 
                   12882: This means that at offset $78dc from @code{forthstart}, one input image
                   12883: contains $bffffa50, and the other contains $bffffa40. Since these cells
                   12884: cannot be represented correctly in the output image, you should examine
                   12885: these places in the dictionary and verify that these cells are dead
                   12886: (i.e., not read before they are written).
1.39      anton    12887: 
                   12888: @cindex --application, @code{gforthmi} option
                   12889: If you insert the option @code{--application} in front of the image file
                   12890: name, you will get an image that uses the @code{--appl-image} option
                   12891: instead of the @code{--image-file} option (@pxref{Invoking
                   12892: Gforth}). When you execute such an image on Unix (by typing the image
                   12893: name as command), the Gforth engine will pass all options to the image
                   12894: instead of trying to interpret them as engine options.
1.1       anton    12895: 
1.27      crook    12896: If you type @file{gforthmi} with no arguments, it prints some usage
                   12897: instructions.
                   12898: 
1.1       anton    12899: @cindex @code{savesystem} during @file{gforthmi}
                   12900: @cindex @code{bye} during @file{gforthmi}
                   12901: @cindex doubly indirect threaded code
1.44      crook    12902: @cindex environment variables
                   12903: @cindex @code{GFORTHD} -- environment variable
                   12904: @cindex @code{GFORTH} -- environment variable
1.1       anton    12905: @cindex @code{gforth-ditc}
1.29      crook    12906: There are a few wrinkles: After processing the passed @i{options}, the
1.1       anton    12907: words @code{savesystem} and @code{bye} must be visible. A special doubly
                   12908: indirect threaded version of the @file{gforth} executable is used for
                   12909: creating the nonrelocatable images; you can pass the exact filename of
                   12910: this executable through the environment variable @code{GFORTHD}
                   12911: (default: @file{gforth-ditc}); if you pass a version that is not doubly
                   12912: indirect threaded, you will not get a fully relocatable image, but a
1.27      crook    12913: data-relocatable image (because there is no code address offset). The
                   12914: normal @file{gforth} executable is used for creating the relocatable
                   12915: image; you can pass the exact filename of this executable through the
                   12916: environment variable @code{GFORTH}.
1.1       anton    12917: 
                   12918: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
                   12919: @subsection @file{cross.fs}
                   12920: @cindex @file{cross.fs}
                   12921: @cindex cross-compiler
                   12922: @cindex metacompiler
1.47      crook    12923: @cindex target compiler
1.1       anton    12924: 
                   12925: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47      crook    12926: programming language (@pxref{Cross Compiler}).
1.1       anton    12927: 
1.47      crook    12928: @code{cross} allows you to create image files for machines with
1.1       anton    12929: different data sizes and data formats than the one used for generating
                   12930: the image file. You can also use it to create an application image that
                   12931: does not contain a Forth compiler. These features are bought with
                   12932: restrictions and inconveniences in programming. E.g., addresses have to
                   12933: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
                   12934: order to make the code relocatable.
                   12935: 
                   12936: 
                   12937: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
                   12938: @section Stack and Dictionary Sizes
                   12939: @cindex image file, stack and dictionary sizes
                   12940: @cindex dictionary size default
                   12941: @cindex stack size default
                   12942: 
                   12943: If you invoke Gforth with a command line flag for the size
                   12944: (@pxref{Invoking Gforth}), the size you specify is stored in the
                   12945: dictionary. If you save the dictionary with @code{savesystem} or create
                   12946: an image with @file{gforthmi}, this size will become the default
                   12947: for the resulting image file. E.g., the following will create a
1.21      crook    12948: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1       anton    12949: 
                   12950: @example
                   12951: gforthmi gforth.fi -m 1M
                   12952: @end example
                   12953: 
                   12954: In other words, if you want to set the default size for the dictionary
                   12955: and the stacks of an image, just invoke @file{gforthmi} with the
                   12956: appropriate options when creating the image.
                   12957: 
                   12958: @cindex stack size, cache-friendly
                   12959: Note: For cache-friendly behaviour (i.e., good performance), you should
                   12960: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
                   12961: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
                   12962: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
                   12963: 
                   12964: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
                   12965: @section Running Image Files
                   12966: @cindex running image files
                   12967: @cindex invoking image files
                   12968: @cindex image file invocation
                   12969: 
                   12970: @cindex -i, invoke image file
                   12971: @cindex --image file, invoke image file
1.29      crook    12972: You can invoke Gforth with an image file @i{image} instead of the
1.1       anton    12973: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
                   12974: @example
1.29      crook    12975: gforth -i @i{image}
1.1       anton    12976: @end example
                   12977: 
                   12978: @cindex executable image file
1.26      crook    12979: @cindex image file, executable
1.1       anton    12980: If your operating system supports starting scripts with a line of the
                   12981: form @code{#! ...}, you just have to type the image file name to start
                   12982: Gforth with this image file (note that the file extension @code{.fi} is
1.29      crook    12983: just a convention). I.e., to run Gforth with the image file @i{image},
                   12984: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27      crook    12985: This works because every @code{.fi} file starts with a line of this
                   12986: format:
                   12987: 
                   12988: @example
                   12989: #! /usr/local/bin/gforth-0.4.0 -i
                   12990: @end example
                   12991: 
                   12992: The file and pathname for the Gforth engine specified on this line is
                   12993: the specific Gforth executable that it was built against; i.e. the value
                   12994: of the environment variable @code{GFORTH} at the time that
                   12995: @file{gforthmi} was executed.
1.1       anton    12996: 
1.27      crook    12997: You can make use of the same shell capability to make a Forth source
                   12998: file into an executable. For example, if you place this text in a file:
1.26      crook    12999: 
                   13000: @example
                   13001: #! /usr/local/bin/gforth
                   13002: 
                   13003: ." Hello, world" CR
                   13004: bye
                   13005: @end example
                   13006: 
                   13007: @noindent
1.27      crook    13008: and then make the file executable (chmod +x in Unix), you can run it
1.26      crook    13009: directly from the command line. The sequence @code{#!} is used in two
                   13010: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29      crook    13011: system@footnote{The Unix kernel actually recognises two types of files:
                   13012: executable files and files of data, where the data is processed by an
                   13013: interpreter that is specified on the ``interpreter line'' -- the first
                   13014: line of the file, starting with the sequence #!. There may be a small
                   13015: limit (e.g., 32) on the number of characters that may be specified on
                   13016: the interpreter line.} secondly it is treated as a comment character by
                   13017: Gforth. Because of the second usage, a space is required between
                   13018: @code{#!} and the path to the executable.
1.27      crook    13019: 
                   13020: The disadvantage of this latter technique, compared with using
                   13021: @file{gforthmi}, is that it is slower; the Forth source code is compiled
                   13022: on-the-fly, each time the program is invoked.
                   13023: 
1.26      crook    13024: 
1.1       anton    13025: doc-#!
                   13026: 
1.44      crook    13027: 
1.1       anton    13028: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
                   13029: @section Modifying the Startup Sequence
                   13030: @cindex startup sequence for image file
                   13031: @cindex image file initialization sequence
                   13032: @cindex initialization sequence of image file
                   13033: 
                   13034: You can add your own initialization to the startup sequence through the
1.26      crook    13035: deferred word @code{'cold}. @code{'cold} is invoked just before the
                   13036: image-specific command line processing (by default, loading files and
                   13037: evaluating (@code{-e}) strings) starts.
1.1       anton    13038: 
                   13039: A sequence for adding your initialization usually looks like this:
                   13040: 
                   13041: @example
                   13042: :noname
                   13043:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
                   13044:     ... \ your stuff
                   13045: ; IS 'cold
                   13046: @end example
                   13047: 
                   13048: @cindex turnkey image files
1.26      crook    13049: @cindex image file, turnkey applications
1.1       anton    13050: You can make a turnkey image by letting @code{'cold} execute a word
                   13051: (your turnkey application) that never returns; instead, it exits Gforth
                   13052: via @code{bye} or @code{throw}.
                   13053: 
                   13054: @cindex command-line arguments, access
                   13055: @cindex arguments on the command line, access
                   13056: You can access the (image-specific) command-line arguments through the
1.26      crook    13057: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1       anton    13058: access to @code{argv}.
                   13059: 
1.26      crook    13060: If @code{'cold} exits normally, Gforth processes the command-line
                   13061: arguments as files to be loaded and strings to be evaluated.  Therefore,
                   13062: @code{'cold} should remove the arguments it has used in this case.
                   13063: 
1.44      crook    13064: 
                   13065: 
1.26      crook    13066: doc-'cold
1.1       anton    13067: doc-argc
                   13068: doc-argv
                   13069: doc-arg
                   13070: 
                   13071: 
1.44      crook    13072: 
1.1       anton    13073: @c ******************************************************************
1.13      pazsan   13074: @node Engine, Binding to System Library, Image Files, Top
1.1       anton    13075: @chapter Engine
                   13076: @cindex engine
                   13077: @cindex virtual machine
                   13078: 
1.26      crook    13079: Reading this chapter is not necessary for programming with Gforth. It
1.1       anton    13080: may be helpful for finding your way in the Gforth sources.
                   13081: 
                   13082: The ideas in this section have also been published in the papers
                   13083: @cite{ANS fig/GNU/??? Forth} (in German) by Bernd Paysan, presented at
                   13084: the Forth-Tagung '93 and @cite{A Portable Forth Engine} by M. Anton
                   13085: Ertl, presented at EuroForth '93; the latter is available at
1.47      crook    13086: @*@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z}.
1.1       anton    13087: 
                   13088: @menu
                   13089: * Portability::                 
                   13090: * Threading::                   
                   13091: * Primitives::                  
                   13092: * Performance::                 
                   13093: @end menu
                   13094: 
                   13095: @node Portability, Threading, Engine, Engine
                   13096: @section Portability
                   13097: @cindex engine portability
                   13098: 
1.26      crook    13099: An important goal of the Gforth Project is availability across a wide
                   13100: range of personal machines. fig-Forth, and, to a lesser extent, F83,
                   13101: achieved this goal by manually coding the engine in assembly language
                   13102: for several then-popular processors. This approach is very
                   13103: labor-intensive and the results are short-lived due to progress in
                   13104: computer architecture.
1.1       anton    13105: 
                   13106: @cindex C, using C for the engine
                   13107: Others have avoided this problem by coding in C, e.g., Mitch Bradley
                   13108: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
                   13109: particularly popular for UNIX-based Forths due to the large variety of
                   13110: architectures of UNIX machines. Unfortunately an implementation in C
                   13111: does not mix well with the goals of efficiency and with using
                   13112: traditional techniques: Indirect or direct threading cannot be expressed
                   13113: in C, and switch threading, the fastest technique available in C, is
                   13114: significantly slower. Another problem with C is that it is very
                   13115: cumbersome to express double integer arithmetic.
                   13116: 
                   13117: @cindex GNU C for the engine
                   13118: @cindex long long
                   13119: Fortunately, there is a portable language that does not have these
                   13120: limitations: GNU C, the version of C processed by the GNU C compiler
                   13121: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
                   13122: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
                   13123: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
                   13124: threading possible, its @code{long long} type (@pxref{Long Long, ,
                   13125: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
                   13126: double numbers@footnote{Unfortunately, long longs are not implemented
                   13127: properly on all machines (e.g., on alpha-osf1, long longs are only 64
                   13128: bits, the same size as longs (and pointers), but they should be twice as
1.4       anton    13129: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1       anton    13130: C Manual}). So, we had to implement doubles in C after all. Still, on
                   13131: most machines we can use long longs and achieve better performance than
                   13132: with the emulation package.}. GNU C is available for free on all
                   13133: important (and many unimportant) UNIX machines, VMS, 80386s running
                   13134: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
                   13135: on all these machines.
                   13136: 
                   13137: Writing in a portable language has the reputation of producing code that
                   13138: is slower than assembly. For our Forth engine we repeatedly looked at
                   13139: the code produced by the compiler and eliminated most compiler-induced
                   13140: inefficiencies by appropriate changes in the source code.
                   13141: 
                   13142: @cindex explicit register declarations
                   13143: @cindex --enable-force-reg, configuration flag
                   13144: @cindex -DFORCE_REG
                   13145: However, register allocation cannot be portably influenced by the
                   13146: programmer, leading to some inefficiencies on register-starved
                   13147: machines. We use explicit register declarations (@pxref{Explicit Reg
                   13148: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
                   13149: improve the speed on some machines. They are turned on by using the
                   13150: configuration flag @code{--enable-force-reg} (@code{gcc} switch
                   13151: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
                   13152: machine, but also on the compiler version: On some machines some
                   13153: compiler versions produce incorrect code when certain explicit register
                   13154: declarations are used. So by default @code{-DFORCE_REG} is not used.
                   13155: 
                   13156: @node Threading, Primitives, Portability, Engine
                   13157: @section Threading
                   13158: @cindex inner interpreter implementation
                   13159: @cindex threaded code implementation
                   13160: 
                   13161: @cindex labels as values
                   13162: GNU C's labels as values extension (available since @code{gcc-2.0},
                   13163: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29      crook    13164: makes it possible to take the address of @i{label} by writing
                   13165: @code{&&@i{label}}.  This address can then be used in a statement like
                   13166: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1       anton    13167: @code{goto x}.
                   13168: 
1.26      crook    13169: @cindex @code{NEXT}, indirect threaded
1.1       anton    13170: @cindex indirect threaded inner interpreter
                   13171: @cindex inner interpreter, indirect threaded
1.26      crook    13172: With this feature an indirect threaded @code{NEXT} looks like:
1.1       anton    13173: @example
                   13174: cfa = *ip++;
                   13175: ca = *cfa;
                   13176: goto *ca;
                   13177: @end example
                   13178: @cindex instruction pointer
                   13179: For those unfamiliar with the names: @code{ip} is the Forth instruction
                   13180: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
                   13181: execution token and points to the code field of the next word to be
                   13182: executed; The @code{ca} (code address) fetched from there points to some
                   13183: executable code, e.g., a primitive or the colon definition handler
                   13184: @code{docol}.
                   13185: 
1.26      crook    13186: @cindex @code{NEXT}, direct threaded
1.1       anton    13187: @cindex direct threaded inner interpreter
                   13188: @cindex inner interpreter, direct threaded
                   13189: Direct threading is even simpler:
                   13190: @example
                   13191: ca = *ip++;
                   13192: goto *ca;
                   13193: @end example
                   13194: 
                   13195: Of course we have packaged the whole thing neatly in macros called
1.26      crook    13196: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1       anton    13197: 
                   13198: @menu
                   13199: * Scheduling::                  
                   13200: * Direct or Indirect Threaded?::  
                   13201: * DOES>::                       
                   13202: @end menu
                   13203: 
                   13204: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
                   13205: @subsection Scheduling
                   13206: @cindex inner interpreter optimization
                   13207: 
                   13208: There is a little complication: Pipelined and superscalar processors,
                   13209: i.e., RISC and some modern CISC machines can process independent
                   13210: instructions while waiting for the results of an instruction. The
                   13211: compiler usually reorders (schedules) the instructions in a way that
                   13212: achieves good usage of these delay slots. However, on our first tries
                   13213: the compiler did not do well on scheduling primitives. E.g., for
                   13214: @code{+} implemented as
                   13215: @example
                   13216: n=sp[0]+sp[1];
                   13217: sp++;
                   13218: sp[0]=n;
                   13219: NEXT;
                   13220: @end example
1.26      crook    13221: the @code{NEXT} comes strictly after the other code, i.e., there is nearly no
1.1       anton    13222: scheduling. After a little thought the problem becomes clear: The
1.21      crook    13223: compiler cannot know that @code{sp} and @code{ip} point to different
                   13224: addresses (and the version of @code{gcc} we used would not know it even
                   13225: if it was possible), so it could not move the load of the cfa above the
                   13226: store to the TOS. Indeed the pointers could be the same, if code on or
                   13227: very near the top of stack were executed. In the interest of speed we
                   13228: chose to forbid this probably unused ``feature'' and helped the compiler
1.26      crook    13229: in scheduling: @code{NEXT} is divided into the loading part (@code{NEXT_P1})
1.21      crook    13230: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
1.1       anton    13231: @example
                   13232: n=sp[0]+sp[1];
                   13233: sp++;
                   13234: NEXT_P1;
                   13235: sp[0]=n;
                   13236: NEXT_P2;
                   13237: @end example
                   13238: This can be scheduled optimally by the compiler.
                   13239: 
                   13240: This division can be turned off with the switch @code{-DCISC_NEXT}. This
                   13241: switch is on by default on machines that do not profit from scheduling
                   13242: (e.g., the 80386), in order to preserve registers.
                   13243: 
                   13244: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
                   13245: @subsection Direct or Indirect Threaded?
                   13246: @cindex threading, direct or indirect?
                   13247: 
                   13248: @cindex -DDIRECT_THREADED
                   13249: Both! After packaging the nasty details in macro definitions we
                   13250: realized that we could switch between direct and indirect threading by
                   13251: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
                   13252: defining a few machine-specific macros for the direct-threading case.
                   13253: On the Forth level we also offer access words that hide the
                   13254: differences between the threading methods (@pxref{Threading Words}).
                   13255: 
                   13256: Indirect threading is implemented completely machine-independently.
                   13257: Direct threading needs routines for creating jumps to the executable
1.21      crook    13258: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
                   13259: machine-dependent, but they do not amount to many source lines. Therefore,
                   13260: even porting direct threading to a new machine requires little effort.
1.1       anton    13261: 
                   13262: @cindex --enable-indirect-threaded, configuration flag
                   13263: @cindex --enable-direct-threaded, configuration flag
                   13264: The default threading method is machine-dependent. You can enforce a
                   13265: specific threading method when building Gforth with the configuration
                   13266: flag @code{--enable-direct-threaded} or
                   13267: @code{--enable-indirect-threaded}. Note that direct threading is not
                   13268: supported on all machines.
                   13269: 
                   13270: @node DOES>,  , Direct or Indirect Threaded?, Threading
                   13271: @subsection DOES>
                   13272: @cindex @code{DOES>} implementation
                   13273: 
1.26      crook    13274: @cindex @code{dodoes} routine
                   13275: @cindex @code{DOES>}-code
1.1       anton    13276: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
                   13277: the chunk of code executed by every word defined by a
                   13278: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
                   13279: the Forth code to be executed, i.e. the code after the
1.26      crook    13280: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
1.1       anton    13281: 
1.21      crook    13282: In fig-Forth the code field points directly to the @code{dodoes} and the
1.45      crook    13283: @code{DOES>}-code address is stored in the cell after the code address (i.e. at
1.29      crook    13284: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
1.1       anton    13285: the Forth-79 and all later standards, because in fig-Forth this address
                   13286: lies in the body (which is illegal in these standards). However, by
                   13287: making the code field larger for all words this solution becomes legal
                   13288: again. We use this approach for the indirect threaded version and for
                   13289: direct threading on some machines. Leaving a cell unused in most words
                   13290: is a bit wasteful, but on the machines we are targeting this is hardly a
                   13291: problem. The other reason for having a code field size of two cells is
                   13292: to avoid having different image files for direct and indirect threaded
                   13293: systems (direct threaded systems require two-cell code fields on many
                   13294: machines).
                   13295: 
1.26      crook    13296: @cindex @code{DOES>}-handler
1.1       anton    13297: The other approach is that the code field points or jumps to the cell
1.26      crook    13298: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
                   13299: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
                   13300: @code{DOES>}-code address by computing the code address, i.e., the address of
1.45      crook    13301: the jump to @code{dodoes}, and add the length of that jump field. A variant of
1.1       anton    13302: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
                   13303: return address (which can be found in the return register on RISCs) is
1.26      crook    13304: the @code{DOES>}-code address. Since the two cells available in the code field
1.1       anton    13305: are used up by the jump to the code address in direct threading on many
                   13306: architectures, we use this approach for direct threading on these
                   13307: architectures. We did not want to add another cell to the code field.
                   13308: 
                   13309: @node Primitives, Performance, Threading, Engine
                   13310: @section Primitives
                   13311: @cindex primitives, implementation
                   13312: @cindex virtual machine instructions, implementation
                   13313: 
                   13314: @menu
                   13315: * Automatic Generation::        
                   13316: * TOS Optimization::            
                   13317: * Produced code::               
                   13318: @end menu
                   13319: 
                   13320: @node Automatic Generation, TOS Optimization, Primitives, Primitives
                   13321: @subsection Automatic Generation
                   13322: @cindex primitives, automatic generation
                   13323: 
                   13324: @cindex @file{prims2x.fs}
                   13325: Since the primitives are implemented in a portable language, there is no
                   13326: longer any need to minimize the number of primitives. On the contrary,
                   13327: having many primitives has an advantage: speed. In order to reduce the
                   13328: number of errors in primitives and to make programming them easier, we
                   13329: provide a tool, the primitive generator (@file{prims2x.fs}), that
                   13330: automatically generates most (and sometimes all) of the C code for a
                   13331: primitive from the stack effect notation.  The source for a primitive
                   13332: has the following form:
                   13333: 
                   13334: @cindex primitive source format
                   13335: @format
1.46      pazsan   13336: @i{Forth-name}  @i{stack-effect}        @i{category}    [@i{pronounc.}]
1.29      crook    13337: [@code{""}@i{glossary entry}@code{""}]
                   13338: @i{C code}
1.1       anton    13339: [@code{:}
1.29      crook    13340: @i{Forth code}]
1.1       anton    13341: @end format
                   13342: 
                   13343: The items in brackets are optional. The category and glossary fields
                   13344: are there for generating the documentation, the Forth code is there
                   13345: for manual implementations on machines without GNU C. E.g., the source
                   13346: for the primitive @code{+} is:
                   13347: @example
                   13348: +    n1 n2 -- n    core    plus
                   13349: n = n1+n2;
                   13350: @end example
                   13351: 
                   13352: This looks like a specification, but in fact @code{n = n1+n2} is C
                   13353: code. Our primitive generation tool extracts a lot of information from
                   13354: the stack effect notations@footnote{We use a one-stack notation, even
                   13355: though we have separate data and floating-point stacks; The separate
                   13356: notation can be generated easily from the unified notation.}: The number
                   13357: of items popped from and pushed on the stack, their type, and by what
                   13358: name they are referred to in the C code. It then generates a C code
                   13359: prelude and postlude for each primitive. The final C code for @code{+}
                   13360: looks like this:
                   13361: 
                   13362: @example
1.46      pazsan   13363: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
1.1       anton    13364: /*  */                          /* documentation */
                   13365: @{
                   13366: DEF_CA                          /* definition of variable ca (indirect threading) */
                   13367: Cell n1;                        /* definitions of variables */
                   13368: Cell n2;
                   13369: Cell n;
                   13370: n1 = (Cell) sp[1];              /* input */
                   13371: n2 = (Cell) TOS;
                   13372: sp += 1;                        /* stack adjustment */
                   13373: NAME("+")                       /* debugging output (with -DDEBUG) */
                   13374: @{
                   13375: n = n1+n2;                      /* C code taken from the source */
                   13376: @}
                   13377: NEXT_P1;                        /* NEXT part 1 */
                   13378: TOS = (Cell)n;                  /* output */
                   13379: NEXT_P2;                        /* NEXT part 2 */
                   13380: @}
                   13381: @end example
                   13382: 
                   13383: This looks long and inefficient, but the GNU C compiler optimizes quite
                   13384: well and produces optimal code for @code{+} on, e.g., the R3000 and the
                   13385: HP RISC machines: Defining the @code{n}s does not produce any code, and
                   13386: using them as intermediate storage also adds no cost.
                   13387: 
1.26      crook    13388: There are also other optimizations that are not illustrated by this
                   13389: example: assignments between simple variables are usually for free (copy
1.1       anton    13390: propagation). If one of the stack items is not used by the primitive
                   13391: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
                   13392: (dead code elimination). On the other hand, there are some things that
                   13393: the compiler does not do, therefore they are performed by
                   13394: @file{prims2x.fs}: The compiler does not optimize code away that stores
                   13395: a stack item to the place where it just came from (e.g., @code{over}).
                   13396: 
                   13397: While programming a primitive is usually easy, there are a few cases
                   13398: where the programmer has to take the actions of the generator into
                   13399: account, most notably @code{?dup}, but also words that do not (always)
1.26      crook    13400: fall through to @code{NEXT}.
1.1       anton    13401: 
                   13402: @node TOS Optimization, Produced code, Automatic Generation, Primitives
                   13403: @subsection TOS Optimization
                   13404: @cindex TOS optimization for primitives
                   13405: @cindex primitives, keeping the TOS in a register
                   13406: 
                   13407: An important optimization for stack machine emulators, e.g., Forth
                   13408: engines, is keeping  one or more of the top stack items in
1.29      crook    13409: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
                   13410: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1       anton    13411: @itemize @bullet
                   13412: @item
1.29      crook    13413: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1       anton    13414: due to fewer loads from and stores to the stack.
1.29      crook    13415: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
                   13416: @i{y<n}, due to additional moves between registers.
1.1       anton    13417: @end itemize
                   13418: 
                   13419: @cindex -DUSE_TOS
                   13420: @cindex -DUSE_NO_TOS
                   13421: In particular, keeping one item in a register is never a disadvantage,
                   13422: if there are enough registers. Keeping two items in registers is a
                   13423: disadvantage for frequent words like @code{?branch}, constants,
                   13424: variables, literals and @code{i}. Therefore our generator only produces
                   13425: code that keeps zero or one items in registers. The generated C code
                   13426: covers both cases; the selection between these alternatives is made at
                   13427: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
                   13428: code for @code{+} is just a simple variable name in the one-item case,
                   13429: otherwise it is a macro that expands into @code{sp[0]}. Note that the
                   13430: GNU C compiler tries to keep simple variables like @code{TOS} in
                   13431: registers, and it usually succeeds, if there are enough registers.
                   13432: 
                   13433: @cindex -DUSE_FTOS
                   13434: @cindex -DUSE_NO_FTOS
                   13435: The primitive generator performs the TOS optimization for the
                   13436: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
                   13437: operations the benefit of this optimization is even larger:
                   13438: floating-point operations take quite long on most processors, but can be
                   13439: performed in parallel with other operations as long as their results are
                   13440: not used. If the FP-TOS is kept in a register, this works. If
                   13441: it is kept on the stack, i.e., in memory, the store into memory has to
                   13442: wait for the result of the floating-point operation, lengthening the
                   13443: execution time of the primitive considerably.
                   13444: 
                   13445: The TOS optimization makes the automatic generation of primitives a
                   13446: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
                   13447: @code{TOS} is not sufficient. There are some special cases to
                   13448: consider:
                   13449: @itemize @bullet
                   13450: @item In the case of @code{dup ( w -- w w )} the generator must not
                   13451: eliminate the store to the original location of the item on the stack,
                   13452: if the TOS optimization is turned on.
                   13453: @item Primitives with stack effects of the form @code{--}
1.29      crook    13454: @i{out1}...@i{outy} must store the TOS to the stack at the start.
                   13455: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1       anton    13456: must load the TOS from the stack at the end. But for the null stack
                   13457: effect @code{--} no stores or loads should be generated.
                   13458: @end itemize
                   13459: 
                   13460: @node Produced code,  , TOS Optimization, Primitives
                   13461: @subsection Produced code
                   13462: @cindex primitives, assembly code listing
                   13463: 
                   13464: @cindex @file{engine.s}
                   13465: To see what assembly code is produced for the primitives on your machine
                   13466: with your compiler and your flag settings, type @code{make engine.s} and
                   13467: look at the resulting file @file{engine.s}.
                   13468: 
                   13469: @node  Performance,  , Primitives, Engine
                   13470: @section Performance
                   13471: @cindex performance of some Forth interpreters
                   13472: @cindex engine performance
                   13473: @cindex benchmarking Forth systems
                   13474: @cindex Gforth performance
                   13475: 
                   13476: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
                   13477: impossible to write a significantly faster engine.
                   13478: 
                   13479: On register-starved machines like the 386 architecture processors
                   13480: improvements are possible, because @code{gcc} does not utilize the
                   13481: registers as well as a human, even with explicit register declarations;
                   13482: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
                   13483: and hand-tuned it for the 486; this system is 1.19 times faster on the
                   13484: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40      anton    13485: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
                   13486: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
                   13487: registers fit in real registers (and we can even afford to use the TOS
                   13488: optimization), resulting in a speedup of 1.14 on the sieve over the
                   13489: earlier results.
1.1       anton    13490: 
                   13491: @cindex Win32Forth performance
                   13492: @cindex NT Forth performance
                   13493: @cindex eforth performance
                   13494: @cindex ThisForth performance
                   13495: @cindex PFE performance
                   13496: @cindex TILE performance
1.40      anton    13497: The potential advantage of assembly language implementations
1.1       anton    13498: is not necessarily realized in complete Forth systems: We compared
1.40      anton    13499: Gforth-0.4.9 (direct threaded, compiled with @code{gcc-2.95.1} and
1.1       anton    13500: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
                   13501: 1994) and Eforth (with and without peephole (aka pinhole) optimization
                   13502: of the threaded code); all these systems were written in assembly
                   13503: language. We also compared Gforth with three systems written in C:
                   13504: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
                   13505: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
1.21      crook    13506: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
                   13507: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
1.1       anton    13508: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
                   13509: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
                   13510: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
                   13511: 486DX2/66 with similar memory performance under Windows NT. Marcel
                   13512: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
                   13513: added the peephole optimizer, ran the benchmarks and reported the
                   13514: results.
1.40      anton    13515: 
1.1       anton    13516: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
                   13517: matrix multiplication come from the Stanford integer benchmarks and have
                   13518: been translated into Forth by Martin Fraeman; we used the versions
                   13519: included in the TILE Forth package, but with bigger data set sizes; and
                   13520: a recursive Fibonacci number computation for benchmarking calling
                   13521: performance. The following table shows the time taken for the benchmarks
                   13522: scaled by the time taken by Gforth (in other words, it shows the speedup
                   13523: factor that Gforth achieved over the other systems).
                   13524: 
                   13525: @example
1.40      anton    13526: relative      Win32-    NT       eforth       This-      
1.1       anton    13527:   time  Gforth Forth Forth eforth  +opt   PFE Forth  TILE
1.40      anton    13528: sieve     1.00  1.58  1.30   1.58  0.97  1.80  3.63  9.79
                   13529: bubble    1.00  1.55  1.67   1.75  1.04  1.78        4.59
                   13530: matmul    1.00  1.67  1.53   1.66  0.84  1.79        4.63
                   13531: fib       1.00  1.75  1.53   1.40  0.99  1.99  3.43  4.93
1.1       anton    13532: @end example
                   13533: 
1.26      crook    13534: You may be quite surprised by the good performance of Gforth when
                   13535: compared with systems written in assembly language. One important reason
                   13536: for the disappointing performance of these other systems is probably
                   13537: that they are not written optimally for the 486 (e.g., they use the
                   13538: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
                   13539: but costly method for relocating the Forth image: like @code{cforth}, it
                   13540: computes the actual addresses at run time, resulting in two address
                   13541: computations per @code{NEXT} (@pxref{Image File Background}).
                   13542: 
1.40      anton    13543: Only Eforth with the peephole optimizer performs comparable to
                   13544: Gforth. The speedups achieved with peephole optimization of threaded
                   13545: code are quite remarkable. Adding a peephole optimizer to Gforth should
                   13546: cause similar speedups.
1.1       anton    13547: 
                   13548: The speedup of Gforth over PFE, ThisForth and TILE can be easily
                   13549: explained with the self-imposed restriction of the latter systems to
                   13550: standard C, which makes efficient threading impossible (however, the
1.4       anton    13551: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1       anton    13552: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
                   13553: Moreover, current C compilers have a hard time optimizing other aspects
                   13554: of the ThisForth and the TILE source.
                   13555: 
1.26      crook    13556: The performance of Gforth on 386 architecture processors varies widely
                   13557: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
                   13558: allocate any of the virtual machine registers into real machine
                   13559: registers by itself and would not work correctly with explicit register
1.40      anton    13560: declarations, giving a 1.5 times slower engine (on a 486DX2/66 running
1.26      crook    13561: the Sieve) than the one measured above.
1.1       anton    13562: 
1.26      crook    13563: Note that there have been several releases of Win32Forth since the
                   13564: release presented here, so the results presented above may have little
1.40      anton    13565: predictive value for the performance of Win32Forth today (results for
                   13566: the current release on an i486DX2/66 are welcome).
1.1       anton    13567: 
                   13568: @cindex @file{Benchres}
                   13569: In @cite{Translating Forth to Efficient C} by M. Anton Ertl and Martin
                   13570: Maierhofer (presented at EuroForth '95), an indirect threaded version of
                   13571: Gforth is compared with Win32Forth, NT Forth, PFE, and ThisForth; that
1.40      anton    13572: version of Gforth is slower on a 486 than the direct threaded version
                   13573: used here. The paper available at
1.47      crook    13574: @*@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz};
1.1       anton    13575: it also contains numbers for some native code systems. You can find a
                   13576: newer version of these measurements at
1.47      crook    13577: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1       anton    13578: find numbers for Gforth on various machines in @file{Benchres}.
                   13579: 
1.26      crook    13580: @c ******************************************************************
1.13      pazsan   13581: @node Binding to System Library, Cross Compiler, Engine, Top
1.14      pazsan   13582: @chapter Binding to System Library
1.13      pazsan   13583: 
                   13584: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14      pazsan   13585: @chapter Cross Compiler
1.47      crook    13586: @cindex @file{cross.fs}
                   13587: @cindex cross-compiler
                   13588: @cindex metacompiler
                   13589: @cindex target compiler
1.13      pazsan   13590: 
1.46      pazsan   13591: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
                   13592: mostly written in Forth, including crucial parts like the outer
                   13593: interpreter and compiler, it needs compiled Forth code to get
                   13594: started. The cross compiler allows to create new images for other
                   13595: architectures, even running under another Forth system.
1.13      pazsan   13596: 
                   13597: @menu
                   13598: * Using the Cross Compiler::
                   13599: * How the Cross Compiler Works::
                   13600: @end menu
                   13601: 
1.21      crook    13602: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14      pazsan   13603: @section Using the Cross Compiler
1.46      pazsan   13604: 
                   13605: The cross compiler uses a language that resembles Forth, but isn't. The
                   13606: main difference is that you can execute Forth code after definition,
                   13607: while you usually can't execute the code compiled by cross, because the
                   13608: code you are compiling is typically for a different computer than the
                   13609: one you are compiling on.
                   13610: 
                   13611: The Makefile is already set up to allow you to create kernels for new
                   13612: architectures with a simple make command. The generic kernels using the
                   13613: GCC compiled virtual machine are created in the normal build process
                   13614: with @code{make}. To create a embedded Gforth executable for e.g. the
                   13615: 8086 processor (running on a DOS machine), type
                   13616: 
                   13617: @example
                   13618: make kernl-8086.fi
                   13619: @end example
                   13620: 
                   13621: This will use the machine description from the @file{arch/8086}
                   13622: directory to create a new kernel. A machine file may look like that:
                   13623: 
                   13624: @example
                   13625: \ Parameter for target systems                         06oct92py
                   13626: 
                   13627:     4 Constant cell             \ cell size in bytes
                   13628:     2 Constant cell<<           \ cell shift to bytes
                   13629:     5 Constant cell>bit         \ cell shift to bits
                   13630:     8 Constant bits/char        \ bits per character
                   13631:     8 Constant bits/byte        \ bits per byte [default: 8]
                   13632:     8 Constant float            \ bytes per float
                   13633:     8 Constant /maxalign        \ maximum alignment in bytes
                   13634: false Constant bigendian        \ byte order
                   13635: ( true=big, false=little )
                   13636: 
                   13637: include machpc.fs               \ feature list
                   13638: @end example
                   13639: 
                   13640: This part is obligatory for the cross compiler itself, the feature list
                   13641: is used by the kernel to conditionally compile some features in and out,
                   13642: depending on whether the target supports these features.
                   13643: 
                   13644: There are some optional features, if you define your own primitives,
                   13645: have an assembler, or need special, nonstandard preparation to make the
                   13646: boot process work. @code{asm-include} include an assembler,
                   13647: @code{prims-include} includes primitives, and @code{>boot} prepares for
                   13648: booting.
                   13649: 
                   13650: @example
                   13651: : asm-include    ." Include assembler" cr
                   13652:   s" arch/8086/asm.fs" included ;
                   13653: 
                   13654: : prims-include  ." Include primitives" cr
                   13655:   s" arch/8086/prim.fs" included ;
                   13656: 
                   13657: : >boot          ." Prepare booting" cr
                   13658:   s" ' boot >body into-forth 1+ !" evaluate ;
                   13659: @end example
                   13660: 
                   13661: These words are used as sort of macro during the cross compilation in
                   13662: the file @file{kernel/main.fs}. Instead of using this macros, it would
                   13663: be possible --- but more complicated --- to write a new kernel project
                   13664: file, too.
                   13665: 
                   13666: @file{kernel/main.fs} expects the machine description file name on the
                   13667: stack; the cross compiler itself (@file{cross.fs}) assumes that either
                   13668: @code{mach-file} leaves a counted string on the stack, or
                   13669: @code{machine-file} leaves an address, count pair of the filename on the
                   13670: stack.
                   13671: 
                   13672: The feature list is typically controlled using @code{SetValue}, generic
                   13673: files that are used by several projects can use @code{DefaultValue}
                   13674: instead. Both functions work like @code{Value}, when the value isn't
                   13675: defined, but @code{SetValue} works like @code{to} if the value is
                   13676: defined, and @code{DefaultValue} doesn't set anything, if the value is
                   13677: defined.
                   13678: 
                   13679: @example
                   13680: \ generic mach file for pc gforth                       03sep97jaw
                   13681: 
                   13682: true DefaultValue NIL  \ relocating
                   13683: 
                   13684: >ENVIRON
                   13685: 
                   13686: true DefaultValue file          \ controls the presence of the
                   13687:                                 \ file access wordset
                   13688: true DefaultValue OS            \ flag to indicate a operating system
                   13689: 
                   13690: true DefaultValue prims         \ true: primitives are c-code
                   13691: 
                   13692: true DefaultValue floating      \ floating point wordset is present
                   13693: 
                   13694: true DefaultValue glocals       \ gforth locals are present
                   13695:                                 \ will be loaded
                   13696: true DefaultValue dcomps        \ double number comparisons
                   13697: 
                   13698: true DefaultValue hash          \ hashing primitives are loaded/present
                   13699: 
                   13700: true DefaultValue xconds        \ used together with glocals,
                   13701:                                 \ special conditionals supporting gforths'
                   13702:                                 \ local variables
                   13703: true DefaultValue header        \ save a header information
                   13704: 
                   13705: true DefaultValue backtrace     \ enables backtrace code
                   13706: 
                   13707: false DefaultValue ec
                   13708: false DefaultValue crlf
                   13709: 
                   13710: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
                   13711: 
                   13712: &16 KB          DefaultValue stack-size
                   13713: &15 KB &512 +   DefaultValue fstack-size
                   13714: &15 KB          DefaultValue rstack-size
                   13715: &14 KB &512 +   DefaultValue lstack-size
                   13716: @end example
1.13      pazsan   13717: 
1.48    ! anton    13718: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
1.14      pazsan   13719: @section How the Cross Compiler Works
1.13      pazsan   13720: 
                   13721: @node Bugs, Origin, Cross Compiler, Top
1.21      crook    13722: @appendix Bugs
1.1       anton    13723: @cindex bug reporting
                   13724: 
1.21      crook    13725: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1       anton    13726: 
                   13727: If you find a bug, please send a bug report to
1.33      anton    13728: @email{bug-gforth@@gnu.org}. A bug report should include this
1.21      crook    13729: information:
                   13730: 
                   13731: @itemize @bullet
                   13732: @item
                   13733: The Gforth version used (it is announced at the start of an
                   13734: interactive Gforth session).
                   13735: @item
                   13736: The machine and operating system (on Unix
                   13737: systems @code{uname -a} will report this information).
                   13738: @item
                   13739: The installation options (send the file @file{config.status}).
                   13740: @item
                   13741: A complete list of changes (if any) you (or your installer) have made to the
                   13742: Gforth sources.
                   13743: @item
                   13744: A program (or a sequence of keyboard commands) that reproduces the bug.
                   13745: @item
                   13746: A description of what you think constitutes the buggy behaviour.
                   13747: @end itemize
1.1       anton    13748: 
                   13749: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
                   13750: to Report Bugs, gcc.info, GNU C Manual}.
                   13751: 
                   13752: 
1.21      crook    13753: @node Origin, Forth-related information, Bugs, Top
                   13754: @appendix Authors and Ancestors of Gforth
1.1       anton    13755: 
                   13756: @section Authors and Contributors
                   13757: @cindex authors of Gforth
                   13758: @cindex contributors to Gforth
                   13759: 
                   13760: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
                   13761: Ertl. The third major author was Jens Wilke.  Lennart Benschop (who was
                   13762: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
                   13763: with their continuous feedback. Lennart Benshop contributed
                   13764: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
                   13765: support for calling C libraries. Helpful comments also came from Paul
                   13766: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.12      anton    13767: Wavrik, Barrie Stott, Marc de Groot, and Jorge Acerada. Since the
                   13768: release of Gforth-0.2.1 there were also helpful comments from many
                   13769: others; thank you all, sorry for not listing you here (but digging
1.23      crook    13770: through my mailbox to extract your names is on my to-do list). Since the
                   13771: release of Gforth-0.4.0 Neal Crook worked on the manual.
1.1       anton    13772: 
                   13773: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
                   13774: and autoconf, among others), and to the creators of the Internet: Gforth
1.21      crook    13775: was developed across the Internet, and its authors did not meet
1.20      pazsan   13776: physically for the first 4 years of development.
1.1       anton    13777: 
                   13778: @section Pedigree
1.26      crook    13779: @cindex pedigree of Gforth
1.1       anton    13780: 
1.20      pazsan   13781: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
1.1       anton    13782: Dirk Zoller) will cross-fertilize each other. Of course, a significant
                   13783: part of the design of Gforth was prescribed by ANS Forth.
                   13784: 
1.20      pazsan   13785: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1       anton    13786: 32 bit native code version of VolksForth for the Atari ST, written
                   13787: mostly by Dietrich Weineck.
                   13788: 
                   13789: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
                   13790: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
                   13791: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
                   13792: 
                   13793: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
                   13794: Forth-83 standard. !! Pedigree? When?
                   13795: 
                   13796: A team led by Bill Ragsdale implemented fig-Forth on many processors in
                   13797: 1979. Robert Selzer and Bill Ragsdale developed the original
                   13798: implementation of fig-Forth for the 6502 based on microForth.
                   13799: 
                   13800: The principal architect of microForth was Dean Sanderson. microForth was
                   13801: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
                   13802: the 1802, and subsequently implemented on the 8080, the 6800 and the
                   13803: Z80.
                   13804: 
                   13805: All earlier Forth systems were custom-made, usually by Charles Moore,
                   13806: who discovered (as he puts it) Forth during the late 60s. The first full
                   13807: Forth existed in 1971.
                   13808: 
                   13809: A part of the information in this section comes from @cite{The Evolution
                   13810: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
                   13811: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
                   13812: Notices 28(3), 1993.  You can find more historical and genealogical
                   13813: information about Forth there.
                   13814: 
1.21      crook    13815: @node Forth-related information, Word Index, Origin, Top
                   13816: @appendix Other Forth-related information
                   13817: @cindex Forth-related information
                   13818: 
                   13819: @menu
                   13820: * Internet resources::
                   13821: * Books::
                   13822: * The Forth Interest Group::
                   13823: * Conferences::
                   13824: @end menu
                   13825: 
                   13826: 
                   13827: @node Internet resources, Books, Forth-related information, Forth-related information
                   13828: @section Internet resources
1.26      crook    13829: @cindex internet resources
1.21      crook    13830: 
                   13831: @cindex comp.lang.forth
                   13832: @cindex frequently asked questions
1.45      crook    13833: There is an active news group (comp.lang.forth) discussing Forth and
1.21      crook    13834: Forth-related issues. A frequently-asked-questions (FAQ) list
1.45      crook    13835: is posted to the news group regularly, and archived at these sites:
1.21      crook    13836: 
                   13837: @itemize @bullet
                   13838: @item
1.47      crook    13839: @uref{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
1.21      crook    13840: @item
1.47      crook    13841: @uref{ftp://ftp.forth.org/pub/Forth/FAQ/}
1.21      crook    13842: @end itemize
                   13843: 
                   13844: The FAQ list should be considered mandatory reading before posting to
1.45      crook    13845: the news group.
1.21      crook    13846: 
                   13847: Here are some other web sites holding Forth-related material:
                   13848: 
                   13849: @itemize @bullet
                   13850: @item
1.47      crook    13851: @uref{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
1.21      crook    13852: @item
1.47      crook    13853: @uref{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
1.21      crook    13854: @item
1.47      crook    13855: @uref{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
1.21      crook    13856: @item
1.47      crook    13857: @uref{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
1.21      crook    13858: Research page, including links to the Journal of Forth Application and
                   13859: Research (JFAR) and a searchable Forth bibliography.
                   13860: @end itemize
                   13861: 
                   13862: 
                   13863: @node Books, The Forth Interest Group, Internet resources, Forth-related information
                   13864: @section Books
1.26      crook    13865: @cindex books on Forth
1.21      crook    13866: 
                   13867: As the Standard is relatively new, there are not many books out yet. It
                   13868: is not recommended to learn Forth by using Gforth and a book that is not
                   13869: written for ANS Forth, as you will not know your mistakes from the
                   13870: deviations of the book. However, books based on the Forth-83 standard
                   13871: should be ok, because ANS Forth is primarily an extension of Forth-83.
1.44      crook    13872: Refer to the Forth FAQ for details of Forth-related books.
1.21      crook    13873: 
                   13874: @cindex standard document for ANS Forth
                   13875: @cindex ANS Forth document
                   13876: The definite reference if you want to write ANS Forth programs is, of
1.26      crook    13877: course, the ANS Forth document. It is available in printed form from the
1.21      crook    13878: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
                   13879: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
                   13880: $200. You can also get it from Global Engineering Documents (Tel.: USA
                   13881: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
                   13882: 
                   13883: @cite{dpANS6}, the last draft of the standard, which was then submitted
                   13884: to ANSI for publication is available electronically and for free in some
                   13885: MS Word format, and it has been converted to HTML
1.47      crook    13886: (@uref{http://www.taygeta.com/forth/dpans.html}; this HTML version also
1.44      crook    13887: includes the answers to Requests for Interpretation (RFIs). Some
                   13888: pointers to these versions can be found through
1.47      crook    13889: @*@uref{http://www.complang.tuwien.ac.at/projects/forth.html}.
1.44      crook    13890: 
1.21      crook    13891: 
                   13892: @node The Forth Interest Group, Conferences, Books, Forth-related information
                   13893: @section The Forth Interest Group
                   13894: @cindex Forth interest group (FIG)
                   13895: 
                   13896: The Forth Interest Group (FIG) is a world-wide, non-profit,
1.26      crook    13897: member-supported organisation. It publishes a regular magazine,
                   13898: @var{FORTH Dimensions}, and offers other benefits of membership. You can
                   13899: contact the FIG through their office email address:
                   13900: @email{office@@forth.org} or by visiting their web site at
1.47      crook    13901: @uref{http://www.forth.org/}. This web site also includes links to FIG
1.26      crook    13902: chapters in other countries and American cities
1.47      crook    13903: (@uref{http://www.forth.org/chapters.html}).
1.21      crook    13904: 
1.48    ! anton    13905: @node Conferences,  , The Forth Interest Group, Forth-related information
1.21      crook    13906: @section Conferences
                   13907: @cindex Conferences
                   13908: 
                   13909: There are several regular conferences related to Forth. They are all
1.26      crook    13910: well-publicised in @var{FORTH Dimensions} and on the comp.lang.forth
1.45      crook    13911: news group:
1.21      crook    13912: 
                   13913: @itemize @bullet
                   13914: @item
                   13915: FORML -- the Forth modification laboratory convenes every year near
                   13916: Monterey, California.
                   13917: @item
                   13918: The Rochester Forth Conference -- an annual conference traditionally
                   13919: held in Rochester, New York.
                   13920: @item
                   13921: EuroForth -- this European conference takes place annually.
                   13922: @end itemize
                   13923: 
                   13924: 
1.41      anton    13925: @node Word Index, Name Index, Forth-related information, Top
1.1       anton    13926: @unnumbered Word Index
                   13927: 
1.26      crook    13928: This index is a list of Forth words that have ``glossary'' entries
                   13929: within this manual. Each word is listed with its stack effect and
                   13930: wordset.
1.1       anton    13931: 
                   13932: @printindex fn
                   13933: 
1.41      anton    13934: @node Name Index, Concept Index, Word Index, Top
                   13935: @unnumbered Name Index
                   13936: 
                   13937: This index is a list of Forth words that have ``glossary'' entries
                   13938: within this manual.
                   13939: 
                   13940: @printindex ky
                   13941: 
                   13942: @node Concept Index,  , Name Index, Top
1.1       anton    13943: @unnumbered Concept and Word Index
                   13944: 
1.26      crook    13945: Not all entries listed in this index are present verbatim in the
                   13946: text. This index also duplicates, in abbreviated form, all of the words
                   13947: listed in the Word Index (only the names are listed for the words here).
1.1       anton    13948: 
                   13949: @printindex cp
                   13950: 
                   13951: @contents
                   13952: @bye
                   13953: 

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