File:  [gforth] / gforth / doc / gforth.ds
Revision 1.22: download - view: text, annotated - select for diffs
Wed Feb 3 23:32:22 1999 UTC (25 years, 2 months ago) by anton
Branches: MAIN
CVS tags: HEAD
fixed doc bugs

    1: \input texinfo   @c -*-texinfo-*-
    2: @comment The source is gforth.ds, from which gforth.texi is generated
    3: @comment TODO: nac29jan99 - a list of things to add in the next edit:
    4: @comment 1. x-ref all ambiguous or implementation-defined features
    5: @comment 2. refer to all environment strings
    6: @comment 3. gloss and info in blocks section
    7: @comment 4. move file and blocks to common sub-section?
    8: @comment 5. command-line editing, command completion etc.
    9: @comment 6. document more of the words in require.fs
   10: @comment 7. document the include files process (Describe the list,
   11: @comment    including its scope)
   12: @comment 8. Describe the use of Auser Avariable etc.
   13: @comment 9. cross-compiler
   14: @comment 10.words in miscellaneous section need a home.
   15: @comment 11.Move structures and oof into their own chapters.
   16: @comment 12.search for TODO for other minor works
   17: @comment %**start of header (This is for running Texinfo on a region.)
   18: @setfilename gforth.info
   19: @settitle Gforth Manual
   20: @dircategory GNU programming tools
   21: @direntry
   22: * Gforth: (gforth).             A fast interpreter for the Forth language.
   23: @end direntry
   24: @comment @setchapternewpage odd
   25: @macro progstyle {}
   26: Programming style note:
   27: @end macro
   28: @comment %**end of header (This is for running Texinfo on a region.)
   29: 
   30: @include version.texi
   31: 
   32: @ifinfo
   33: This file documents Gforth @value{VERSION}
   34: 
   35: Copyright @copyright{} 1995-1998 Free Software Foundation, Inc.
   36: 
   37:      Permission is granted to make and distribute verbatim copies of
   38:      this manual provided the copyright notice and this permission notice
   39:      are preserved on all copies.
   40:      
   41: @ignore
   42:      Permission is granted to process this file through TeX and print the
   43:      results, provided the printed document carries a copying permission
   44:      notice identical to this one except for the removal of this paragraph
   45:      (this paragraph not being relevant to the printed manual).
   46:      
   47: @end ignore
   48:      Permission is granted to copy and distribute modified versions of this
   49:      manual under the conditions for verbatim copying, provided also that the
   50:      sections entitled "Distribution" and "General Public License" are
   51:      included exactly as in the original, and provided that the entire
   52:      resulting derived work is distributed under the terms of a permission
   53:      notice identical to this one.
   54:      
   55:      Permission is granted to copy and distribute translations of this manual
   56:      into another language, under the above conditions for modified versions,
   57:      except that the sections entitled "Distribution" and "General Public
   58:      License" may be included in a translation approved by the author instead
   59:      of in the original English.
   60: @end ifinfo
   61: 
   62: @finalout
   63: @titlepage
   64: @sp 10
   65: @center @titlefont{Gforth Manual}
   66: @sp 2
   67: @center for version @value{VERSION}
   68: @sp 2
   69: @center Anton Ertl
   70: @center Bernd Paysan
   71: @center Jens Wilke
   72: @sp 3
   73: @center This manual is permanently under construction and was last updated on 18-Jan-1999
   74: 
   75: @comment  The following two commands start the copyright page.
   76: @page
   77: @vskip 0pt plus 1filll
   78: Copyright @copyright{} 1995--1998 Free Software Foundation, Inc.
   79: 
   80: @comment !! Published by ... or You can get a copy of this manual ...
   81: 
   82:      Permission is granted to make and distribute verbatim copies of
   83:      this manual provided the copyright notice and this permission notice
   84:      are preserved on all copies.
   85:      
   86:      Permission is granted to copy and distribute modified versions of this
   87:      manual under the conditions for verbatim copying, provided also that the
   88:      sections entitled "Distribution" and "General Public License" are
   89:      included exactly as in the original, and provided that the entire
   90:      resulting derived work is distributed under the terms of a permission
   91:      notice identical to this one.
   92:      
   93:      Permission is granted to copy and distribute translations of this manual
   94:      into another language, under the above conditions for modified versions,
   95:      except that the sections entitled "Distribution" and "General Public
   96:      License" may be included in a translation approved by the author instead
   97:      of in the original English.
   98: @end titlepage
   99: 
  100: 
  101: @node Top, License, (dir), (dir)
  102: @ifinfo
  103: Gforth is a free implementation of ANS Forth available on many
  104: personal machines. This manual corresponds to version @value{VERSION}.
  105: @end ifinfo
  106: 
  107: @menu
  108: * License::                     The GPL
  109: * Introduction::                An introduction to ANS Forth
  110: * Goals::                       About the Gforth Project
  111: * Invoking Gforth::             Starting (and exiting) Gforth
  112: * Words::                       Forth words available in Gforth
  113: * Tools::                       Programming tools
  114: * ANS conformance::             Implementation-defined options etc.
  115: * Model::                       The abstract machine of Gforth
  116: * Integrating Gforth::          Forth as scripting language for applications
  117: * Emacs and Gforth::            The Gforth Mode
  118: * Image Files::                 @code{.fi} files contain compiled code
  119: * Engine::                      The inner interpreter and the primitives
  120: * Cross Compiler::              The Cross Compiler
  121: * Bugs::                        How to report them
  122: * Origin::                      Authors and ancestors of Gforth
  123: * Forth-related information::   Books and places to look on the WWW
  124: * Word Index::                  An item for each Forth word
  125: * Concept Index::               A menu covering many topics
  126: 
  127:  --- The Detailed Node Listing ---
  128: 
  129: Goals
  130: 
  131: * Gforth Extensions Sinful?::
  132: 
  133: Forth Words
  134: 
  135: * Notation::                    
  136: * Comments::
  137: * Boolean Flags::
  138: * Arithmetic::                  
  139: * Stack Manipulation::          
  140: * Memory::                      
  141: * Control Structures::          
  142: * Locals::                      
  143: * Defining Words::              
  144: * The Text Interpreter::
  145: * Structures::                  
  146: * Object-oriented Forth::       
  147: * Tokens for Words::            
  148: * Word Lists::                   
  149: * Environmental Queries::
  150: * Files::                       
  151: * Including Files::             
  152: * Blocks::                      
  153: * Other I/O::                   
  154: * Programming Tools::           
  155: * Assembler and Code Words::    
  156: * Threading Words::             
  157: * Passing Commands to the OS::
  158: * Miscellaneous Words::
  159: 
  160: Arithmetic
  161: 
  162: * Single precision::            
  163: * Bitwise operations::          
  164: * Double precision::            Double-cell integer arithmetic
  165: * Numeric comparison::
  166: * Mixed precision::             operations with single and double-cell integers
  167: * Floating Point::              
  168: 
  169: Stack Manipulation
  170: 
  171: * Data stack::                  
  172: * Floating point stack::        
  173: * Return stack::                
  174: * Locals stack::                
  175: * Stack pointer manipulation::  
  176: 
  177: Memory
  178: 
  179: * Memory Access::      
  180: * Address arithmetic::          
  181: * Memory Blocks::         
  182: 
  183: Control Structures
  184: 
  185: * Selection::                   
  186: * Simple Loops::                
  187: * Counted Loops::               
  188: * Arbitrary control structures::  
  189: * Calls and returns::           
  190: * Exception Handling::          
  191: 
  192: Locals
  193: 
  194: * Gforth locals::               
  195: * ANS Forth locals::            
  196: 
  197: Gforth locals
  198: 
  199: * Where are locals visible by name?::  
  200: * How long do locals live?::    
  201: * Programming Style::           
  202: * Implementation::              
  203: 
  204: Defining Words
  205: 
  206: * Simple Defining Words::       
  207: * Colon Definitions::           
  208: * User-defined Defining Words::  
  209: * Supplying names::             
  210: * Interpretation and Compilation Semantics::  
  211: 
  212: The Text Interpreter
  213: 
  214: * Number Conversion::
  215: * Interpret/Compile states::
  216: * Literals::
  217: * Interpreter Directives::
  218: 
  219: Structures
  220: 
  221: * Why explicit structure support?::  
  222: * Structure Usage::             
  223: * Structure Naming Convention::  
  224: * Structure Implementation::    
  225: * Structure Glossary::          
  226: 
  227: Object-oriented Forth
  228: 
  229: * Objects::                     
  230: * OOF::                         
  231: * Mini-OOF::                    
  232: 
  233: Objects
  234: 
  235: * Properties of the Objects model::  
  236: * Why object-oriented programming?::  
  237: * Object-Oriented Terminology::  
  238: * Basic Objects Usage::         
  239: * The class Object::            
  240: * Creating objects::            
  241: * Object-Oriented Programming Style::  
  242: * Class Binding::               
  243: * Method conveniences::         
  244: * Classes and Scoping::         
  245: * Object Interfaces::           
  246: * Objects Implementation::      
  247: * Comparison with other object models::  
  248: * Objects Glossary::            
  249: 
  250: OOF
  251: 
  252: * Properties of the OOF model::
  253: * Basic OOF Usage::
  254: * The base class object::
  255: * Class Declaration::
  256: * Class Implementation::
  257: 
  258: Word Lists
  259: 
  260: * Why use word lists?::
  261: * Word list examples::
  262: 
  263: Including Files
  264: 
  265: * Words for Including::         
  266: * Search Path::                 
  267: * Forth Search Paths::    
  268: * General Search Paths::        
  269: 
  270: Other I/O
  271: 
  272: * Simple numeric output::
  273: * Formatted numeric output::
  274: * String Formats::
  275: * Displaying characters and strings::
  276: * Input::
  277: 
  278: Programming Tools
  279: 
  280: * Debugging::                   Simple and quick.
  281: * Assertions::                  Making your programs self-checking.
  282: * Singlestep Debugger::		Executing your program word by word.
  283: 
  284: Tools
  285: 
  286: * ANS Report::                  Report the words used, sorted by wordset.
  287: 
  288: ANS conformance
  289: 
  290: * The Core Words::              
  291: * The optional Block word set::  
  292: * The optional Double Number word set::  
  293: * The optional Exception word set::  
  294: * The optional Facility word set::  
  295: * The optional File-Access word set::  
  296: * The optional Floating-Point word set::  
  297: * The optional Locals word set::  
  298: * The optional Memory-Allocation word set::  
  299: * The optional Programming-Tools word set::  
  300: * The optional Search-Order word set::  
  301: 
  302: The Core Words
  303: 
  304: * core-idef::                   Implementation Defined Options                   
  305: * core-ambcond::                Ambiguous Conditions                
  306: * core-other::                  Other System Documentation                  
  307: 
  308: The optional Block word set
  309: 
  310: * block-idef::                  Implementation Defined Options
  311: * block-ambcond::               Ambiguous Conditions               
  312: * block-other::                 Other System Documentation                 
  313: 
  314: The optional Double Number word set
  315: 
  316: * double-ambcond::              Ambiguous Conditions              
  317: 
  318: The optional Exception word set
  319: 
  320: * exception-idef::              Implementation Defined Options              
  321: 
  322: The optional Facility word set
  323: 
  324: * facility-idef::               Implementation Defined Options               
  325: * facility-ambcond::            Ambiguous Conditions            
  326: 
  327: The optional File-Access word set
  328: 
  329: * file-idef::                   Implementation Defined Options
  330: * file-ambcond::                Ambiguous Conditions                
  331: 
  332: The optional Floating-Point word set
  333: 
  334: * floating-idef::               Implementation Defined Options
  335: * floating-ambcond::            Ambiguous Conditions            
  336: 
  337: The optional Locals word set
  338: 
  339: * locals-idef::                 Implementation Defined Options                 
  340: * locals-ambcond::              Ambiguous Conditions              
  341: 
  342: The optional Memory-Allocation word set
  343: 
  344: * memory-idef::                 Implementation Defined Options                 
  345: 
  346: The optional Programming-Tools word set
  347: 
  348: * programming-idef::            Implementation Defined Options            
  349: * programming-ambcond::         Ambiguous Conditions         
  350: 
  351: The optional Search-Order word set
  352: 
  353: * search-idef::                 Implementation Defined Options                 
  354: * search-ambcond::              Ambiguous Conditions              
  355: 
  356: Image Files
  357: 
  358: * Image File Background::          Why have image files?
  359: * Non-Relocatable Image Files::    don't always work.
  360: * Data-Relocatable Image Files::   are better.
  361: * Fully Relocatable Image Files::  better yet.
  362: * Stack and Dictionary Sizes::     Setting the default sizes for an image.
  363: * Running Image Files::            @code{gforth -i @var{file}} or @var{file}.
  364: * Modifying the Startup Sequence:: and turnkey applications.
  365: 
  366: Fully Relocatable Image Files
  367: 
  368: * gforthmi::                    The normal way
  369: * cross.fs::                    The hard way
  370: 
  371: Engine
  372: 
  373: * Portability::                 
  374: * Threading::                   
  375: * Primitives::                  
  376: * Performance::                 
  377: 
  378: Threading
  379: 
  380: * Scheduling::                  
  381: * Direct or Indirect Threaded?::  
  382: * DOES>::                       
  383: 
  384: Primitives
  385: 
  386: * Automatic Generation::        
  387: * TOS Optimization::            
  388: * Produced code::               
  389: 
  390: System Libraries
  391: 
  392: * Binding to System Library::
  393: 
  394: Cross Compiler
  395: 
  396: * Using the Cross Compiler::
  397: * How the Cross Compiler Works::
  398: 
  399: Forth-related information
  400: 
  401: * Internet resources::
  402: * Books::
  403: * The Forth Interest Group::
  404: * Conferences::
  405: 
  406: 
  407: 
  408: @end menu
  409: 
  410: @node License, Introduction, Top, Top
  411: @unnumbered GNU GENERAL PUBLIC LICENSE
  412: @center Version 2, June 1991
  413: 
  414: @display
  415: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
  416: 675 Mass Ave, Cambridge, MA 02139, USA
  417: 
  418: Everyone is permitted to copy and distribute verbatim copies
  419: of this license document, but changing it is not allowed.
  420: @end display
  421: 
  422: @unnumberedsec Preamble
  423: 
  424:   The licenses for most software are designed to take away your
  425: freedom to share and change it.  By contrast, the GNU General Public
  426: License is intended to guarantee your freedom to share and change free
  427: software---to make sure the software is free for all its users.  This
  428: General Public License applies to most of the Free Software
  429: Foundation's software and to any other program whose authors commit to
  430: using it.  (Some other Free Software Foundation software is covered by
  431: the GNU Library General Public License instead.)  You can apply it to
  432: your programs, too.
  433: 
  434:   When we speak of free software, we are referring to freedom, not
  435: price.  Our General Public Licenses are designed to make sure that you
  436: have the freedom to distribute copies of free software (and charge for
  437: this service if you wish), that you receive source code or can get it
  438: if you want it, that you can change the software or use pieces of it
  439: in new free programs; and that you know you can do these things.
  440: 
  441:   To protect your rights, we need to make restrictions that forbid
  442: anyone to deny you these rights or to ask you to surrender the rights.
  443: These restrictions translate to certain responsibilities for you if you
  444: distribute copies of the software, or if you modify it.
  445: 
  446:   For example, if you distribute copies of such a program, whether
  447: gratis or for a fee, you must give the recipients all the rights that
  448: you have.  You must make sure that they, too, receive or can get the
  449: source code.  And you must show them these terms so they know their
  450: rights.
  451: 
  452:   We protect your rights with two steps: (1) copyright the software, and
  453: (2) offer you this license which gives you legal permission to copy,
  454: distribute and/or modify the software.
  455: 
  456:   Also, for each author's protection and ours, we want to make certain
  457: that everyone understands that there is no warranty for this free
  458: software.  If the software is modified by someone else and passed on, we
  459: want its recipients to know that what they have is not the original, so
  460: that any problems introduced by others will not reflect on the original
  461: authors' reputations.
  462: 
  463:   Finally, any free program is threatened constantly by software
  464: patents.  We wish to avoid the danger that redistributors of a free
  465: program will individually obtain patent licenses, in effect making the
  466: program proprietary.  To prevent this, we have made it clear that any
  467: patent must be licensed for everyone's free use or not licensed at all.
  468: 
  469:   The precise terms and conditions for copying, distribution and
  470: modification follow.
  471: 
  472: @iftex
  473: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  474: @end iftex
  475: @ifinfo
  476: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  477: @end ifinfo
  478: 
  479: @enumerate 0
  480: @item
  481: This License applies to any program or other work which contains
  482: a notice placed by the copyright holder saying it may be distributed
  483: under the terms of this General Public License.  The ``Program'', below,
  484: refers to any such program or work, and a ``work based on the Program''
  485: means either the Program or any derivative work under copyright law:
  486: that is to say, a work containing the Program or a portion of it,
  487: either verbatim or with modifications and/or translated into another
  488: language.  (Hereinafter, translation is included without limitation in
  489: the term ``modification''.)  Each licensee is addressed as ``you''.
  490: 
  491: Activities other than copying, distribution and modification are not
  492: covered by this License; they are outside its scope.  The act of
  493: running the Program is not restricted, and the output from the Program
  494: is covered only if its contents constitute a work based on the
  495: Program (independent of having been made by running the Program).
  496: Whether that is true depends on what the Program does.
  497: 
  498: @item
  499: You may copy and distribute verbatim copies of the Program's
  500: source code as you receive it, in any medium, provided that you
  501: conspicuously and appropriately publish on each copy an appropriate
  502: copyright notice and disclaimer of warranty; keep intact all the
  503: notices that refer to this License and to the absence of any warranty;
  504: and give any other recipients of the Program a copy of this License
  505: along with the Program.
  506: 
  507: You may charge a fee for the physical act of transferring a copy, and
  508: you may at your option offer warranty protection in exchange for a fee.
  509: 
  510: @item
  511: You may modify your copy or copies of the Program or any portion
  512: of it, thus forming a work based on the Program, and copy and
  513: distribute such modifications or work under the terms of Section 1
  514: above, provided that you also meet all of these conditions:
  515: 
  516: @enumerate a
  517: @item
  518: You must cause the modified files to carry prominent notices
  519: stating that you changed the files and the date of any change.
  520: 
  521: @item
  522: You must cause any work that you distribute or publish, that in
  523: whole or in part contains or is derived from the Program or any
  524: part thereof, to be licensed as a whole at no charge to all third
  525: parties under the terms of this License.
  526: 
  527: @item
  528: If the modified program normally reads commands interactively
  529: when run, you must cause it, when started running for such
  530: interactive use in the most ordinary way, to print or display an
  531: announcement including an appropriate copyright notice and a
  532: notice that there is no warranty (or else, saying that you provide
  533: a warranty) and that users may redistribute the program under
  534: these conditions, and telling the user how to view a copy of this
  535: License.  (Exception: if the Program itself is interactive but
  536: does not normally print such an announcement, your work based on
  537: the Program is not required to print an announcement.)
  538: @end enumerate
  539: 
  540: These requirements apply to the modified work as a whole.  If
  541: identifiable sections of that work are not derived from the Program,
  542: and can be reasonably considered independent and separate works in
  543: themselves, then this License, and its terms, do not apply to those
  544: sections when you distribute them as separate works.  But when you
  545: distribute the same sections as part of a whole which is a work based
  546: on the Program, the distribution of the whole must be on the terms of
  547: this License, whose permissions for other licensees extend to the
  548: entire whole, and thus to each and every part regardless of who wrote it.
  549: 
  550: Thus, it is not the intent of this section to claim rights or contest
  551: your rights to work written entirely by you; rather, the intent is to
  552: exercise the right to control the distribution of derivative or
  553: collective works based on the Program.
  554: 
  555: In addition, mere aggregation of another work not based on the Program
  556: with the Program (or with a work based on the Program) on a volume of
  557: a storage or distribution medium does not bring the other work under
  558: the scope of this License.
  559: 
  560: @item
  561: You may copy and distribute the Program (or a work based on it,
  562: under Section 2) in object code or executable form under the terms of
  563: Sections 1 and 2 above provided that you also do one of the following:
  564: 
  565: @enumerate a
  566: @item
  567: Accompany it with the complete corresponding machine-readable
  568: source code, which must be distributed under the terms of Sections
  569: 1 and 2 above on a medium customarily used for software interchange; or,
  570: 
  571: @item
  572: Accompany it with a written offer, valid for at least three
  573: years, to give any third party, for a charge no more than your
  574: cost of physically performing source distribution, a complete
  575: machine-readable copy of the corresponding source code, to be
  576: distributed under the terms of Sections 1 and 2 above on a medium
  577: customarily used for software interchange; or,
  578: 
  579: @item
  580: Accompany it with the information you received as to the offer
  581: to distribute corresponding source code.  (This alternative is
  582: allowed only for noncommercial distribution and only if you
  583: received the program in object code or executable form with such
  584: an offer, in accord with Subsection b above.)
  585: @end enumerate
  586: 
  587: The source code for a work means the preferred form of the work for
  588: making modifications to it.  For an executable work, complete source
  589: code means all the source code for all modules it contains, plus any
  590: associated interface definition files, plus the scripts used to
  591: control compilation and installation of the executable.  However, as a
  592: special exception, the source code distributed need not include
  593: anything that is normally distributed (in either source or binary
  594: form) with the major components (compiler, kernel, and so on) of the
  595: operating system on which the executable runs, unless that component
  596: itself accompanies the executable.
  597: 
  598: If distribution of executable or object code is made by offering
  599: access to copy from a designated place, then offering equivalent
  600: access to copy the source code from the same place counts as
  601: distribution of the source code, even though third parties are not
  602: compelled to copy the source along with the object code.
  603: 
  604: @item
  605: You may not copy, modify, sublicense, or distribute the Program
  606: except as expressly provided under this License.  Any attempt
  607: otherwise to copy, modify, sublicense or distribute the Program is
  608: void, and will automatically terminate your rights under this License.
  609: However, parties who have received copies, or rights, from you under
  610: this License will not have their licenses terminated so long as such
  611: parties remain in full compliance.
  612: 
  613: @item
  614: You are not required to accept this License, since you have not
  615: signed it.  However, nothing else grants you permission to modify or
  616: distribute the Program or its derivative works.  These actions are
  617: prohibited by law if you do not accept this License.  Therefore, by
  618: modifying or distributing the Program (or any work based on the
  619: Program), you indicate your acceptance of this License to do so, and
  620: all its terms and conditions for copying, distributing or modifying
  621: the Program or works based on it.
  622: 
  623: @item
  624: Each time you redistribute the Program (or any work based on the
  625: Program), the recipient automatically receives a license from the
  626: original licensor to copy, distribute or modify the Program subject to
  627: these terms and conditions.  You may not impose any further
  628: restrictions on the recipients' exercise of the rights granted herein.
  629: You are not responsible for enforcing compliance by third parties to
  630: this License.
  631: 
  632: @item
  633: If, as a consequence of a court judgment or allegation of patent
  634: infringement or for any other reason (not limited to patent issues),
  635: conditions are imposed on you (whether by court order, agreement or
  636: otherwise) that contradict the conditions of this License, they do not
  637: excuse you from the conditions of this License.  If you cannot
  638: distribute so as to satisfy simultaneously your obligations under this
  639: License and any other pertinent obligations, then as a consequence you
  640: may not distribute the Program at all.  For example, if a patent
  641: license would not permit royalty-free redistribution of the Program by
  642: all those who receive copies directly or indirectly through you, then
  643: the only way you could satisfy both it and this License would be to
  644: refrain entirely from distribution of the Program.
  645: 
  646: If any portion of this section is held invalid or unenforceable under
  647: any particular circumstance, the balance of the section is intended to
  648: apply and the section as a whole is intended to apply in other
  649: circumstances.
  650: 
  651: It is not the purpose of this section to induce you to infringe any
  652: patents or other property right claims or to contest validity of any
  653: such claims; this section has the sole purpose of protecting the
  654: integrity of the free software distribution system, which is
  655: implemented by public license practices.  Many people have made
  656: generous contributions to the wide range of software distributed
  657: through that system in reliance on consistent application of that
  658: system; it is up to the author/donor to decide if he or she is willing
  659: to distribute software through any other system and a licensee cannot
  660: impose that choice.
  661: 
  662: This section is intended to make thoroughly clear what is believed to
  663: be a consequence of the rest of this License.
  664: 
  665: @item
  666: If the distribution and/or use of the Program is restricted in
  667: certain countries either by patents or by copyrighted interfaces, the
  668: original copyright holder who places the Program under this License
  669: may add an explicit geographical distribution limitation excluding
  670: those countries, so that distribution is permitted only in or among
  671: countries not thus excluded.  In such case, this License incorporates
  672: the limitation as if written in the body of this License.
  673: 
  674: @item
  675: The Free Software Foundation may publish revised and/or new versions
  676: of the General Public License from time to time.  Such new versions will
  677: be similar in spirit to the present version, but may differ in detail to
  678: address new problems or concerns.
  679: 
  680: Each version is given a distinguishing version number.  If the Program
  681: specifies a version number of this License which applies to it and ``any
  682: later version'', you have the option of following the terms and conditions
  683: either of that version or of any later version published by the Free
  684: Software Foundation.  If the Program does not specify a version number of
  685: this License, you may choose any version ever published by the Free Software
  686: Foundation.
  687: 
  688: @item
  689: If you wish to incorporate parts of the Program into other free
  690: programs whose distribution conditions are different, write to the author
  691: to ask for permission.  For software which is copyrighted by the Free
  692: Software Foundation, write to the Free Software Foundation; we sometimes
  693: make exceptions for this.  Our decision will be guided by the two goals
  694: of preserving the free status of all derivatives of our free software and
  695: of promoting the sharing and reuse of software generally.
  696: 
  697: @iftex
  698: @heading NO WARRANTY
  699: @end iftex
  700: @ifinfo
  701: @center NO WARRANTY
  702: @end ifinfo
  703: 
  704: @item
  705: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
  706: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
  707: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
  708: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
  709: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  710: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
  711: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
  712: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
  713: REPAIR OR CORRECTION.
  714: 
  715: @item
  716: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
  717: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
  718: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
  719: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
  720: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
  721: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
  722: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
  723: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
  724: POSSIBILITY OF SUCH DAMAGES.
  725: @end enumerate
  726: 
  727: @iftex
  728: @heading END OF TERMS AND CONDITIONS
  729: @end iftex
  730: @ifinfo
  731: @center END OF TERMS AND CONDITIONS
  732: @end ifinfo
  733: 
  734: @page
  735: @unnumberedsec How to Apply These Terms to Your New Programs
  736: 
  737:   If you develop a new program, and you want it to be of the greatest
  738: possible use to the public, the best way to achieve this is to make it
  739: free software which everyone can redistribute and change under these terms.
  740: 
  741:   To do so, attach the following notices to the program.  It is safest
  742: to attach them to the start of each source file to most effectively
  743: convey the exclusion of warranty; and each file should have at least
  744: the ``copyright'' line and a pointer to where the full notice is found.
  745: 
  746: @smallexample
  747: @var{one line to give the program's name and a brief idea of what it does.}
  748: Copyright (C) 19@var{yy}  @var{name of author}
  749: 
  750: This program is free software; you can redistribute it and/or modify 
  751: it under the terms of the GNU General Public License as published by 
  752: the Free Software Foundation; either version 2 of the License, or 
  753: (at your option) any later version.
  754: 
  755: This program is distributed in the hope that it will be useful,
  756: but WITHOUT ANY WARRANTY; without even the implied warranty of
  757: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  758: GNU General Public License for more details.
  759: 
  760: You should have received a copy of the GNU General Public License
  761: along with this program; if not, write to the Free Software
  762: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  763: @end smallexample
  764: 
  765: Also add information on how to contact you by electronic and paper mail.
  766: 
  767: If the program is interactive, make it output a short notice like this
  768: when it starts in an interactive mode:
  769: 
  770: @smallexample
  771: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
  772: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
  773: type `show w'.  
  774: This is free software, and you are welcome to redistribute it 
  775: under certain conditions; type `show c' for details.
  776: @end smallexample
  777: 
  778: The hypothetical commands @samp{show w} and @samp{show c} should show
  779: the appropriate parts of the General Public License.  Of course, the
  780: commands you use may be called something other than @samp{show w} and
  781: @samp{show c}; they could even be mouse-clicks or menu items---whatever
  782: suits your program.
  783: 
  784: You should also get your employer (if you work as a programmer) or your
  785: school, if any, to sign a ``copyright disclaimer'' for the program, if
  786: necessary.  Here is a sample; alter the names:
  787: 
  788: @smallexample
  789: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  790: `Gnomovision' (which makes passes at compilers) written by James Hacker.
  791: 
  792: @var{signature of Ty Coon}, 1 April 1989
  793: Ty Coon, President of Vice
  794: @end smallexample
  795: 
  796: This General Public License does not permit incorporating your program into
  797: proprietary programs.  If your program is a subroutine library, you may
  798: consider it more useful to permit linking proprietary applications with the
  799: library.  If this is what you want to do, use the GNU Library General
  800: Public License instead of this License.
  801: 
  802: @iftex
  803: @unnumbered Preface
  804: @cindex Preface
  805: This manual documents Gforth. Some introductory material is provided for
  806: readers who are unfamiliar with Forth or who are migrating to Gforth
  807: from other Forth compilers. However, this manual is primarily a
  808: reference manual.
  809: @end iftex
  810: 
  811: @c ----------------------------------------------------------
  812: @node    Introduction, Goals, License, Top
  813: @comment node-name,     next,           previous, up
  814: @chapter An Introduction to ANS Forth
  815: @cindex Forth - an introduction
  816: 
  817: The primary purpose of this manual is to document Gforth. However, since
  818: Forth is not a widely-known language and there is a lack of up-to-date
  819: teaching material, it seems worthwhile to provide some introductory
  820: material. @xref{Forth-related information} for other sources of Forth-related
  821: information.
  822: 
  823: The examples in this section should work on any ANS Standard Forth, the
  824: output shown was produced using Gforth. In each example, I have tried to
  825: reproduce the exact output that Gforth produces. If you try out the
  826: examples (and you should), what you should type is shown @kbd{like this}
  827: and Gforth's response is shown @code{like this}. The single exception is
  828: that, where the example shows @kbd{<return>} it means that you should
  829: press the "carriage return" key. Unfortunatley, some output formats for
  830: this manual cannot show the difference between @kbd{this} and
  831: @code{this} which will make trying out the examples harder (but not
  832: impossible).
  833: 
  834: Forth is an unusual language. It provides an interactive development
  835: environment which includes both an interpreter and compiler. Forth
  836: programming style encourages you to break a problem down into many
  837: @cindex factoring
  838: small fragments (@var{factoring}), and then to develop and test each
  839: fragment interactively. Forth advocates assert that breaking the
  840: edit-compile-test cycle used by conventional programming languages can
  841: lead to great productivity improvements.
  842: 
  843: @menu
  844: * Introducing the Text Interpreter::
  845: * Stacks and Postfix notation::
  846: * Your first definition::
  847: * How does that work?::
  848: * Forth is written in Forth::
  849: * Classifying Forth words::
  850: * Review - elements of a Forth system::
  851: * Exercises::
  852: @end menu
  853: @comment TODO add these sections to the top xref lists
  854: 
  855: @comment ----------------------------------------------
  856: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
  857: @section Introducing the Text Interpreter
  858: @cindex text interpreter
  859: @cindex outer interpreter
  860: 
  861: When you invoke the Forth image, you will see a startup banner printed
  862: and nothing else (if you have Gforth installed on your system, try
  863: invoking it now, by typing @kbd{gforth<return>}). Forth is now running
  864: its command line interpreter, which is called the @var{Text Interpreter}
  865: (also known as the @var{Outer Interpreter}).  (@pxref{The Text
  866: Interpreter} describes it in more detail, but we will learn more about
  867: its behaviour as we go through this chapter).
  868: 
  869: Although it may not be obvious, Forth is actually waiting for your
  870: input. Type a number and press the <return> key:
  871: 
  872: @example
  873: @kbd{45<return>}  ok
  874: @end example
  875: 
  876: Rather than give you a prompt to invite you to input something, the text
  877: interpreter prints a status message @var{after} it has processed a line
  878: of input. The status message in this case (" ok" followed by
  879: carriage-return) indicates that the text interpreter was able to process
  880: all of your input successfully. Now type something illegal:
  881: 
  882: @example
  883: @kbd{qwer341<return>}
  884: ^^^^^^^
  885: Error: Undefined word
  886: @end example
  887: 
  888: When the text interpreter detects an error, it discards any remaining
  889: text on a line, resets certain internal state and prints an error
  890: message.
  891: 
  892: The text interpreter works on input one line at a time. Starting at
  893: the beginning of the line, it breaks the line into groups of characters
  894: separated by spaces. For each group of characters in turn, it makes two
  895: attempts to do something:
  896: 
  897: @itemize @bullet
  898: @item
  899: It tries to treat it as a command. It does this by searching a @var{name
  900: dictionary}. If the group of characters matches an entry in the name
  901: dictionary, the name dictionary provides the text interpreter with
  902: information that allows the text interpreter perform some actions. In
  903: Forth jargon, we say that the group
  904: @cindex word
  905: @cindex definition
  906: @cindex execution token
  907: @cindex xt
  908: of characters names a @var{word}, that the dictionary search returns an
  909: @var{execution token (xt)} corresponding to the @var{definition} of the
  910: word, and that the text interpreter executes the xt. Often, the terms
  911: @var{word} and @var{definition} are used interchangeably.
  912: @item
  913: If the text interpreter fails to find a match in the name dictionary, it
  914: tries to treat the group of characters as a number in the current number
  915: base (when you start up Forth, the current number base is base 10). If
  916: the group of characters legitimately represents a number, the text
  917: interpreter pushes the number onto a stack (we'll learn more about that
  918: in the next section).
  919: @end itemize
  920: 
  921: If the text interpreter is unable to do either of these things with any
  922: group of characters, it discards the rest of the line and print an error
  923: message. If the text interpreter reaches the end of the line without
  924: error, it prints the status message " ok" followed by carriage-return.
  925: 
  926: This is the simplest command we can give to the text interpreter:
  927: 
  928: @example
  929: @kbd{<return>}  ok
  930: @end example
  931: 
  932: The text interpreter did everything we asked it to do (nothing) without
  933: an error, so it said that everything is "ok". Try a slightly longer
  934: command:
  935: 
  936: @example
  937: @kbd{12 dup fred dup<return>}
  938:        ^^^^
  939: Error: Undefined word
  940: @end example
  941: 
  942: When you pres the <return> key, the text interpreter starts to work its
  943: way along the line.
  944: 
  945: @itemize @bullet
  946: @item
  947: When it gets to the space after the @code{2}, it takes the group of
  948: characters @code{12} and looks them up in the name
  949: dictionary@footnote{We can't tell if it found them or not, but assume
  950: for now that it did not}. There is no match for this group of characters
  951: in the name dictionary, so it tries to treat them as a number. It is
  952: able to do this successfully, so it puts the number, 12, "on the stack"
  953: (whatever that means).
  954: @item
  955: The text interpreter resumes scanning the line and gets the next group
  956: of characters, @code{dup}. It looks them up in the name dictionary and
  957: (you'll have to take my word for this) finds them, and executes the word
  958: @code{dup} (whatever that means).
  959: @item
  960: Once again, the text interpreter resumes scanning the line and gets the
  961: group of characters @code{fred}. It looks them up in the name
  962: dictionary, but can't find them. It tries to treat them as a number, but
  963: they don't represent any legal number.
  964: @end itemize
  965: 
  966: At this point, the text interpreter gives up and prints an error
  967: message. The error message shows exactly how far the text interpreter
  968: got in processing the line. In particular, it shows that the text
  969: interpreter made no attempt to do anything with the final character
  970: group, @code{dup}, even though we have good reason to believe that the
  971: text interpreter would have had no problems with looking that word up
  972: and executing it a second time.
  973: 
  974: 
  975: @comment ----------------------------------------------
  976: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
  977: @section Stacks, postfix notation and parameter passing
  978: @cindex text interpreter
  979: @cindex outer interpreter
  980: 
  981: In procedural programming languages (like C and Pascal), the
  982: building-block of programs is the function or procedure. These
  983: functions or procedures are called with explicit parameters. For
  984: example, in C we might write:
  985: 
  986: @example
  987: total = total + new_volume(length,height,depth);
  988: @end example
  989: 
  990: where total, length, height, depth are all variables and new_volume is
  991: a function-call to another piece of code.
  992: 
  993: In Forth, the equivalent to the function or procedure is the
  994: @var{definition} and parameters are implicitly passed between
  995: definitions using a shared stack that is visible to the
  996: programmer. Although Forth does support variables, the existence of the
  997: stack means that they are used far less often than in most other
  998: programming languages. When the text interpreter encounters a number, it
  999: will place (@var{push}) it on the stack. There are several stacks (the
 1000: actual number is implementation-dependent ..) and the particular stack
 1001: used for any operation is implied unambiguously by the operation being
 1002: performed. The stack used for all integer operations is called the @var{data
 1003: stack} and, since this is the stack used most commonly, references to
 1004: "the data stack" are often abbreviated to "the stack".
 1005: 
 1006: The stacks have a last-in, first-out (LIFO) organisation. If you type:
 1007: 
 1008: @example
 1009: @kbd{1 2 3<return>}  ok
 1010: @end example
 1011: 
 1012: Then you (well, the text interpreter, really) have placed three numbers
 1013: on the (data) stack. An analogy for the behaviour of the stack is to
 1014: take a pack of playing cards and deal out the ace (1), 2 and 3 into a
 1015: pile on the table. The 3 was the last card onto the pile ("last-in") and
 1016: if you take a card off the pile then, unless you're prepared to fiddle a
 1017: bit, the card that you take off will be the 3 ("first-out"). The number
 1018: that will be first-out of the stack is called the "top of stack", which
 1019: is often abbreviated to @var{TOS}.
 1020: 
 1021: To see how parameters are passed in Forth, we will consider the
 1022: behaviour of the definition @code{+} (pronounced "plus"). You will not be
 1023: surprised to learn that this definition performs addition. More
 1024: precisely, it adds two number together and produces a result. Where does
 1025: it get the two numbers from? It takes the first two numbers off the
 1026: stack. Where does it place the result? On the stack. You can act-out the
 1027: behaviour of @code{+} with your playing cards like this:
 1028: 
 1029: @itemize @bullet
 1030: @item
 1031: Pick up two cards from the stack
 1032: @item
 1033: Stare at them intently and ask yourself "what *is* the sum of these two
 1034: numbers"
 1035: @item
 1036: Decide that the answer is 5
 1037: @item
 1038: Shuffle the two cards back into the pack and find a 5
 1039: @item
 1040: Put a 5 on the remaining ace that's on the table.
 1041: @end itemize
 1042: 
 1043: If you don't have a pack of cards handy but you do have Forth running,
 1044: you can use the definition .s to show the current state of the stack,
 1045: without affecting the stack. Type:
 1046: 
 1047: @example
 1048: @kbd{clearstack 1 2 3<return>} ok
 1049: @kbd{.s<return> <3> 1 2 3 } ok
 1050: @end example
 1051: 
 1052: The text interpreter looks up the word @code{clearstack} and executes
 1053: it; it tidies up the stack and removes any entries that may have been
 1054: left on it by earlier examples. The text interpreter pushes each of the
 1055: three numbers in turn onto the stack. Finally, the text interpreter
 1056: looks up the word @code{.s} and executes it. The effect of executing
 1057: @code{.s} is to print the "<3>" (the total number of items on the stack)
 1058: followed by a list of all the items and the item on the far right-hand
 1059: side is the TOS.
 1060: 
 1061: You can now type:
 1062: 
 1063: + .s<return> <2> 1 5  ok
 1064: 
 1065: which is correct; there are now 2 items on the stack and the result of
 1066: the addition is 5.
 1067: 
 1068: If you're playing with cards, try doing a second addition; pick up the
 1069: two cards, work out that their sum is 6, shuffle them into the pack,
 1070: look for a 6 and place that on the table. You now have just one item
 1071: on the stack. What happens if you try to do a third addition? Pick up
 1072: the first card, pick up the second card - ah. There is no second
 1073: card. This is called a "stack underflow" and consitutes an error. If
 1074: you try to do the same thing with Forth it will report an error
 1075: (probably a Stack Underflow or an Invalid Memory Address error).
 1076: 
 1077: The opposite situation to a stack underflow is a stack overflow, which
 1078: simply accepts that there is a finite amount of storage space reserved
 1079: for the stack. To stretch the playing card analogy, if you had enough
 1080: packs of cards and you piled the cards up on the table, you would
 1081: eventually be unable to add another card; you'd hit the
 1082: ceiling. Gforth allows you to set the maximum size of the stacks. In
 1083: general, the only time that you will get a stack overflow is because a
 1084: definition has a bug in it and is generating data on the stack
 1085: uncontrollably.
 1086: 
 1087: There's one final use for the playing card analogy. If you model your
 1088: stack using a pack of playing cards, the maximum number of items on
 1089: your stack will be 52 (I assume you didn't use the Joker). The maximum
 1090: *value* of any item on the stack is 13 (the King). In fact, the only
 1091: possible numbers are positive integer numbers 1 through 13; you can't
 1092: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
 1093: think about some of the cards, you can accommodate different
 1094: numbers. For example, you could think of the Jack as representing 0,
 1095: the Queen as representing -1 and the King as representing -2. Your
 1096: *range* remains unchanged (you can still only represent a total of 13
 1097: numbers) but the numbers that you can represent are -2 through 10.
 1098: 
 1099: In that analogy, the limit was the amount of information that a single
 1100: stack entry could hold, and Forth has a similar limit. In Forth, the
 1101: size of a stack entry is called a "cell". The actual size of a cell is
 1102: implementation dependent and affects the maximum value that a stack
 1103: entry can hold. A Standard Forth provides a cell size of at least
 1104: 16-bits, and most desktop systems use a cell size of 32-bits.
 1105: 
 1106: Forth does not do any type checking for you, so you are free to
 1107: manipulate and combine stack items in any way you wish. A convenient
 1108: ways of treating stack items is as 2's complement signed integers, and
 1109: that is what Standard words like "+" do. Therefore you can type:
 1110: 
 1111: -5 12 + .s<return> <1> 7  ok
 1112: 
 1113: If you use numbers and definitions like "+" in order to turn Forth
 1114: into a great big pocket calculator, you will realise that it's rather
 1115: different from a normal calculator. Rather than typing 2 + 3 = you had
 1116: to type 2 3 + (ignore the fact that you had to use .s to see the
 1117: result). The terminology used to describe this difference is to say
 1118: that your calculator uses "Infix Notation" (parameters and operators
 1119: are mixed) whilst Forth uses "Postfix Notation" (parameters and
 1120: operators are separate), also called "Reverse Polish Notation".
 1121: 
 1122: Whilst postfix notation might look confusing to begin with, it has
 1123: several important advantages:
 1124: 
 1125: - it is unambiguous
 1126: - it is more concise
 1127: - it fits naturally with a stack-based system
 1128: 
 1129: To examine these claims in more detail, consider these sums:
 1130: 
 1131: 6 + 5 * 4 =
 1132: 4 * 5 + 6 =
 1133: 
 1134: If you're just learning maths or your maths is very rusty, you will
 1135: probably come up with the answer 44 for the first and 26 for the
 1136: second. If you are a bit of a whizz at maths you will remember the
 1137: *convention* that multiplication takes precendence over addition, and
 1138: you'd come up with the answer 26 both times. To explain the answer 26
 1139: to someone who got the answer 44, you'd probably rewrite the first sum
 1140: like this:
 1141: 
 1142: 6 + (5 * 4) =
 1143: 
 1144: If what you really wanted was to perform the addition before the
 1145: multiplication, you would have to use parentheses to force it.
 1146: 
 1147: If you did the first two sums on a pocket calculator you would probably
 1148: get the right answers, unless you were very cautious and entered them using
 1149: these keystroke sequences:
 1150: 
 1151: 6 + 5 = * 4 =
 1152: 4 * 5 = + 6 =
 1153: 
 1154: Postfix notation is unambiguous because the order that the operators
 1155: are applied is always explicit; that also means that parentheses are
 1156: never required. The operators are *active* (the act of quoting the
 1157: operator makes the operation occur) which removes the need for "=".
 1158: 
 1159: The sum 6 + 5 * 4 can be written (in postfix notation) in two
 1160: equivalent ways:
 1161: 
 1162: 6 5 4 * +      or:
 1163: 5 4 * 6 +
 1164: 
 1165: TODO point out that the order of number is never changed.
 1166: 
 1167: TODO -- another way of thinking of this is to think of all Forth
 1168: definitions as being ACTIVE. They execute as they are encountered by the
 1169: text interpreter. With this mental model, it's easy to see that the only
 1170: way of implementing an active scheme is to use postfix notation.
 1171: 
 1172: 
 1173: 
 1174: 
 1175: .. up until now we've just been giving lists of commands that once
 1176: exeduted are gone forwever (well, not really-- try pressing the up-arrow
 1177: key.. you can recall, edit and re-enter )
 1178: 
 1179: 
 1180: @comment ----------------------------------------------
 1181: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
 1182: @section Your first Forth definition
 1183: @cindex first definition
 1184: 
 1185: 
 1186: The easiest way to create a new definition is to use a "colon
 1187: definition". In order to provide a few examples (and give you some
 1188: homework) I'm going to introduce a very small set of words but only
 1189: describe what they do very informally, by example.
 1190: 
 1191: +   add the top two numbers on the stack and place the result on the
 1192: stack
 1193: .   print the top stack item
 1194: ."  print text until a " delimiter is found
 1195: CR  print a carriage-return
 1196: :   start a new definition
 1197: ;   end a definition
 1198: DUP blah
 1199: DROP blah
 1200: 
 1201: example 1:
 1202: : greet ." Hello and welcome" ;<return>  ok
 1203: greet<return> Hello and welcome  ok
 1204: greet greet<return> Hello and welcomeHello and welcome  ok
 1205: 
 1206: When you try out this example, be careful to copy the spaces
 1207: accurately; there needs to be a space between each group of characters
 1208: that will be processed by the text interpreter.
 1209: 
 1210: 
 1211: example 2:
 1212: : add-two 2 + . ;<return>  ok
 1213: 5 add-two<return> 7  ok
 1214: 
 1215: 
 1216: - numbers and definitions
 1217: - redefining things .. what uses the old defn and what uses the new one
 1218: - boundary between system definitions and your definitions
 1219: - standards.. a double-edged sword
 1220: - philosophy
 1221: 
 1222: - your first set of definitions
 1223: 
 1224: 
 1225: 
 1226: @comment ----------------------------------------------
 1227: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
 1228: @section How does that work?
 1229: @cindex parsing words
 1230: 
 1231: 
 1232: todo parsing words .. trick the text interpreter
 1233: 
 1234: .. switching from intepret to compile and back again
 1235: 
 1236: .. what the text interpreter does.
 1237: 
 1238: Now that we have looked at the behaviour of the text interpreter in
 1239: greater detail, we can list all of the things that it knows how to do:
 1240: 
 1241: @itemize @bullet
 1242: @item
 1243: It knows how to @var{compile} a number
 1244: @item
 1245: It knows how to @var{compile} a word into a new definition
 1246: @item
 1247: It knows how to @var{interpret} a number
 1248: @item
 1249: It knows how to @var{interpret} a word
 1250: @end itemize
 1251: 
 1252: The way in which the text interpreter interprets and compiles numbers is
 1253: fixed; the effect of interpreting a number is to put that number on the
 1254: stack, and the effect of compiling a number into a definition is to
 1255: perform some trick whereby the number appears on the stack when the
 1256: definition is executed.
 1257: 
 1258: The way in which the text interpreter interprets and compiles words is
 1259: not fixed; it is defined at the same time as the word is defined, and
 1260: can be overridden in subtle ways later. When the text interpreter
 1261: searches the name dictionary for a defintion, it not only retrieves the
 1262: xt for the word, it also retrieves information about the way in which
 1263: the words can behave.
 1264: 
 1265: 
 1266: @comment TODO -- fix this up and decide whether I really want it here.
 1267: @itemize @bullet
 1268: @item
 1269: Interpretation
 1270: Compilation
 1271: Description
 1272: 
 1273: @item
 1274: execute
 1275: the xt is compiled
 1276: Normal non-immediate definition. Created by default (eg using @code{:})
 1277: 
 1278: @item
 1279: execute
 1280: execute
 1281: Normal immediate definition. Created using @code{immediate} after definition.
 1282: 
 1283: @item
 1284: illegal (generate error)
 1285: the xt is compiled
 1286: Compile-only definition. Created using @code{compile-only} after definition.
 1287: 
 1288: @item
 1289: illegal (generate error)
 1290: execute
 1291: Immediate compile-only definition created using @code{immediate} @code{compile-only} after definition.
 1292: 
 1293: @item
 1294: execute
 1295: illegal
 1296: Interpret-only definition. No standard way to generate this.
 1297: 
 1298: @end itemize
 1299: 
 1300: 
 1301: 
 1302: @comment ----------------------------------------------
 1303: @node Forth is written in Forth, Classifying Forth words, How does that work?, Introduction
 1304: @section Forth is written in Forth
 1305: @cindex structure of Forth programs
 1306: 
 1307: 
 1308: 
 1309: Blah
 1310: 
 1311: When you start up the Forth compiler, a large number of definitions
 1312: already exist. To develop a new application, use bottom-up programming
 1313: techniques to create new definitions that are defined in terms of
 1314: existing definitions. As you create each definition you can test it
 1315: interactively. Ultimately, you end up with an environment <blah blah>
 1316: 
 1317: @comment TODO - other defining words
 1318: @comment other parsing words
 1319: @comment Your first loop
 1320: @comment syntax and semantics
 1321: @comment DOES>
 1322: @comment taste of other elements of Forth
 1323: 
 1324: @comment ----------------------------------------------
 1325: @node Classifying Forth words, Review - elements of a Forth system, Forth is written in Forth, Introduction
 1326: @section Classifying Forth words
 1327: @cindex classifying Forth words
 1328: 
 1329: It can be helpful to classify Forth words into a number of groups. We
 1330: can classify any word in several orthogonal ways:
 1331: 
 1332: @itemize @bullet
 1333: @item
 1334: Based upon the way in which it is implemented
 1335: @item
 1336: Based upon whether it affects the input stream
 1337: @item
 1338: Based upon its behaviour at different times
 1339: @end itemize
 1340: 
 1341: If we classify a word based upon the way in which it is implemented, we
 1342: divide words into two groups:
 1343: 
 1344: @itemize @bullet
 1345: @item
 1346: Those that are implemented in Forth (often called @var{high-level
 1347: definitions}).
 1348: @item
 1349: Those that are not (often called @var{low-level definitions},
 1350: @var{code definitions} or @var{primitives}).
 1351: @end itemize
 1352: 
 1353: When you are programming in Forth it should never make any difference to you (or
 1354: even be apparent to you) whether any particular word is implemented as a
 1355: high-level definition or a low-level definition. If you use the word
 1356: disassembler, @code{see} you can easily find both types of words (try
 1357: @kbd{see +} and @kbd{see :}).
 1358: 
 1359: If we classify a word based upon the way in which it affects the input
 1360: stream we also divide words into two groups:
 1361: 
 1362: @itemize @bullet
 1363: @item
 1364: Those that do not affect the input stream (the vast majority of Forth
 1365: definitions fall into this category).
 1366: @item
 1367: Those that do affect the input stream (these are called @var{parsing words}).
 1368: @end itemize
 1369: 
 1370: Here are some examples of ANS Standard parsing words; you can use the
 1371: word index at the back of this manual to find out more about them:
 1372: 
 1373: @code{:}  @ @code{CONSTANT} @ @code{[CHAR]} @ @code{CHAR} @ @code{\}
 1374: 
 1375: The most complex way of classifying Forth words is based upon their
 1376: behaviour at different times. We have already seen how the text
 1377: interpreter knows how to treat words differently depending upon whether
 1378: it is interpreting or compiling, 
 1379:   
 1380: -- classifying words
 1381:   Three orthogonal ways:
 1382:   -- by function
 1383:   -- classifying words by the way in which they are defined
 1384:   -- classifying words by their behaviour
 1385: 
 1386: 
 1387: 
 1388: 
 1389: .. interactive stuff
 1390: 5 3 +  . <return> 8  ok
 1391: 
 1392: could have been split over several lines
 1393: 
 1394: 5 . . <return> 
 1395: 
 1396: 
 1397: .. talk about syntax and semantics
 1398: 
 1399: 
 1400: -- command-line recall and editing
 1401: 
 1402: 
 1403: Recode this example to show that, when you define a word, the old
 1404: definition becomes unavailable to any *subsequent* definitions.
 1405: 
 1406: @example
 1407: : greet ." Hello" ;
 1408: : announce ." I just want to say " greet ;
 1409: : greet ." Bog off" ;
 1410: : another-announce ." I just want to say " greet ;
 1411: @end example
 1412: 
 1413: After these four words have been defined, invoking the three distinct words will have this result:
 1414: 
 1415: @example
 1416: greet Welcome
 1417: announce I just want to say Hello
 1418: another-announce I just want to say Bog off
 1419: @end example
 1420: 
 1421: The original definition of @code{greet} is no longer available.
 1422: 
 1423: However, if you created two word lists and put alternative definitions of
 1424: greet in each of them, you could control which was used by changing the search order, like this:
 1425: 
 1426: @example
 1427: <create two word lists>
 1428: ALSO POLITE-WORDS DEFINITIONS
 1429: : greet ." Hello" ;
 1430: ALSO RUDE-WORDS DEFINITIONS
 1431: : greet ." Bonjour" ;
 1432: 
 1433: FORTH DEFINITIONS
 1434: ALSO POLITE-WORDS
 1435: : announce ." I just want to say " greet ;
 1436: PREVIOUS
 1437: ALSO RUDE-WORDS
 1438: : another-announce ." I just want to say " greet ;
 1439: PREVIOUS
 1440: @end example
 1441: 
 1442: 
 1443: 
 1444: 
 1445: 
 1446: 
 1447: - cells and chars
 1448: 
 1449: - the text interpreter in "Compilation" state.
 1450: 
 1451: -- elements of a forth system
 1452:   - text interpreter (outer interpreter)
 1453:   - compiler
 1454:   - inner interpreter
 1455:   - dictionaries and wordlists
 1456:   - stacks
 1457: 
 1458: -- disparate spaces .. may be better to describe that elsewhere.
 1459: 
 1460: -- show how to use the rest of the manual and how to use the ANS Forth Standard
 1461: 
 1462: @comment ----------------------------------------------
 1463: @node Review - elements of a Forth system, Exercises, Classifying Forth words, Introduction
 1464: @section Review - elements of a Forth system
 1465: @cindex elements of a Forth system
 1466: 
 1467: 
 1468: 
 1469: 
 1470: @comment ----------------------------------------------
 1471: @node Exercises, ,Review - elements of a Forth system, Introduction
 1472: @section Exercises
 1473: @cindex elements of a Forth system
 1474: 
 1475: Ideally, provide a set of programming excercises linked into the stuff
 1476: done already and into other sections of the manual. Provide solutions to
 1477: all the exercises in a .fs file in the distribution. Get some
 1478: inspiration from Starting Forth and Kelly&Spies.
 1479: 
 1480: 
 1481: @c ----------------------------------------------------------
 1482: @node Goals, Invoking Gforth, Introduction, Top
 1483: @comment node-name,     next,           previous, up
 1484: @chapter Goals of Gforth
 1485: @cindex Goals
 1486: The goal of the Gforth Project is to develop a standard model for
 1487: ANS Forth. This can be split into several subgoals:
 1488: 
 1489: @itemize @bullet
 1490: @item
 1491: Gforth should conform to the ANS Forth Standard.
 1492: @item
 1493: It should be a model, i.e. it should define all the
 1494: implementation-dependent things.
 1495: @item
 1496: It should become standard, i.e. widely accepted and used. This goal
 1497: is the most difficult one.
 1498: @end itemize
 1499: 
 1500: To achieve these goals Gforth should be
 1501: @itemize @bullet
 1502: @item
 1503: Similar to previous models (fig-Forth, F83)
 1504: @item
 1505: Powerful. It should provide for all the things that are considered
 1506: necessary today and even some that are not yet considered necessary.
 1507: @item
 1508: Efficient. It should not get the reputation of being exceptionally
 1509: slow.
 1510: @item
 1511: Free.
 1512: @item
 1513: Available on many machines/easy to port.
 1514: @end itemize
 1515: 
 1516: Have we achieved these goals? Gforth conforms to the ANS Forth
 1517: standard. It may be considered a model, but we have not yet documented
 1518: which parts of the model are stable and which parts we are likely to
 1519: change. It certainly has not yet become a de facto standard, but it
 1520: appears to be quite popular. It has some similarities to and some
 1521: differences from previous models. It has some powerful features, but not
 1522: yet everything that we envisioned. We certainly have achieved our
 1523: execution speed goals (@pxref{Performance}).  It is free and available
 1524: on many machines.
 1525: 
 1526: @menu
 1527: * Gforth Extensions Sinful?::
 1528: @end menu
 1529: 
 1530: @node Gforth Extensions Sinful?, , Goals, Goals
 1531: @comment node-name,     next,           previous, up
 1532: @section Is it a Sin to use Gforth Extensions?
 1533: @cindex Gforth extensions
 1534: 
 1535: If you've been paying attention, you will have realised that there is an
 1536: ANS Standard for Forth. As you read through the rest of this manual, you
 1537: will see documentation for @var{Standard} words, and documentation for
 1538: some appealing Gforth @var{extensions}. You might ask yourself the
 1539: question: @var{"Given that there is a standard, would I be committing a
 1540: sin to use (non-Standard) Gforth extensions?"}
 1541: 
 1542: The answer to that question is somewhat pragmatic and somewhat
 1543: philosophical. Consider these points:
 1544: 
 1545: @itemize @bullet
 1546: @item
 1547: A number of the Gforth extensions can be implemented in ANS Standard
 1548: Forth using files provided in the @file{compat/} directory. These are
 1549: mentioned in the text in passing.
 1550: @item
 1551: Forth has a rich historical precedent for programmers taking advantage
 1552: of implementation-dependent features of their tools (for example,
 1553: relying on a knowledge of the dictionary structure). Sometimes these
 1554: techniques are necessary to extract every last bit of performance from
 1555: the hardware, sometimes they are just a programming shorthand.
 1556: @item
 1557: The best way to break the rules is to know what the rules are. To learn
 1558: the rules, there is no substitute for studying the text of the Standard
 1559: itself. In particular, Appendix A of the Standard (@var{Rationale})
 1560: provides a valuable insight into the thought processes of the technical
 1561: committee.
 1562: @item
 1563: The best reason to break a rule is because you have to; because it's
 1564: more productive to do that, because it makes your code run fast enough
 1565: or because you can see no Standard way to achieve what you want to
 1566: achieve.
 1567: @end itemize
 1568: 
 1569: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
 1570: analyse your program and determine what non-Standard definitions it
 1571: relies upon.
 1572: 
 1573: 
 1574: 
 1575: @c ----------------------------------------------------------
 1576: @node Invoking Gforth, Words, Goals, Top
 1577: @chapter Invoking Gforth
 1578: @cindex Gforth - invoking
 1579: @cindex invoking Gforth
 1580: @cindex running Gforth
 1581: @cindex command-line options
 1582: @cindex options on the command line
 1583: @cindex flags on the command line
 1584: 
 1585: You will usually just say @code{gforth}. In many other cases the default
 1586: Gforth image will be invoked like this:
 1587: @example
 1588: gforth [files] [-e forth-code]
 1589: @end example
 1590: This interprets the contents of the files and the Forth code in the order they
 1591: are given.
 1592: 
 1593: In general, the command line looks like this:
 1594: 
 1595: @example
 1596: gforth [initialization options] [image-specific options]
 1597: @end example
 1598: 
 1599: The initialization options must come before the rest of the command
 1600: line. They are:
 1601: 
 1602: @table @code
 1603: @cindex -i, command-line option
 1604: @cindex --image-file, command-line option
 1605: @item --image-file @var{file}
 1606: @itemx -i @var{file}
 1607: Loads the Forth image @var{file} instead of the default
 1608: @file{gforth.fi} (@pxref{Image Files}).
 1609: 
 1610: @cindex --path, command-line option
 1611: @cindex -p, command-line option
 1612: @item --path @var{path}
 1613: @itemx -p @var{path}
 1614: Uses @var{path} for searching the image file and Forth source code files
 1615: instead of the default in the environment variable @code{GFORTHPATH} or
 1616: the path specified at installation time (e.g.,
 1617: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
 1618: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
 1619: 
 1620: @cindex --dictionary-size, command-line option
 1621: @cindex -m, command-line option
 1622: @cindex @var{size} parameters for command-line options
 1623: @cindex size of the dictionary and the stacks
 1624: @item --dictionary-size @var{size}
 1625: @itemx -m @var{size}
 1626: Allocate @var{size} space for the Forth dictionary space instead of
 1627: using the default specified in the image (typically 256K). The
 1628: @var{size} specification for this and subsequent options consists of
 1629: an integer and a unit (e.g.,
 1630: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
 1631: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
 1632: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
 1633: @code{e} is used.
 1634: 
 1635: @cindex --data-stack-size, command-line option
 1636: @cindex -d, command-line option
 1637: @item --data-stack-size @var{size}
 1638: @itemx -d @var{size}
 1639: Allocate @var{size} space for the data stack instead of using the
 1640: default specified in the image (typically 16K).
 1641: 
 1642: @cindex --return-stack-size, command-line option
 1643: @cindex -r, command-line option
 1644: @item --return-stack-size @var{size}
 1645: @itemx -r @var{size}
 1646: Allocate @var{size} space for the return stack instead of using the
 1647: default specified in the image (typically 15K).
 1648: 
 1649: @cindex --fp-stack-size, command-line option
 1650: @cindex -f, command-line option
 1651: @item --fp-stack-size @var{size}
 1652: @itemx -f @var{size}
 1653: Allocate @var{size} space for the floating point stack instead of
 1654: using the default specified in the image (typically 15.5K). In this case
 1655: the unit specifier @code{e} refers to floating point numbers.
 1656: 
 1657: @cindex --locals-stack-size, command-line option
 1658: @cindex -l, command-line option
 1659: @item --locals-stack-size @var{size}
 1660: @itemx -l @var{size}
 1661: Allocate @var{size} space for the locals stack instead of using the
 1662: default specified in the image (typically 14.5K).
 1663: 
 1664: @cindex -h, command-line option
 1665: @cindex --help, command-line option
 1666: @item --help
 1667: @itemx -h
 1668: Print a message about the command-line options
 1669: 
 1670: @cindex -v, command-line option
 1671: @cindex --version, command-line option
 1672: @item --version
 1673: @itemx -v
 1674: Print version and exit
 1675: 
 1676: @cindex --debug, command-line option
 1677: @item --debug
 1678: Print some information useful for debugging on startup.
 1679: 
 1680: @cindex --offset-image, command-line option
 1681: @item --offset-image
 1682: Start the dictionary at a slightly different position than would be used
 1683: otherwise (useful for creating data-relocatable images,
 1684: @pxref{Data-Relocatable Image Files}).
 1685: 
 1686: @cindex --no-offset-im, command-line option
 1687: @item --no-offset-im
 1688: Start the dictionary at the normal position.
 1689: 
 1690: @cindex --clear-dictionary, command-line option
 1691: @item --clear-dictionary
 1692: Initialize all bytes in the dictionary to 0 before loading the image
 1693: (@pxref{Data-Relocatable Image Files}).
 1694: 
 1695: @cindex --die-on-signal, command-line-option
 1696: @item --die-on-signal
 1697: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
 1698: or the segmentation violation SIGSEGV) by translating it into a Forth
 1699: @code{THROW}. With this option, Gforth exits if it receives such a
 1700: signal. This option is useful when the engine and/or the image might be
 1701: severely broken (such that it causes another signal before recovering
 1702: from the first); this option avoids endless loops in such cases.
 1703: @end table
 1704: 
 1705: @cindex loading files at startup
 1706: @cindex executing code on startup
 1707: @cindex batch processing with Gforth
 1708: As explained above, the image-specific command-line arguments for the
 1709: default image @file{gforth.fi} consist of a sequence of filenames and
 1710: @code{-e @var{forth-code}} options that are interpreted in the sequence
 1711: in which they are given. The @code{-e @var{forth-code}} or
 1712: @code{--evaluate @var{forth-code}} option evaluates the Forth
 1713: code. This option takes only one argument; if you want to evaluate more
 1714: Forth words, you have to quote them or use several @code{-e}s. To exit
 1715: after processing the command line (instead of entering interactive mode)
 1716: append @code{-e bye} to the command line.
 1717: 
 1718: @cindex versions, invoking other versions of Gforth
 1719: If you have several versions of Gforth installed, @code{gforth} will
 1720: invoke the version that was installed last. @code{gforth-@var{version}}
 1721: invokes a specific version. You may want to use the option
 1722: @code{--path}, if your environment contains the variable
 1723: @code{GFORTHPATH}.
 1724: 
 1725: Not yet implemented:
 1726: On startup the system first executes the system initialization file
 1727: (unless the option @code{--no-init-file} is given; note that the system
 1728: resulting from using this option may not be ANS Forth conformant). Then
 1729: the user initialization file @file{.gforth.fs} is executed, unless the
 1730: option @code{--no-rc} is given; this file is first searched in @file{.},
 1731: then in @file{~}, then in the normal path (see above).
 1732: 
 1733: 
 1734: @cindex Gforth - leaving
 1735: @cindex leaving Gforth
 1736: 
 1737: You can leave Gforth by typing @code{bye} or (if you invoked Gforth with
 1738: the @code{--die-on-signal} option) Ctrl-C. When you leave Gforth, all of
 1739: your definitions and data are discarded. @xref{Image Files} for ways
 1740: of saving the state of the system before leaving Gforth.
 1741: 
 1742: doc-bye
 1743: 
 1744: 
 1745: @node Words, Tools, Invoking Gforth, Top
 1746: @chapter Forth Words
 1747: @cindex Words
 1748: 
 1749: @menu
 1750: * Notation::                    
 1751: * Comments::
 1752: * Boolean Flags::
 1753: * Arithmetic::                  
 1754: * Stack Manipulation::          
 1755: * Memory::                      
 1756: * Control Structures::          
 1757: * Locals::                      
 1758: * Defining Words::              
 1759: * The Text Interpreter::
 1760: * Structures::                  
 1761: * Object-oriented Forth::       
 1762: * Tokens for Words::            
 1763: * Word Lists::                   
 1764: * Environmental Queries::
 1765: * Files::                       
 1766: * Including Files::             
 1767: * Blocks::                      
 1768: * Other I/O::                   
 1769: * Programming Tools::           
 1770: * Assembler and Code Words::    
 1771: * Threading Words::             
 1772: * Passing Commands to the OS::
 1773: * Miscellaneous Words::
 1774: @end menu
 1775: 
 1776: @node Notation, Comments, Words, Words
 1777: @section Notation
 1778: @cindex notation of glossary entries
 1779: @cindex format of glossary entries
 1780: @cindex glossary notation format
 1781: @cindex word glossary entry format
 1782: 
 1783: The Forth words are described in this section in the glossary notation
 1784: that has become a de-facto standard for Forth texts, i.e.,
 1785: 
 1786: @format
 1787: @var{word}     @var{Stack effect}   @var{wordset}   @var{pronunciation}
 1788: @end format
 1789: @var{Description}
 1790: 
 1791: @table @var
 1792: @item word
 1793: @cindex case insensitivity
 1794: The name of the word. BTW, Gforth is case insensitive, so you can
 1795: type the words in in lower case (However, @pxref{core-idef}).
 1796: 
 1797: @item Stack effect
 1798: @cindex stack effect
 1799: The stack effect is written in the notation @code{@var{before} --
 1800: @var{after}}, where @var{before} and @var{after} describe the top of
 1801: stack entries before and after the execution of the word. The rest of
 1802: the stack is not touched by the word. The top of stack is rightmost,
 1803: i.e., a stack sequence is written as it is typed in. Note that Gforth
 1804: uses a separate floating point stack, but a unified stack
 1805: notation. Also, return stack effects are not shown in @var{stack
 1806: effect}, but in @var{Description}. The name of a stack item describes
 1807: the type and/or the function of the item. See below for a discussion of
 1808: the types.
 1809: 
 1810: All words have two stack effects: A compile-time stack effect and a
 1811: run-time stack effect. The compile-time stack-effect of most words is
 1812: @var{ -- }. If the compile-time stack-effect of a word deviates from
 1813: this standard behaviour, or the word does other unusual things at
 1814: compile time, both stack effects are shown; otherwise only the run-time
 1815: stack effect is shown.
 1816: 
 1817: @cindex pronounciation of words
 1818: @item pronunciation
 1819: How the word is pronounced.
 1820: 
 1821: @cindex wordset
 1822: @item wordset
 1823: The ANS Forth standard is divided into several word sets. A standard
 1824: system need not support all of them. Therefore, in theory, the fewer
 1825: word sets your program uses the more portable it will be. However, we
 1826: suspect that most ANS Forth systems on personal machines will feature
 1827: all word sets. Words that are not defined in the ANS standard have
 1828: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
 1829: describes words that will work in future releases of Gforth;
 1830: @code{gforth-internal} words are more volatile. Environmental query
 1831: strings are also displayed like words; you can recognize them by the
 1832: @code{environment} in the word set field.
 1833: 
 1834: @item Description
 1835: A description of the behaviour of the word.
 1836: @end table
 1837: 
 1838: @cindex types of stack items
 1839: @cindex stack item types
 1840: The type of a stack item is specified by the character(s) the name
 1841: starts with:
 1842: 
 1843: @table @code
 1844: @item f
 1845: @cindex @code{f}, stack item type
 1846: Boolean flags, i.e. @code{false} or @code{true}.
 1847: @item c
 1848: @cindex @code{c}, stack item type
 1849: Char
 1850: @item w
 1851: @cindex @code{w}, stack item type
 1852: Cell, can contain an integer or an address
 1853: @item n
 1854: @cindex @code{n}, stack item type
 1855: signed integer
 1856: @item u
 1857: @cindex @code{u}, stack item type
 1858: unsigned integer
 1859: @item d
 1860: @cindex @code{d}, stack item type
 1861: double sized signed integer
 1862: @item ud
 1863: @cindex @code{ud}, stack item type
 1864: double sized unsigned integer
 1865: @item r
 1866: @cindex @code{r}, stack item type
 1867: Float (on the FP stack)
 1868: @item a-
 1869: @cindex @code{a_}, stack item type
 1870: Cell-aligned address
 1871: @item c-
 1872: @cindex @code{c_}, stack item type
 1873: Char-aligned address (note that a Char may have two bytes in Windows NT)
 1874: @item f-
 1875: @cindex @code{f_}, stack item type
 1876: Float-aligned address
 1877: @item df-
 1878: @cindex @code{df_}, stack item type
 1879: Address aligned for IEEE double precision float
 1880: @item sf-
 1881: @cindex @code{sf_}, stack item type
 1882: Address aligned for IEEE single precision float
 1883: @item xt
 1884: @cindex @code{xt}, stack item type
 1885: Execution token, same size as Cell
 1886: @item wid
 1887: @cindex @code{wid}, stack item type
 1888: Word list ID, same size as Cell
 1889: @item f83name
 1890: @cindex @code{f83name}, stack item type
 1891: Pointer to a name structure
 1892: @item "
 1893: @cindex @code{"}, stack item type
 1894: string in the input stream (not on the stack). The terminating character
 1895: is a blank by default. If it is not a blank, it is shown in @code{<>}
 1896: quotes.
 1897: @end table
 1898: 
 1899: @node Comments, Boolean Flags, Notation, Words
 1900: @section Comments
 1901: @cindex Comments
 1902: 
 1903: Forth supports two styles of comment; the traditional "in-line" comment,
 1904: @code{(} and its modern cousin, the "comment to end of line"; @code{\}.
 1905: 
 1906: doc-\
 1907: doc-(
 1908: 
 1909: 
 1910: @node Boolean Flags, Arithmetic, Comments, Words
 1911: @section Boolean Flags
 1912: @cindex Boolean Flags
 1913: 
 1914: A Boolean flag is cell-sized. A cell with all bits clear represents the
 1915: flag @code{false} and a flag with all bits set represents the flag
 1916: @code{true}. Words that check a flag (for example, @var{IF}) will treat
 1917: a cell that has @var{any} bit set as @code{true}.
 1918: 
 1919: doc-true
 1920: doc-false
 1921: 
 1922: 
 1923: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
 1924: @section Arithmetic
 1925: @cindex arithmetic words
 1926: 
 1927: @cindex division with potentially negative operands
 1928: Forth arithmetic is not checked, i.e., you will not hear about integer
 1929: overflow on addition or multiplication, you may hear about division by
 1930: zero if you are lucky. The operator is written after the operands, but
 1931: the operands are still in the original order. I.e., the infix @code{2-1}
 1932: corresponds to @code{2 1 -}. Forth offers a variety of division
 1933: operators. If you perform division with potentially negative operands,
 1934: you do not want to use @code{/} or @code{/mod} with its undefined
 1935: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
 1936: former, @pxref{Mixed precision}).
 1937: 
 1938: @menu
 1939: * Single precision::            
 1940: * Bitwise operations::          
 1941: * Double precision::            Double-cell integer arithmetic
 1942: * Numeric comparison::
 1943: * Mixed precision::             operations with single and double-cell integers
 1944: * Floating Point::              
 1945: @end menu
 1946: 
 1947: @node Single precision, Bitwise operations, Arithmetic, Arithmetic
 1948: @subsection Single precision
 1949: @cindex single precision arithmetic words
 1950: 
 1951: By default, numbers in Forth are single-precision integers that are 1
 1952: CELL in size. They can be signed or unsigned, depending upon how you
 1953: treat them. @xref{Number Conversion} for the rules used by the text
 1954: interpreter for recognising single-precision integers.
 1955: 
 1956: doc-+
 1957: doc-1+
 1958: doc--
 1959: doc-1-
 1960: doc-*
 1961: doc-/
 1962: doc-mod
 1963: doc-/mod
 1964: doc-negate
 1965: doc-abs
 1966: doc-min
 1967: doc-max
 1968: doc-d>s
 1969: 
 1970: @node Bitwise operations, Double precision, Single precision, Arithmetic
 1971: @subsection Bitwise operations
 1972: @cindex bitwise operation words
 1973: 
 1974: doc-and
 1975: doc-or
 1976: doc-xor
 1977: doc-invert
 1978: doc-lshift
 1979: doc-rshift
 1980: doc-2*
 1981: doc-d2*
 1982: doc-2/
 1983: doc-d2/
 1984: 
 1985: @node Double precision, Numeric comparison, Bitwise operations, Arithmetic
 1986: @subsection Double precision
 1987: @cindex double precision arithmetic words
 1988: 
 1989: @xref{Number Conversion} for the rules used by the text interpreter for
 1990: recognising double-precision integers.
 1991: 
 1992: A double precision number is represented by a cell pair, with the most
 1993: significant digit at the TOS. It is trivial to convert an unsigned single
 1994: to an (unsigned) double; simply push a @code{0} onto the TOS. Since numbers
 1995: are represented by Gforth using 2's complement arithmetic, converting
 1996: a signed single to a (signed) double requires sign-extension across the
 1997: most significant digit. This can be achieved using @code{s>d}. The moral
 1998: of the story is that you cannot convert a number without knowing what that
 1999: number represents.
 2000: 
 2001: doc-s>d
 2002: doc-d+
 2003: doc-d-
 2004: doc-dnegate
 2005: doc-dabs
 2006: doc-dmin
 2007: doc-dmax
 2008: 
 2009: @node Numeric comparison, Mixed precision, Double precision, Arithmetic
 2010: @subsection Numeric comparison
 2011: @cindex numeric comparison words
 2012: 
 2013: doc-0<
 2014: doc-0<>
 2015: doc-0=
 2016: doc-<
 2017: doc-<>
 2018: doc-=
 2019: doc->
 2020: doc-d0<
 2021: doc-d0=
 2022: doc-d<
 2023: doc-d=
 2024: doc-u<
 2025: doc-du<
 2026: doc-u>
 2027: doc-within
 2028: 
 2029: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
 2030: @subsection Mixed precision
 2031: @cindex mixed precision arithmetic words
 2032: 
 2033: doc-m+
 2034: doc-*/
 2035: doc-*/mod
 2036: doc-m*
 2037: doc-um*
 2038: doc-m*/
 2039: doc-um/mod
 2040: doc-fm/mod
 2041: doc-sm/rem
 2042: 
 2043: @node Floating Point,  , Mixed precision, Arithmetic
 2044: @subsection Floating Point
 2045: @cindex floating point arithmetic words
 2046: 
 2047: @xref{Number Conversion} for the rules used by the text interpreter for
 2048: recognising floating-point numbers.
 2049: 
 2050: @cindex angles in trigonometric operations
 2051: @cindex trigonometric operations
 2052: Angles in floating point operations are given in radians (a full circle
 2053: has 2 pi radians). Note, that Gforth has a separate floating point
 2054: stack, but we use the unified notation.
 2055: 
 2056: @cindex floating-point arithmetic, pitfalls
 2057: Floating point numbers have a number of unpleasant surprises for the
 2058: unwary (e.g., floating point addition is not associative) and even a few
 2059: for the wary. You should not use them unless you know what you are doing
 2060: or you don't care that the results you get are totally bogus. If you
 2061: want to learn about the problems of floating point numbers (and how to
 2062: avoid them), you might start with @cite{David Goldberg, What Every
 2063: Computer Scientist Should Know About Floating-Point Arithmetic, ACM
 2064: Computing Surveys 23(1):5@minus{}48, March 1991}
 2065: (@url{http://www.validgh.com/goldberg/paper.ps}).
 2066: 
 2067: doc-d>f
 2068: doc-f>d
 2069: doc-f+
 2070: doc-f-
 2071: doc-f*
 2072: doc-f/
 2073: doc-fnegate
 2074: doc-fabs
 2075: doc-fmax
 2076: doc-fmin
 2077: doc-floor
 2078: doc-fround
 2079: doc-f**
 2080: doc-fsqrt
 2081: doc-fexp
 2082: doc-fexpm1
 2083: doc-fln
 2084: doc-flnp1
 2085: doc-flog
 2086: doc-falog
 2087: doc-fsin
 2088: doc-fcos
 2089: doc-fsincos
 2090: doc-ftan
 2091: doc-fasin
 2092: doc-facos
 2093: doc-fatan
 2094: doc-fatan2
 2095: doc-fsinh
 2096: doc-fcosh
 2097: doc-ftanh
 2098: doc-fasinh
 2099: doc-facosh
 2100: doc-fatanh
 2101: doc-pi
 2102: doc-f0<
 2103: doc-f0=
 2104: doc-f<
 2105: doc-f<=
 2106: doc-f<>
 2107: doc-f=
 2108: doc-f>
 2109: doc-f>=
 2110: doc-f2*
 2111: doc-f2/
 2112: doc-1/f
 2113: doc-f~
 2114: doc-precision
 2115: doc-set-precision
 2116: 
 2117: @node Stack Manipulation, Memory, Arithmetic, Words
 2118: @section Stack Manipulation
 2119: @cindex stack manipulation words
 2120: 
 2121: @cindex floating-point stack in the standard
 2122: Gforth maintains a number of separate stacks:
 2123: 
 2124: @itemize @bullet
 2125: @item
 2126: A data stack (aka parameter stack) -- for characters, cells,
 2127: addresses, and double cells.
 2128: 
 2129: @item
 2130: A floating point stack -- for floating point numbers.
 2131: 
 2132: @item
 2133: A return stack -- for storing the return addresses of colon
 2134: definitions and other data.
 2135: 
 2136: @item
 2137: A locals stack for storing local variables.
 2138: @end itemize
 2139: 
 2140: Whilst every sane Forth has a separate floating-point stack, it is not
 2141: strictly required; an ANS Forth system could theoretically keep
 2142: floating-point numbers on the data stack. As an additional difficulty,
 2143: you don't know how many cells a floating-point number takes. It is
 2144: reportedly possible to write words in a way that they work also for a
 2145: unified stack model, but we do not recommend trying it. Instead, just
 2146: say that your program has an environmental dependency on a separate
 2147: floating-point stack.
 2148: 
 2149: doc-floating-stack
 2150: 
 2151: @cindex return stack and locals
 2152: @cindex locals and return stack
 2153: A Forth system is allowed to keep local variables on the
 2154: return stack. This is reasonable, as local variables usually eliminate
 2155: the need to use the return stack explicitly. So, if you want to produce
 2156: a standard compliant program and you are using local variables in a
 2157: word, forget about return stack manipulations in that word (refer to the
 2158: standard document for the exact rules).
 2159: 
 2160: @menu
 2161: * Data stack::                  
 2162: * Floating point stack::        
 2163: * Return stack::                
 2164: * Locals stack::                
 2165: * Stack pointer manipulation::  
 2166: @end menu
 2167: 
 2168: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
 2169: @subsection Data stack
 2170: @cindex data stack manipulation words
 2171: @cindex stack manipulations words, data stack
 2172: 
 2173: doc-drop
 2174: doc-nip
 2175: doc-dup
 2176: doc-over
 2177: doc-tuck
 2178: doc-swap
 2179: doc-pick
 2180: doc-rot
 2181: doc--rot
 2182: doc-?dup
 2183: doc-roll
 2184: doc-2drop
 2185: doc-2nip
 2186: doc-2dup
 2187: doc-2over
 2188: doc-2tuck
 2189: doc-2swap
 2190: doc-2rot
 2191: 
 2192: @node Floating point stack, Return stack, Data stack, Stack Manipulation
 2193: @subsection Floating point stack
 2194: @cindex floating-point stack manipulation words
 2195: @cindex stack manipulation words, floating-point stack
 2196: 
 2197: doc-fdrop
 2198: doc-fnip
 2199: doc-fdup
 2200: doc-fover
 2201: doc-ftuck
 2202: doc-fswap
 2203: doc-fpick
 2204: doc-frot
 2205: 
 2206: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
 2207: @subsection Return stack
 2208: @cindex return stack manipulation words
 2209: @cindex stack manipulation words, return stack
 2210: 
 2211: doc->r
 2212: doc-r>
 2213: doc-r@
 2214: doc-rdrop
 2215: doc-2>r
 2216: doc-2r>
 2217: doc-2r@
 2218: doc-2rdrop
 2219: 
 2220: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
 2221: @subsection Locals stack
 2222: 
 2223: 
 2224: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
 2225: @subsection Stack pointer manipulation
 2226: @cindex stack pointer manipulation words
 2227: 
 2228: doc-sp0
 2229: doc-s0
 2230: doc-sp@
 2231: doc-sp!
 2232: doc-fp0
 2233: doc-fp@
 2234: doc-fp!
 2235: doc-rp0
 2236: doc-r0
 2237: doc-rp@
 2238: doc-rp!
 2239: doc-lp0
 2240: doc-l0
 2241: doc-lp@
 2242: doc-lp!
 2243: 
 2244: @node Memory, Control Structures, Stack Manipulation, Words
 2245: @section Memory
 2246: @cindex Memory words
 2247: 
 2248: @menu
 2249: * Memory Access::      
 2250: * Address arithmetic::          
 2251: * Memory Blocks::         
 2252: @end menu
 2253: 
 2254: @node Memory Access, Address arithmetic, Memory, Memory
 2255: @subsection Memory Access
 2256: @cindex memory access words
 2257: 
 2258: doc-@
 2259: doc-!
 2260: doc-+!
 2261: doc-c@
 2262: doc-c!
 2263: doc-2@
 2264: doc-2!
 2265: doc-f@
 2266: doc-f!
 2267: doc-sf@
 2268: doc-sf!
 2269: doc-df@
 2270: doc-df!
 2271: 
 2272: @node Address arithmetic, Memory Blocks, Memory Access, Memory
 2273: @subsection Address arithmetic
 2274: @cindex address arithmetic words
 2275: 
 2276: ANS Forth does not specify the sizes of the data types. Instead, it
 2277: offers a number of words for computing sizes and doing address
 2278: arithmetic. Basically, address arithmetic is performed in terms of
 2279: address units (aus); on most systems the address unit is one byte. Note
 2280: that a character may have more than one au, so @code{chars} is no noop
 2281: (on systems where it is a noop, it compiles to nothing).
 2282: 
 2283: @cindex alignment of addresses for types
 2284: ANS Forth also defines words for aligning addresses for specific
 2285: types. Many computers require that accesses to specific data types
 2286: must only occur at specific addresses; e.g., that cells may only be
 2287: accessed at addresses divisible by 4. Even if a machine allows unaligned
 2288: accesses, it can usually perform aligned accesses faster. 
 2289: 
 2290: For the performance-conscious: alignment operations are usually only
 2291: necessary during the definition of a data structure, not during the
 2292: (more frequent) accesses to it.
 2293: 
 2294: ANS Forth defines no words for character-aligning addresses. This is not
 2295: an oversight, but reflects the fact that addresses that are not
 2296: char-aligned have no use in the standard and therefore will not be
 2297: created.
 2298: 
 2299: @cindex @code{CREATE} and alignment
 2300: The standard guarantees that addresses returned by @code{CREATE}d words
 2301: are cell-aligned; in addition, Gforth guarantees that these addresses
 2302: are aligned for all purposes.
 2303: 
 2304: Note that the standard defines a word @code{char}, which has nothing to
 2305: do with address arithmetic.
 2306: 
 2307: doc-chars
 2308: doc-char+
 2309: doc-cells
 2310: doc-cell+
 2311: doc-cell
 2312: doc-align
 2313: doc-aligned
 2314: doc-floats
 2315: doc-float+
 2316: doc-float
 2317: doc-falign
 2318: doc-faligned
 2319: doc-sfloats
 2320: doc-sfloat+
 2321: doc-sfalign
 2322: doc-sfaligned
 2323: doc-dfloats
 2324: doc-dfloat+
 2325: doc-dfalign
 2326: doc-dfaligned
 2327: doc-maxalign
 2328: doc-maxaligned
 2329: doc-cfalign
 2330: doc-cfaligned
 2331: doc-address-unit-bits
 2332: 
 2333: @node Memory Blocks,  , Address arithmetic, Memory
 2334: @subsection Memory Blocks
 2335: @cindex memory block words
 2336: 
 2337: Some of these words work on address units (increments of @code{CELL}),
 2338: and expect a @code{CELL}-aligned address. Others work on character units
 2339: (increments of @code{CHAR}), and expect a @code{CHAR}-aligned
 2340: address. Choose the correct operation depending upon your data type. If
 2341: you are moving a block of memory (for example, a region reserved by
 2342: @code{allot}) it is safe to use @code{move}, and it should be faster
 2343: than using @code{cmove}. If you are moving (for example) a string
 2344: compiled using @code{S"}, it is not portable to use @code{move}; the
 2345: alignment of the string in memory could change, and the relationship
 2346: between @code{CELL} and @code{CHAR} could change.
 2347: 
 2348: When copying characters between overlapping memory regions, choose
 2349: carefully between @code{cmove} and @code{cmove>}.
 2350: 
 2351: You can only use any of these words @var{portably} to access data space.
 2352: 
 2353: @comment - think the naming of the arguments is wrong for move
 2354: doc-move
 2355: doc-erase
 2356: 
 2357: @comment - think the naming of the arguments is wrong for cmove
 2358: doc-cmove
 2359: @comment - think the naming of the arguments is wrong for cmove>
 2360: doc-cmove>
 2361: doc-fill
 2362: @comment - think the naming of the arguments is wrong for blank
 2363: doc-blank
 2364: doc-compare
 2365: doc-search
 2366: 
 2367: @node Control Structures, Locals, Memory, Words
 2368: @section Control Structures
 2369: @cindex control structures
 2370: 
 2371: Control structures in Forth cannot be used in interpret state, only in
 2372: compile state@footnote{More precisely, they have no interpretation
 2373: semantics (@pxref{Interpretation and Compilation Semantics})}, i.e., in
 2374: a colon definition. We do not like this limitation, but have not seen a
 2375: satisfying way around it yet, although many schemes have been proposed.
 2376: 
 2377: @menu
 2378: * Selection::                   
 2379: * Simple Loops::                
 2380: * Counted Loops::               
 2381: * Arbitrary control structures::  
 2382: * Calls and returns::           
 2383: * Exception Handling::          
 2384: @end menu
 2385: 
 2386: @node Selection, Simple Loops, Control Structures, Control Structures
 2387: @subsection Selection
 2388: @cindex selection control structures
 2389: @cindex control structures for selection
 2390: 
 2391: @cindex @code{IF} control structure
 2392: @example
 2393: @var{flag}
 2394: IF
 2395:   @var{code}
 2396: ENDIF
 2397: @end example
 2398: @noindent
 2399: or
 2400: @example
 2401: @var{flag}
 2402: IF
 2403:   @var{code1}
 2404: ELSE
 2405:   @var{code2}
 2406: ENDIF
 2407: @end example
 2408: 
 2409: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
 2410: standard, and @code{ENDIF} is not, although it is quite popular. We
 2411: recommend using @code{ENDIF}, because it is less confusing for people
 2412: who also know other languages (and is not prone to reinforcing negative
 2413: prejudices against Forth in these people). Adding @code{ENDIF} to a
 2414: system that only supplies @code{THEN} is simple:
 2415: @example
 2416: : ENDIF   POSTPONE THEN ; immediate
 2417: @end example
 2418: 
 2419: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
 2420: (adv.)}  has the following meanings:
 2421: @quotation
 2422: ... 2b: following next after in order ... 3d: as a necessary consequence
 2423: (if you were there, then you saw them).
 2424: @end quotation
 2425: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
 2426: and many other programming languages has the meaning 3d.]
 2427: 
 2428: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
 2429: you can avoid using @code{?dup}. Using these alternatives is also more
 2430: efficient than using @code{?dup}. Definitions in ANS Standard Forth
 2431: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
 2432: @file{compat/control.fs}.
 2433: 
 2434: @cindex @code{CASE} control structure
 2435: @example
 2436: @var{n}
 2437: CASE
 2438:   @var{n1} OF @var{code1} ENDOF
 2439:   @var{n2} OF @var{code2} ENDOF
 2440:   @dots{}
 2441: ENDCASE
 2442: @end example
 2443: 
 2444: Executes the first @var{codei}, where the @var{ni} is equal to
 2445: @var{n}. A default case can be added by simply writing the code after
 2446: the last @code{ENDOF}. It may use @var{n}, which is on top of the stack,
 2447: but must not consume it.
 2448: 
 2449: @node Simple Loops, Counted Loops, Selection, Control Structures
 2450: @subsection Simple Loops
 2451: @cindex simple loops
 2452: @cindex loops without count 
 2453: 
 2454: @cindex @code{WHILE} loop
 2455: @example
 2456: BEGIN
 2457:   @var{code1}
 2458:   @var{flag}
 2459: WHILE
 2460:   @var{code2}
 2461: REPEAT
 2462: @end example
 2463: 
 2464: @var{code1} is executed and @var{flag} is computed. If it is true,
 2465: @var{code2} is executed and the loop is restarted; If @var{flag} is
 2466: false, execution continues after the @code{REPEAT}.
 2467: 
 2468: @cindex @code{UNTIL} loop
 2469: @example
 2470: BEGIN
 2471:   @var{code}
 2472:   @var{flag}
 2473: UNTIL
 2474: @end example
 2475: 
 2476: @var{code} is executed. The loop is restarted if @code{flag} is false.
 2477: 
 2478: @cindex endless loop
 2479: @cindex loops, endless
 2480: @example
 2481: BEGIN
 2482:   @var{code}
 2483: AGAIN
 2484: @end example
 2485: 
 2486: This is an endless loop.
 2487: 
 2488: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
 2489: @subsection Counted Loops
 2490: @cindex counted loops
 2491: @cindex loops, counted
 2492: @cindex @code{DO} loops
 2493: 
 2494: The basic counted loop is:
 2495: @example
 2496: @var{limit} @var{start}
 2497: ?DO
 2498:   @var{body}
 2499: LOOP
 2500: @end example
 2501: 
 2502: This performs one iteration for every integer, starting from @var{start}
 2503: and up to, but excluding @var{limit}. The counter, or @var{index}, can be
 2504: accessed with @code{i}. For example, the loop:
 2505: @example
 2506: 10 0 ?DO
 2507:   i .
 2508: LOOP
 2509: @end example
 2510: @noindent
 2511: prints @code{0 1 2 3 4 5 6 7 8 9}
 2512: 
 2513: The index of the innermost loop can be accessed with @code{i}, the index
 2514: of the next loop with @code{j}, and the index of the third loop with
 2515: @code{k}.
 2516: 
 2517: doc-i
 2518: doc-j
 2519: doc-k
 2520: 
 2521: The loop control data are kept on the return stack, so there are some
 2522: restrictions on mixing return stack accesses and counted loop words. In
 2523: particuler, if you put values on the return stack outside the loop, you
 2524: cannot read them inside the loop@footnote{well, not in a way that is
 2525: portable.}. If you put values on the return stack within a loop, you
 2526: have to remove them before the end of the loop and before accessing the
 2527: index of the loop.
 2528: 
 2529: There are several variations on the counted loop:
 2530: 
 2531: @itemize @bullet
 2532: @item
 2533: @code{LEAVE} leaves the innermost counted loop immediately; execution
 2534: continues after the associated @code{LOOP} or @code{NEXT}. For example:
 2535: 
 2536: @example
 2537: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
 2538: @end example
 2539: prints @code{0 1 2 3}
 2540: 
 2541: 
 2542: @item
 2543: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
 2544: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
 2545: return stack so @code{EXIT} can get to its return address. For example:
 2546: 
 2547: @example
 2548: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
 2549: @end example
 2550: prints @code{0 1 2 3}
 2551: 
 2552: 
 2553: @item
 2554: If @var{start} is greater than @var{limit}, a @code{?DO} loop is entered
 2555: (and @code{LOOP} iterates until they become equal by wrap-around
 2556: arithmetic). This behaviour is usually not what you want. Therefore,
 2557: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
 2558: @code{?DO}), which do not enter the loop if @var{start} is greater than
 2559: @var{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
 2560: unsigned loop parameters.
 2561: 
 2562: @item
 2563: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
 2564: the loop, independent of the loop parameters. Do not use @code{DO}, even
 2565: if you know that the loop is entered in any case. Such knowledge tends
 2566: to become invalid during maintenance of a program, and then the
 2567: @code{DO} will make trouble.
 2568: 
 2569: @item
 2570: @code{LOOP} can be replaced with @code{@var{n} +LOOP}; this updates the
 2571: index by @var{n} instead of by 1. The loop is terminated when the border
 2572: between @var{limit-1} and @var{limit} is crossed. E.g.:
 2573: 
 2574: @example
 2575: 4 0 +DO  i .  2 +LOOP
 2576: @end example
 2577: @noindent
 2578: prints @code{0 2}
 2579: 
 2580: @example
 2581: 4 1 +DO  i .  2 +LOOP
 2582: @end example
 2583: @noindent
 2584: prints @code{1 3}
 2585: 
 2586: 
 2587: @cindex negative increment for counted loops
 2588: @cindex counted loops with negative increment
 2589: The behaviour of @code{@var{n} +LOOP} is peculiar when @var{n} is negative:
 2590: 
 2591: @example
 2592: -1 0 ?DO  i .  -1 +LOOP
 2593: @end example
 2594: @noindent
 2595: prints @code{0 -1}
 2596: 
 2597: @example
 2598: 0 0 ?DO  i .  -1 +LOOP
 2599: @end example
 2600: prints nothing.
 2601: 
 2602: Therefore we recommend avoiding @code{@var{n} +LOOP} with negative
 2603: @var{n}. One alternative is @code{@var{u} -LOOP}, which reduces the
 2604: index by @var{u} each iteration. The loop is terminated when the border
 2605: between @var{limit+1} and @var{limit} is crossed. Gforth also provides
 2606: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
 2607: 
 2608: @example
 2609: -2 0 -DO  i .  1 -LOOP
 2610: @end example
 2611: @noindent
 2612: prints @code{0 -1}
 2613: 
 2614: @example
 2615: -1 0 -DO  i .  1 -LOOP
 2616: @end example
 2617: @noindent
 2618: prints @code{0}
 2619: 
 2620: @example
 2621: 0 0 -DO  i .  1 -LOOP
 2622: @end example
 2623: @noindent
 2624: prints nothing.
 2625: 
 2626: @end itemize
 2627: 
 2628: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
 2629: @code{-LOOP} are not in the ANS Forth standard. However, an
 2630: implementation for these words that uses only standard words is provided
 2631: in @file{compat/loops.fs}.
 2632: 
 2633: 
 2634: 
 2635: @cindex @code{FOR} loops
 2636: Another counted loop is
 2637: @example
 2638: @var{n}
 2639: FOR
 2640:   @var{body}
 2641: NEXT
 2642: @end example
 2643: This is the preferred loop of native code compiler writers who are too
 2644: lazy to optimize @code{?DO} loops properly. In Gforth, this loop
 2645: iterates @var{n+1} times; @code{i} produces values starting with @var{n}
 2646: and ending with 0. Other Forth systems may behave differently, even if
 2647: they support @code{FOR} loops. To avoid problems, don't use @code{FOR}
 2648: loops.
 2649: 
 2650: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
 2651: @subsection Arbitrary control structures
 2652: @cindex control structures, user-defined
 2653: 
 2654: @cindex control-flow stack
 2655: ANS Forth permits and supports using control structures in a non-nested
 2656: way. Information about incomplete control structures is stored on the
 2657: control-flow stack. This stack may be implemented on the Forth data
 2658: stack, and this is what we have done in Gforth.
 2659: 
 2660: @cindex @code{orig}, control-flow stack item
 2661: @cindex @code{dest}, control-flow stack item
 2662: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
 2663: entry represents a backward branch target. A few words are the basis for
 2664: building any control structure possible (except control structures that
 2665: need storage, like calls, coroutines, and backtracking).
 2666: 
 2667: doc-if
 2668: doc-ahead
 2669: doc-then
 2670: doc-begin
 2671: doc-until
 2672: doc-again
 2673: doc-cs-pick
 2674: doc-cs-roll
 2675: 
 2676: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
 2677: manipulate the control-flow stack in a portable way. Without them, you
 2678: would need to know how many stack items are occupied by a control-flow
 2679: entry (many systems use one cell. In Gforth they currently take three,
 2680: but this may change in the future).
 2681: 
 2682: 
 2683: Some standard control structure words are built from these words:
 2684: 
 2685: doc-else
 2686: doc-while
 2687: doc-repeat
 2688: 
 2689: Gforth adds some more control-structure words:
 2690: 
 2691: doc-endif
 2692: doc-?dup-if
 2693: doc-?dup-0=-if
 2694: 
 2695: Counted loop words constitute a separate group of words:
 2696: 
 2697: doc-?do
 2698: doc-+do
 2699: doc-u+do
 2700: doc--do
 2701: doc-u-do
 2702: doc-do
 2703: doc-for
 2704: doc-loop
 2705: doc-+loop
 2706: doc--loop
 2707: doc-next
 2708: doc-leave
 2709: doc-?leave
 2710: doc-unloop
 2711: doc-done
 2712: 
 2713: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
 2714: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
 2715: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
 2716: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
 2717: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
 2718: resolved (by using one of the loop-ending words or @code{DONE}).
 2719: 
 2720: Another group of control structure words are
 2721: 
 2722: doc-case
 2723: doc-endcase
 2724: doc-of
 2725: doc-endof
 2726: 
 2727: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
 2728: @code{CS-ROLL}.
 2729: 
 2730: @subsubsection Programming Style
 2731: 
 2732: In order to ensure readability we recommend that you do not create
 2733: arbitrary control structures directly, but define new control structure
 2734: words for the control structure you want and use these words in your
 2735: program.
 2736: 
 2737: E.g., instead of writing:
 2738: 
 2739: @example
 2740: begin
 2741:   ...
 2742: if [ 1 cs-roll ]
 2743:   ...
 2744: again then
 2745: @end example
 2746: 
 2747: @noindent
 2748: we recommend defining control structure words, e.g.,
 2749: 
 2750: @example
 2751: : while ( dest -- orig dest )
 2752:  POSTPONE if
 2753:  1 cs-roll ; immediate
 2754: 
 2755: : repeat ( orig dest -- )
 2756:  POSTPONE again
 2757:  POSTPONE then ; immediate
 2758: @end example
 2759: 
 2760: @noindent
 2761: and then using these to create the control structure:
 2762: 
 2763: @example
 2764: begin
 2765:   ...
 2766: while
 2767:   ...
 2768: repeat
 2769: @end example
 2770: 
 2771: That's much easier to read, isn't it? Of course, @code{REPEAT} and
 2772: @code{WHILE} are predefined, so in this example it would not be
 2773: necessary to define them.
 2774: 
 2775: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
 2776: @subsection Calls and returns
 2777: @cindex calling a definition
 2778: @cindex returning from a definition
 2779: 
 2780: @cindex recursive definitions
 2781: A definition can be called simply be writing the name of the definition
 2782: to be called. Note that normally a definition is invisible during its
 2783: definition. If you want to write a directly recursive definition, you
 2784: can use @code{recursive} to make the current definition visible.
 2785: 
 2786: doc-recursive
 2787: 
 2788: Another way to perform a recursive call is
 2789: 
 2790: doc-recurse
 2791: 
 2792: @comment TODO add example of the two recursion methods
 2793: @quotation
 2794: @progstyle
 2795: I prefer using @code{recursive} to @code{recurse}, because calling the
 2796: definition by name is more descriptive (if the name is well-chosen) than
 2797: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
 2798: implementation, it is much better to read (and think) ``now sort the
 2799: partitions'' than to read ``now do a recursive call''.
 2800: @end quotation
 2801: 
 2802: @comment TODO maybe move deferred words to Defining Words section and x-ref
 2803: @comment from here.. that is where these two are glossed.
 2804: 
 2805: For mutual recursion, use @code{defer}red words, like this:
 2806: 
 2807: @example
 2808: defer foo
 2809: 
 2810: : bar ( ... -- ... )
 2811:  ... foo ... ;
 2812: 
 2813: :noname ( ... -- ... )
 2814:  ... bar ... ;
 2815: IS foo
 2816: @end example
 2817: 
 2818: When the end of the definition is reached, it returns. An earlier return
 2819: can be forced using
 2820: 
 2821: doc-exit
 2822: 
 2823: Don't forget to clean up the return stack and @code{UNLOOP} any
 2824: outstanding @code{?DO}...@code{LOOP}s before @code{EXIT}ing.
 2825: 
 2826: doc-;s
 2827: 
 2828: @node Exception Handling,  , Calls and returns, Control Structures
 2829: @subsection Exception Handling
 2830: @cindex Exceptions
 2831: 
 2832: @comment TODO examples and blurb
 2833: doc-catch
 2834: doc-throw
 2835: @comment TODO -- think this will alllcate you a new THROW code?
 2836: @comment for reserving new exception numbers. Note the existence of compat/exception.fs
 2837: doc---exception-exception
 2838: doc-quit
 2839: doc-abort
 2840: doc-abort"
 2841: 
 2842: 
 2843: @node Locals, Defining Words, Control Structures, Words
 2844: @section Locals
 2845: @cindex locals
 2846: 
 2847: Local variables can make Forth programming more enjoyable and Forth
 2848: programs easier to read. Unfortunately, the locals of ANS Forth are
 2849: laden with restrictions. Therefore, we provide not only the ANS Forth
 2850: locals wordset, but also our own, more powerful locals wordset (we
 2851: implemented the ANS Forth locals wordset through our locals wordset).
 2852: 
 2853: The ideas in this section have also been published in the paper
 2854: @cite{Automatic Scoping of Local Variables} by M. Anton Ertl, presented
 2855: at EuroForth '94; it is available at
 2856: @*@url{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz}.
 2857: 
 2858: @menu
 2859: * Gforth locals::               
 2860: * ANS Forth locals::            
 2861: @end menu
 2862: 
 2863: @node Gforth locals, ANS Forth locals, Locals, Locals
 2864: @subsection Gforth locals
 2865: @cindex Gforth locals
 2866: @cindex locals, Gforth style
 2867: 
 2868: Locals can be defined with
 2869: 
 2870: @example
 2871: @{ local1 local2 ... -- comment @}
 2872: @end example
 2873: or
 2874: @example
 2875: @{ local1 local2 ... @}
 2876: @end example
 2877: 
 2878: E.g.,
 2879: @example
 2880: : max @{ n1 n2 -- n3 @}
 2881:  n1 n2 > if
 2882:    n1
 2883:  else
 2884:    n2
 2885:  endif ;
 2886: @end example
 2887: 
 2888: The similarity of locals definitions with stack comments is intended. A
 2889: locals definition often replaces the stack comment of a word. The order
 2890: of the locals corresponds to the order in a stack comment and everything
 2891: after the @code{--} is really a comment.
 2892: 
 2893: This similarity has one disadvantage: It is too easy to confuse locals
 2894: declarations with stack comments, causing bugs and making them hard to
 2895: find. However, this problem can be avoided by appropriate coding
 2896: conventions: Do not use both notations in the same program. If you do,
 2897: they should be distinguished using additional means, e.g. by position.
 2898: 
 2899: @cindex types of locals
 2900: @cindex locals types
 2901: The name of the local may be preceded by a type specifier, e.g.,
 2902: @code{F:} for a floating point value:
 2903: 
 2904: @example
 2905: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
 2906: \ complex multiplication
 2907:  Ar Br f* Ai Bi f* f-
 2908:  Ar Bi f* Ai Br f* f+ ;
 2909: @end example
 2910: 
 2911: @cindex flavours of locals
 2912: @cindex locals flavours
 2913: @cindex value-flavoured locals
 2914: @cindex variable-flavoured locals
 2915: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
 2916: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
 2917: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
 2918: with @code{W:}, @code{D:} etc.) produces its value and can be changed
 2919: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
 2920: produces its address (which becomes invalid when the variable's scope is
 2921: left). E.g., the standard word @code{emit} can be defined in terms of
 2922: @code{type} like this:
 2923: 
 2924: @example
 2925: : emit @{ C^ char* -- @}
 2926:     char* 1 type ;
 2927: @end example
 2928: 
 2929: @cindex default type of locals
 2930: @cindex locals, default type
 2931: A local without type specifier is a @code{W:} local. Both flavours of
 2932: locals are initialized with values from the data or FP stack.
 2933: 
 2934: Currently there is no way to define locals with user-defined data
 2935: structures, but we are working on it.
 2936: 
 2937: Gforth allows defining locals everywhere in a colon definition. This
 2938: poses the following questions:
 2939: 
 2940: @menu
 2941: * Where are locals visible by name?::  
 2942: * How long do locals live?::    
 2943: * Programming Style::           
 2944: * Implementation::              
 2945: @end menu
 2946: 
 2947: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
 2948: @subsubsection Where are locals visible by name?
 2949: @cindex locals visibility
 2950: @cindex visibility of locals
 2951: @cindex scope of locals
 2952: 
 2953: Basically, the answer is that locals are visible where you would expect
 2954: it in block-structured languages, and sometimes a little longer. If you
 2955: want to restrict the scope of a local, enclose its definition in
 2956: @code{SCOPE}...@code{ENDSCOPE}.
 2957: 
 2958: doc-scope
 2959: doc-endscope
 2960: 
 2961: These words behave like control structure words, so you can use them
 2962: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
 2963: arbitrary ways.
 2964: 
 2965: If you want a more exact answer to the visibility question, here's the
 2966: basic principle: A local is visible in all places that can only be
 2967: reached through the definition of the local@footnote{In compiler
 2968: construction terminology, all places dominated by the definition of the
 2969: local.}. In other words, it is not visible in places that can be reached
 2970: without going through the definition of the local. E.g., locals defined
 2971: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
 2972: defined in @code{BEGIN}...@code{UNTIL} are visible after the
 2973: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
 2974: 
 2975: The reasoning behind this solution is: We want to have the locals
 2976: visible as long as it is meaningful. The user can always make the
 2977: visibility shorter by using explicit scoping. In a place that can
 2978: only be reached through the definition of a local, the meaning of a
 2979: local name is clear. In other places it is not: How is the local
 2980: initialized at the control flow path that does not contain the
 2981: definition? Which local is meant, if the same name is defined twice in
 2982: two independent control flow paths?
 2983: 
 2984: This should be enough detail for nearly all users, so you can skip the
 2985: rest of this section. If you really must know all the gory details and
 2986: options, read on.
 2987: 
 2988: In order to implement this rule, the compiler has to know which places
 2989: are unreachable. It knows this automatically after @code{AHEAD},
 2990: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
 2991: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
 2992: compiler that the control flow never reaches that place. If
 2993: @code{UNREACHABLE} is not used where it could, the only consequence is
 2994: that the visibility of some locals is more limited than the rule above
 2995: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
 2996: lie to the compiler), buggy code will be produced.
 2997: 
 2998: doc-unreachable
 2999: 
 3000: Another problem with this rule is that at @code{BEGIN}, the compiler
 3001: does not know which locals will be visible on the incoming
 3002: back-edge. All problems discussed in the following are due to this
 3003: ignorance of the compiler (we discuss the problems using @code{BEGIN}
 3004: loops as examples; the discussion also applies to @code{?DO} and other
 3005: loops). Perhaps the most insidious example is:
 3006: @example
 3007: AHEAD
 3008: BEGIN
 3009:   x
 3010: [ 1 CS-ROLL ] THEN
 3011:   @{ x @}
 3012:   ...
 3013: UNTIL
 3014: @end example
 3015: 
 3016: This should be legal according to the visibility rule. The use of
 3017: @code{x} can only be reached through the definition; but that appears
 3018: textually below the use.
 3019: 
 3020: From this example it is clear that the visibility rules cannot be fully
 3021: implemented without major headaches. Our implementation treats common
 3022: cases as advertised and the exceptions are treated in a safe way: The
 3023: compiler makes a reasonable guess about the locals visible after a
 3024: @code{BEGIN}; if it is too pessimistic, the
 3025: user will get a spurious error about the local not being defined; if the
 3026: compiler is too optimistic, it will notice this later and issue a
 3027: warning. In the case above the compiler would complain about @code{x}
 3028: being undefined at its use. You can see from the obscure examples in
 3029: this section that it takes quite unusual control structures to get the
 3030: compiler into trouble, and even then it will often do fine.
 3031: 
 3032: If the @code{BEGIN} is reachable from above, the most optimistic guess
 3033: is that all locals visible before the @code{BEGIN} will also be
 3034: visible after the @code{BEGIN}. This guess is valid for all loops that
 3035: are entered only through the @code{BEGIN}, in particular, for normal
 3036: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
 3037: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
 3038: compiler. When the branch to the @code{BEGIN} is finally generated by
 3039: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
 3040: warns the user if it was too optimistic:
 3041: @example
 3042: IF
 3043:   @{ x @}
 3044: BEGIN
 3045:   \ x ? 
 3046: [ 1 cs-roll ] THEN
 3047:   ...
 3048: UNTIL
 3049: @end example
 3050: 
 3051: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
 3052: optimistically assumes that it lives until the @code{THEN}. It notices
 3053: this difference when it compiles the @code{UNTIL} and issues a
 3054: warning. The user can avoid the warning, and make sure that @code{x}
 3055: is not used in the wrong area by using explicit scoping:
 3056: @example
 3057: IF
 3058:   SCOPE
 3059:   @{ x @}
 3060:   ENDSCOPE
 3061: BEGIN
 3062: [ 1 cs-roll ] THEN
 3063:   ...
 3064: UNTIL
 3065: @end example
 3066: 
 3067: Since the guess is optimistic, there will be no spurious error messages
 3068: about undefined locals.
 3069: 
 3070: If the @code{BEGIN} is not reachable from above (e.g., after
 3071: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
 3072: optimistic guess, as the locals visible after the @code{BEGIN} may be
 3073: defined later. Therefore, the compiler assumes that no locals are
 3074: visible after the @code{BEGIN}. However, the user can use
 3075: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
 3076: visible at the BEGIN as at the point where the top control-flow stack
 3077: item was created.
 3078: 
 3079: doc-assume-live
 3080: 
 3081: E.g.,
 3082: @example
 3083: @{ x @}
 3084: AHEAD
 3085: ASSUME-LIVE
 3086: BEGIN
 3087:   x
 3088: [ 1 CS-ROLL ] THEN
 3089:   ...
 3090: UNTIL
 3091: @end example
 3092: 
 3093: Other cases where the locals are defined before the @code{BEGIN} can be
 3094: handled by inserting an appropriate @code{CS-ROLL} before the
 3095: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
 3096: behind the @code{ASSUME-LIVE}).
 3097: 
 3098: Cases where locals are defined after the @code{BEGIN} (but should be
 3099: visible immediately after the @code{BEGIN}) can only be handled by
 3100: rearranging the loop. E.g., the ``most insidious'' example above can be
 3101: arranged into:
 3102: @example
 3103: BEGIN
 3104:   @{ x @}
 3105:   ... 0=
 3106: WHILE
 3107:   x
 3108: REPEAT
 3109: @end example
 3110: 
 3111: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
 3112: @subsubsection How long do locals live?
 3113: @cindex locals lifetime
 3114: @cindex lifetime of locals
 3115: 
 3116: The right answer for the lifetime question would be: A local lives at
 3117: least as long as it can be accessed. For a value-flavoured local this
 3118: means: until the end of its visibility. However, a variable-flavoured
 3119: local could be accessed through its address far beyond its visibility
 3120: scope. Ultimately, this would mean that such locals would have to be
 3121: garbage collected. Since this entails un-Forth-like implementation
 3122: complexities, I adopted the same cowardly solution as some other
 3123: languages (e.g., C): The local lives only as long as it is visible;
 3124: afterwards its address is invalid (and programs that access it
 3125: afterwards are erroneous).
 3126: 
 3127: @node Programming Style, Implementation, How long do locals live?, Gforth locals
 3128: @subsubsection Programming Style
 3129: @cindex locals programming style
 3130: @cindex programming style, locals
 3131: 
 3132: The freedom to define locals anywhere has the potential to change
 3133: programming styles dramatically. In particular, the need to use the
 3134: return stack for intermediate storage vanishes. Moreover, all stack
 3135: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
 3136: determined arguments) can be eliminated: If the stack items are in the
 3137: wrong order, just write a locals definition for all of them; then
 3138: write the items in the order you want.
 3139: 
 3140: This seems a little far-fetched and eliminating stack manipulations is
 3141: unlikely to become a conscious programming objective. Still, the number
 3142: of stack manipulations will be reduced dramatically if local variables
 3143: are used liberally (e.g., compare @code{max} in @ref{Gforth locals} with
 3144: a traditional implementation of @code{max}).
 3145: 
 3146: This shows one potential benefit of locals: making Forth programs more
 3147: readable. Of course, this benefit will only be realized if the
 3148: programmers continue to honour the principle of factoring instead of
 3149: using the added latitude to make the words longer.
 3150: 
 3151: @cindex single-assignment style for locals
 3152: Using @code{TO} can and should be avoided.  Without @code{TO},
 3153: every value-flavoured local has only a single assignment and many
 3154: advantages of functional languages apply to Forth. I.e., programs are
 3155: easier to analyse, to optimize and to read: It is clear from the
 3156: definition what the local stands for, it does not turn into something
 3157: different later.
 3158: 
 3159: E.g., a definition using @code{TO} might look like this:
 3160: @example
 3161: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 3162:  u1 u2 min 0
 3163:  ?do
 3164:    addr1 c@@ addr2 c@@ -
 3165:    ?dup-if
 3166:      unloop exit
 3167:    then
 3168:    addr1 char+ TO addr1
 3169:    addr2 char+ TO addr2
 3170:  loop
 3171:  u1 u2 - ;
 3172: @end example
 3173: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
 3174: every loop iteration. @code{strcmp} is a typical example of the
 3175: readability problems of using @code{TO}. When you start reading
 3176: @code{strcmp}, you think that @code{addr1} refers to the start of the
 3177: string. Only near the end of the loop you realize that it is something
 3178: else.
 3179: 
 3180: This can be avoided by defining two locals at the start of the loop that
 3181: are initialized with the right value for the current iteration.
 3182: @example
 3183: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 3184:  addr1 addr2
 3185:  u1 u2 min 0 
 3186:  ?do @{ s1 s2 @}
 3187:    s1 c@@ s2 c@@ -
 3188:    ?dup-if
 3189:      unloop exit
 3190:    then
 3191:    s1 char+ s2 char+
 3192:  loop
 3193:  2drop
 3194:  u1 u2 - ;
 3195: @end example
 3196: Here it is clear from the start that @code{s1} has a different value
 3197: in every loop iteration.
 3198: 
 3199: @node Implementation,  , Programming Style, Gforth locals
 3200: @subsubsection Implementation
 3201: @cindex locals implementation
 3202: @cindex implementation of locals
 3203: 
 3204: @cindex locals stack
 3205: Gforth uses an extra locals stack. The most compelling reason for
 3206: this is that the return stack is not float-aligned; using an extra stack
 3207: also eliminates the problems and restrictions of using the return stack
 3208: as locals stack. Like the other stacks, the locals stack grows toward
 3209: lower addresses. A few primitives allow an efficient implementation:
 3210: 
 3211: doc-@local#
 3212: doc-f@local#
 3213: doc-laddr#
 3214: doc-lp+!#
 3215: doc-lp!
 3216: doc->l
 3217: doc-f>l
 3218: 
 3219: In addition to these primitives, some specializations of these
 3220: primitives for commonly occurring inline arguments are provided for
 3221: efficiency reasons, e.g., @code{@@local0} as specialization of
 3222: @code{@@local#} for the inline argument 0. The following compiling words
 3223: compile the right specialized version, or the general version, as
 3224: appropriate:
 3225: 
 3226: doc-compile-@local
 3227: doc-compile-f@local
 3228: doc-compile-lp+!
 3229: 
 3230: Combinations of conditional branches and @code{lp+!#} like
 3231: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
 3232: is taken) are provided for efficiency and correctness in loops.
 3233: 
 3234: A special area in the dictionary space is reserved for keeping the
 3235: local variable names. @code{@{} switches the dictionary pointer to this
 3236: area and @code{@}} switches it back and generates the locals
 3237: initializing code. @code{W:} etc.@ are normal defining words. This
 3238: special area is cleared at the start of every colon definition.
 3239: 
 3240: @cindex word list for defining locals
 3241: A special feature of Gforth's dictionary is used to implement the
 3242: definition of locals without type specifiers: every word list (aka
 3243: vocabulary) has its own methods for searching
 3244: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
 3245: with a special search method: When it is searched for a word, it
 3246: actually creates that word using @code{W:}. @code{@{} changes the search
 3247: order to first search the word list containing @code{@}}, @code{W:} etc.,
 3248: and then the word list for defining locals without type specifiers.
 3249: 
 3250: The lifetime rules support a stack discipline within a colon
 3251: definition: The lifetime of a local is either nested with other locals
 3252: lifetimes or it does not overlap them.
 3253: 
 3254: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
 3255: pointer manipulation is generated. Between control structure words
 3256: locals definitions can push locals onto the locals stack. @code{AGAIN}
 3257: is the simplest of the other three control flow words. It has to
 3258: restore the locals stack depth of the corresponding @code{BEGIN}
 3259: before branching. The code looks like this:
 3260: @format
 3261: @code{lp+!#} current-locals-size @minus{} dest-locals-size
 3262: @code{branch} <begin>
 3263: @end format
 3264: 
 3265: @code{UNTIL} is a little more complicated: If it branches back, it
 3266: must adjust the stack just like @code{AGAIN}. But if it falls through,
 3267: the locals stack must not be changed. The compiler generates the
 3268: following code:
 3269: @format
 3270: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
 3271: @end format
 3272: The locals stack pointer is only adjusted if the branch is taken.
 3273: 
 3274: @code{THEN} can produce somewhat inefficient code:
 3275: @format
 3276: @code{lp+!#} current-locals-size @minus{} orig-locals-size
 3277: <orig target>:
 3278: @code{lp+!#} orig-locals-size @minus{} new-locals-size
 3279: @end format
 3280: The second @code{lp+!#} adjusts the locals stack pointer from the
 3281: level at the @var{orig} point to the level after the @code{THEN}. The
 3282: first @code{lp+!#} adjusts the locals stack pointer from the current
 3283: level to the level at the orig point, so the complete effect is an
 3284: adjustment from the current level to the right level after the
 3285: @code{THEN}.
 3286: 
 3287: @cindex locals information on the control-flow stack
 3288: @cindex control-flow stack items, locals information
 3289: In a conventional Forth implementation a dest control-flow stack entry
 3290: is just the target address and an orig entry is just the address to be
 3291: patched. Our locals implementation adds a word list to every orig or dest
 3292: item. It is the list of locals visible (or assumed visible) at the point
 3293: described by the entry. Our implementation also adds a tag to identify
 3294: the kind of entry, in particular to differentiate between live and dead
 3295: (reachable and unreachable) orig entries.
 3296: 
 3297: A few unusual operations have to be performed on locals word lists:
 3298: 
 3299: doc-common-list
 3300: doc-sub-list?
 3301: doc-list-size
 3302: 
 3303: Several features of our locals word list implementation make these
 3304: operations easy to implement: The locals word lists are organised as
 3305: linked lists; the tails of these lists are shared, if the lists
 3306: contain some of the same locals; and the address of a name is greater
 3307: than the address of the names behind it in the list.
 3308: 
 3309: Another important implementation detail is the variable
 3310: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
 3311: determine if they can be reached directly or only through the branch
 3312: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
 3313: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
 3314: definition, by @code{BEGIN} and usually by @code{THEN}.
 3315: 
 3316: Counted loops are similar to other loops in most respects, but
 3317: @code{LEAVE} requires special attention: It performs basically the same
 3318: service as @code{AHEAD}, but it does not create a control-flow stack
 3319: entry. Therefore the information has to be stored elsewhere;
 3320: traditionally, the information was stored in the target fields of the
 3321: branches created by the @code{LEAVE}s, by organizing these fields into a
 3322: linked list. Unfortunately, this clever trick does not provide enough
 3323: space for storing our extended control flow information. Therefore, we
 3324: introduce another stack, the leave stack. It contains the control-flow
 3325: stack entries for all unresolved @code{LEAVE}s.
 3326: 
 3327: Local names are kept until the end of the colon definition, even if
 3328: they are no longer visible in any control-flow path. In a few cases
 3329: this may lead to increased space needs for the locals name area, but
 3330: usually less than reclaiming this space would cost in code size.
 3331: 
 3332: 
 3333: @node ANS Forth locals,  , Gforth locals, Locals
 3334: @subsection ANS Forth locals
 3335: @cindex locals, ANS Forth style
 3336: 
 3337: The ANS Forth locals wordset does not define a syntax for locals, but
 3338: words that make it possible to define various syntaxes. One of the
 3339: possible syntaxes is a subset of the syntax we used in the Gforth locals
 3340: wordset, i.e.:
 3341: 
 3342: @example
 3343: @{ local1 local2 ... -- comment @}
 3344: @end example
 3345: or
 3346: @example
 3347: @{ local1 local2 ... @}
 3348: @end example
 3349: 
 3350: The order of the locals corresponds to the order in a stack comment. The
 3351: restrictions are:
 3352: 
 3353: @itemize @bullet
 3354: @item
 3355: Locals can only be cell-sized values (no type specifiers are allowed).
 3356: @item
 3357: Locals can be defined only outside control structures.
 3358: @item
 3359: Locals can interfere with explicit usage of the return stack. For the
 3360: exact (and long) rules, see the standard. If you don't use return stack
 3361: accessing words in a definition using locals, you will be all right. The
 3362: purpose of this rule is to make locals implementation on the return
 3363: stack easier.
 3364: @item
 3365: The whole definition must be in one line.
 3366: @end itemize
 3367: 
 3368: Locals defined in this way behave like @code{VALUE}s (@xref{Simple
 3369: Defining Words}). I.e., they are initialized from the stack. Using their
 3370: name produces their value. Their value can be changed using @code{TO}.
 3371: 
 3372: Since this syntax is supported by Gforth directly, you need not do
 3373: anything to use it. If you want to port a program using this syntax to
 3374: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
 3375: syntax on the other system.
 3376: 
 3377: Note that a syntax shown in the standard, section A.13 looks
 3378: similar, but is quite different in having the order of locals
 3379: reversed. Beware!
 3380: 
 3381: The ANS Forth locals wordset itself consists of the following word
 3382: 
 3383: doc-(local)
 3384: 
 3385: The ANS Forth locals extension wordset defines a syntax, but it is so
 3386: awful that we strongly recommend not to use it. We have implemented this
 3387: syntax to make porting to Gforth easy, but do not document it here. The
 3388: problem with this syntax is that the locals are defined in an order
 3389: reversed with respect to the standard stack comment notation, making
 3390: programs harder to read, and easier to misread and miswrite. The only
 3391: merit of this syntax is that it is easy to implement using the ANS Forth
 3392: locals wordset.
 3393: 
 3394: @node Defining Words, The Text Interpreter, Locals, Words
 3395: @section Defining Words
 3396: @cindex defining words
 3397: 
 3398: @menu
 3399: * Simple Defining Words::       
 3400: * Colon Definitions::           
 3401: * User-defined Defining Words::  
 3402: * Supplying names::             
 3403: * Interpretation and Compilation Semantics::  
 3404: @end menu
 3405: 
 3406: @node Simple Defining Words, Colon Definitions, Defining Words, Defining Words
 3407: @subsection Simple Defining Words
 3408: @cindex simple defining words
 3409: @cindex defining words, simple
 3410: 
 3411: doc-constant
 3412: doc-2constant
 3413: doc-fconstant
 3414: doc-variable
 3415: doc-2variable
 3416: doc-fvariable
 3417: doc-create
 3418: doc-user
 3419: doc-value
 3420: doc-to
 3421: doc-defer
 3422: doc-is
 3423: 
 3424: Definitions in ANS Standard Forth for @code{defer}, @code{<is>} and
 3425: @code{[is]} are provided in @file{compat/defer.fs}. TODO - what do
 3426: the two is words do?
 3427: 
 3428: @node Colon Definitions, User-defined Defining Words, Simple Defining Words, Defining Words
 3429: @subsection Colon Definitions
 3430: @cindex colon definitions
 3431: 
 3432: @example
 3433: : name ( ... -- ... )
 3434:     word1 word2 word3 ;
 3435: @end example
 3436: 
 3437: creates a word called @code{name}, that, upon execution, executes
 3438: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
 3439: 
 3440: The explanation above is somewhat superficial. @xref{Interpretation and
 3441: Compilation Semantics} for an in-depth discussion of some of the issues
 3442: involved.
 3443: 
 3444: doc-:
 3445: doc-;
 3446: 
 3447: @node User-defined Defining Words, Supplying names, Colon Definitions, Defining Words
 3448: @subsection User-defined Defining Words
 3449: @cindex user-defined defining words
 3450: @cindex defining words, user-defined
 3451: 
 3452: You can create new defining words simply by wrapping defining-time code
 3453: around existing defining words and putting the sequence in a colon
 3454: definition.
 3455: 
 3456: @comment TODO example
 3457: 
 3458: @cindex @code{CREATE} ... @code{DOES>}
 3459: If you want the words defined with your defining words to behave
 3460: differently from words defined with standard defining words, you can
 3461: write your defining word like this:
 3462: 
 3463: @example
 3464: : def-word ( "name" -- )
 3465:     Create @var{code1}
 3466: DOES> ( ... -- ... )
 3467:     @var{code2} ;
 3468: 
 3469: def-word name
 3470: @end example
 3471: 
 3472: Technically, this fragment defines a defining word @code{def-word}, and
 3473: a word @code{name}; when you execute @code{name}, the address of the
 3474: body of @code{name} is put on the data stack and @var{code2} is executed
 3475: (the address of the body of @code{name} is the address @code{HERE}
 3476: returns immediately after the @code{CREATE}). The word @code{name} is
 3477: sometimes called a @var{child} of @code{def-word}.
 3478: 
 3479: In other words, if you make the following definitions:
 3480: 
 3481: @example
 3482: : def-word1 ( "name" -- )
 3483:     Create @var{code1} ;
 3484: 
 3485: : action1 ( ... -- ... )
 3486:     @var{code2} ;
 3487: 
 3488: def-word name1
 3489: @end example
 3490: 
 3491: Using @code{name1 action1} is equivalent to using @code{name}.
 3492: 
 3493: E.g., you can implement @code{Constant} in this way:
 3494: 
 3495: @example
 3496: : constant ( w "name" -- )
 3497:     create ,
 3498: DOES> ( -- w )
 3499:     @@ ;
 3500: @end example
 3501: 
 3502: @comment that is the classic example.. maybe it should be earlier. There
 3503: @comment is a beautiful description of how this works and what it does in
 3504: @comment the Forthwrite 100th edition.
 3505: 
 3506: When you create a constant with @code{5 constant five}, first a new word
 3507: @code{five} is created, then the value 5 is laid down in the body of
 3508: @code{five} with @code{,}. When @code{five} is invoked, the address of
 3509: the body is put on the stack, and @code{@@} retrieves the value 5.
 3510: 
 3511: @cindex stack effect of @code{DOES>}-parts
 3512: @cindex @code{DOES>}-parts, stack effect
 3513: In the example above the stack comment after the @code{DOES>} specifies
 3514: the stack effect of the defined words, not the stack effect of the
 3515: following code (the following code expects the address of the body on
 3516: the top of stack, which is not reflected in the stack comment). This is
 3517: the convention that I use and recommend (it clashes a bit with using
 3518: locals declarations for stack effect specification, though).
 3519: 
 3520: @subsubsection Applications of @code{CREATE..DOES>}
 3521: @cindex @code{CREATE} ... @code{DOES>}, applications
 3522: 
 3523: You may wonder how to use this feature. Here are some usage patterns:
 3524: 
 3525: @cindex factoring similar colon definitions
 3526: When you see a sequence of code occurring several times, and you can
 3527: identify a meaning, you will factor it out as a colon definition. When
 3528: you see similar colon definitions, you can factor them using
 3529: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
 3530: that look very similar:
 3531: @example
 3532: : ori, ( reg-target reg-source n -- )
 3533:     0 asm-reg-reg-imm ;
 3534: : andi, ( reg-target reg-source n -- )
 3535:     1 asm-reg-reg-imm ;
 3536: @end example
 3537: 
 3538: @noindent
 3539: This could be factored with:
 3540: @example
 3541: : reg-reg-imm ( op-code -- )
 3542:     CREATE ,
 3543: DOES> ( reg-target reg-source n -- )
 3544:     @@ asm-reg-reg-imm ;
 3545: 
 3546: 0 reg-reg-imm ori,
 3547: 1 reg-reg-imm andi,
 3548: @end example
 3549: 
 3550: @cindex currying
 3551: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
 3552: supply a part of the parameters for a word (known as @dfn{currying} in
 3553: the functional language community). E.g., @code{+} needs two
 3554: parameters. Creating versions of @code{+} with one parameter fixed can
 3555: be done like this:
 3556: @example
 3557: : curry+ ( n1 -- )
 3558:     CREATE ,
 3559: DOES> ( n2 -- n1+n2 )
 3560:     @@ + ;
 3561: 
 3562:  3 curry+ 3+
 3563: -2 curry+ 2-
 3564: @end example
 3565: 
 3566: @subsubsection The gory details of @code{CREATE..DOES>}
 3567: @cindex @code{CREATE} ... @code{DOES>}, details
 3568: 
 3569: doc-does>
 3570: 
 3571: @cindex @code{DOES>} in a separate definition
 3572: This means that you need not use @code{CREATE} and @code{DOES>} in the
 3573: same definition; you can put the @code{DOES>}-part in a separate
 3574: definition. This allows us to, e.g., select among different DOES>-parts:
 3575: @example
 3576: : does1 
 3577: DOES> ( ... -- ... )
 3578:     ... ;
 3579: 
 3580: : does2
 3581: DOES> ( ... -- ... )
 3582:     ... ;
 3583: 
 3584: : def-word ( ... -- ... )
 3585:     create ...
 3586:     IF
 3587:        does1
 3588:     ELSE
 3589:        does2
 3590:     ENDIF ;
 3591: @end example
 3592: 
 3593: In this example, the selection of whether to use @code{does1} or
 3594: @code{does2} is made at compile-time; at the time that the child word is
 3595: @code{Create}d.
 3596: 
 3597: @cindex @code{DOES>} in interpretation state
 3598: In a standard program you can apply a @code{DOES>}-part only if the last
 3599: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
 3600: will override the behaviour of the last word defined in any case. In a
 3601: standard program, you can use @code{DOES>} only in a colon
 3602: definition. In Gforth, you can also use it in interpretation state, in a
 3603: kind of one-shot mode:
 3604: @example
 3605: CREATE name ( ... -- ... )
 3606:   @var{initialization}
 3607: DOES>
 3608:   @var{code} ;
 3609: @end example
 3610: This is equivalent to the standard
 3611: @example
 3612: :noname
 3613: DOES>
 3614:     @var{code} ;
 3615: CREATE name EXECUTE ( ... -- ... )
 3616:     @var{initialization}
 3617: @end example
 3618: 
 3619: You can get the address of the body of a word with
 3620: 
 3621: doc->body
 3622: 
 3623: @node Supplying names, Interpretation and Compilation Semantics, User-defined Defining Words, Defining Words
 3624: @subsection Supplying names for the defined words
 3625: @cindex names for defined words
 3626: @cindex defining words, name parameter
 3627: 
 3628: @cindex defining words, name given in a string
 3629: By default, defining words take the names for the defined words from the
 3630: input stream. Sometimes you want to supply the name from a string. You
 3631: can do this with:
 3632: 
 3633: doc-nextname
 3634: 
 3635: For example:
 3636: 
 3637: @example
 3638: s" foo" nextname create
 3639: @end example
 3640: @noindent
 3641: is equivalent to:
 3642: @example
 3643: create foo
 3644: @end example
 3645: 
 3646: @cindex defining words without name
 3647: Sometimes you want to define an @var{anonymous word}; a word without a
 3648: name. You can do this with:
 3649: 
 3650: doc-:noname
 3651: 
 3652: This leaves the execution token for the word on the stack after the
 3653: closing @code{;}. Here's an example in which a deferred word is
 3654: initialised with an @code{xt} from an anonymous colon definition:
 3655: @example
 3656: Defer deferred
 3657: :noname ( ... -- ... )
 3658:   ... ;
 3659: IS deferred
 3660: @end example
 3661: 
 3662: Gforth provides an alternative way of doing this, using two separate
 3663: words:
 3664: 
 3665: doc-noname
 3666: @cindex execution token of last defined word
 3667: doc-lastxt
 3668: 
 3669: The previous example can be rewritten using @code{noname} and
 3670: @code{lastxt}:
 3671: 
 3672: @example
 3673: Defer deferred
 3674: noname : ( ... -- ... )
 3675:   ... ;
 3676: lastxt IS deferred
 3677: @end example
 3678: 
 3679: @code{lastxt} also works when the last word was not defined as
 3680: @code{noname}. 
 3681: 
 3682: 
 3683: @node Interpretation and Compilation Semantics,  , Supplying names, Defining Words
 3684: @subsection Interpretation and Compilation Semantics
 3685: @cindex semantics, interpretation and compilation
 3686: 
 3687: @cindex interpretation semantics
 3688: The @dfn{interpretation semantics} of a word are what the text
 3689: interpreter does when it encounters the word in interpret state. It also
 3690: appears in some other contexts, e.g., the execution token returned by
 3691: @code{' @var{word}} identifies the interpretation semantics of
 3692: @var{word} (in other words, @code{' @var{word} execute} is equivalent to
 3693: interpret-state text interpretation of @code{@var{word}}).
 3694: 
 3695: @cindex compilation semantics
 3696: The @dfn{compilation semantics} of a word are what the text interpreter
 3697: does when it encounters the word in compile state. It also appears in
 3698: other contexts, e.g, @code{POSTPONE @var{word}} compiles@footnote{In
 3699: standard terminology, ``appends to the current definition''.} the
 3700: compilation semantics of @var{word}.
 3701: 
 3702: @cindex execution semantics
 3703: The standard also talks about @dfn{execution semantics}. They are used
 3704: only for defining the interpretation and compilation semantics of many
 3705: words. By default, the interpretation semantics of a word are to
 3706: @code{execute} its execution semantics, and the compilation semantics of
 3707: a word are to @code{compile,} its execution semantics.@footnote{In
 3708: standard terminology: The default interpretation semantics are its
 3709: execution semantics; the default compilation semantics are to append its
 3710: execution semantics to the execution semantics of the current
 3711: definition.}
 3712: 
 3713: @comment TODO expand, make it co-operate with new sections on text interpreter.
 3714: 
 3715: @cindex immediate words
 3716: You can change the compilation semantics into @code{execute}ing the
 3717: execution semantics with
 3718: 
 3719: doc-immediate
 3720: 
 3721: @cindex compile-only words
 3722: You can remove the interpretation semantics of a word with
 3723: 
 3724: doc-compile-only
 3725: doc-restrict
 3726: 
 3727: Note that ticking (@code{'}) compile-only words gives an error
 3728: (``Interpreting a compile-only word'').
 3729: 
 3730: Gforth also allows you to define words with arbitrary combinations of
 3731: interpretation and compilation semantics.
 3732: 
 3733: doc-interpret/compile:
 3734: 
 3735: This feature was introduced for implementing @code{TO} and @code{S"}. I
 3736: recommend that you do not define such words, as cute as they may be:
 3737: they make it hard to get at both parts of the word in some contexts.
 3738: E.g., assume you want to get an execution token for the compilation
 3739: part. Instead, define two words, one that embodies the interpretation
 3740: part, and one that embodies the compilation part.  Once you have done
 3741: that, you can define a combined word with @code{interpret/compile:} for
 3742: the convenience of your users.
 3743: 
 3744: You also might try to provide an optimizing implementation of the
 3745: default compilation semantics with this feature, like this:
 3746: 
 3747: @example
 3748: :noname
 3749:    foo bar ;
 3750: :noname
 3751:    POSTPONE foo POSTPONE bar ;
 3752: interpret/compile: foobar
 3753: @end example
 3754: 
 3755: @noindent
 3756: as an optimizing version of:
 3757: 
 3758: @example
 3759: : foobar
 3760:     foo bar ;
 3761: @end example
 3762: 
 3763: Unfortunately, this does not work correctly with @code{[compile]},
 3764: because @code{[compile]} assumes that the compilation semantics of all
 3765: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
 3766: foobar} would compile the compilation semantics for the optimizing
 3767: @code{foobar}, whereas it would compile the interpretation semantics for
 3768: the non-optimizing @code{foobar}.
 3769: 
 3770: @cindex state-smart words are a bad idea
 3771: Some people try to use state-smart words to emulate the feature provided
 3772: by @code{interpret/compile:} (words are state-smart if they check
 3773: @code{STATE} during execution). E.g., they would try to code
 3774: @code{foobar} like this:
 3775: 
 3776: @example
 3777: : foobar
 3778:   STATE @@
 3779:   IF ( compilation state )
 3780:     POSTPONE foo POSTPONE bar
 3781:   ELSE
 3782:     foo bar
 3783:   ENDIF ; immediate
 3784: @end example
 3785: 
 3786: While this works if @code{foobar} is processed only by the text
 3787: interpreter, it does not work in other contexts (like @code{'} or
 3788: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
 3789: for a state-smart word, not for the interpretation semantics of the
 3790: original @code{foobar}; when you execute this execution token (directly
 3791: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
 3792: state, the result will not be what you expected (i.e., it will not
 3793: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
 3794: write them@footnote{For a more detailed discussion of this topic, see
 3795: @cite{@code{State}-smartness -- Why it is Evil and How to Exorcise it} by Anton
 3796: Ertl; presented at EuroForth '98 and available from
 3797: @url{http://www.complang.tuwien.ac.at/papers/}}!
 3798: 
 3799: @cindex defining words with arbitrary semantics combinations
 3800: It is also possible to write defining words that define words with
 3801: arbitrary combinations of interpretation and compilation semantics. In
 3802: general, this looks like:
 3803: 
 3804: @example
 3805: : def-word
 3806:     create-interpret/compile
 3807:     @var{code1}
 3808: interpretation>
 3809:     @var{code2}
 3810: <interpretation
 3811: compilation>
 3812:     @var{code3}
 3813: <compilation ;
 3814: @end example
 3815: 
 3816: For a @var{word} defined with @code{def-word}, the interpretation
 3817: semantics are to push the address of the body of @var{word} and perform
 3818: @var{code2}, and the compilation semantics are to push the address of
 3819: the body of @var{word} and perform @var{code3}. E.g., @code{constant}
 3820: can also be defined like this (except that the defined constants don't
 3821: behave correctly when @code{[compile]}d):
 3822: 
 3823: @example
 3824: : constant ( n "name" -- )
 3825:     create-interpret/compile
 3826:     ,
 3827: interpretation> ( -- n )
 3828:     @@
 3829: <interpretation
 3830: compilation> ( compilation. -- ; run-time. -- n )
 3831:     @@ postpone literal
 3832: <compilation ;
 3833: @end example
 3834: 
 3835: doc-create-interpret/compile
 3836: doc-interpretation>
 3837: doc-<interpretation
 3838: doc-compilation>
 3839: doc-<compilation
 3840: 
 3841: Note that words defined with @code{interpret/compile:} and
 3842: @code{create-interpret/compile} have an extended header structure that
 3843: differs from other words; however, unless you try to access them with
 3844: plain address arithmetic, you should not notice this. Words for
 3845: accessing the header structure usually know how to deal with this; e.g.,
 3846: @code{' word >body} also gives you the body of a word created with
 3847: @code{create-interpret/compile}.
 3848: 
 3849: @c ----------------------------------------------------------
 3850: @node The Text Interpreter, Structures, Defining Words, Words
 3851: @section  The Text Interpreter
 3852: @cindex interpreter - outer
 3853: @cindex text interpreter
 3854: @cindex outer interpreter
 3855: 
 3856: Blah blah.
 3857: 
 3858: doc->in
 3859: 
 3860: 
 3861: @menu
 3862: * Number Conversion::
 3863: * Interpret/Compile states::
 3864: * Literals::
 3865: * Interpreter Directives::
 3866: @end menu
 3867: 
 3868: 
 3869: 
 3870: invoking it now, by typing @kbd{gforth<return>}). Forth is now running
 3871: its command line interpreter, which is called the "Text Interpreter"
 3872: (also known as the "Outer Interpreter").  The behaviour of the text
 3873: interpreter depends upon whether the system is in "Interpret" or
 3874: "Compile" state. At startup, the system is always in "Interpret" state.
 3875: 
 3876: 
 3877: Behaviour of the text interpreter in "Interpret" state
 3878: ------------------------------------------------------
 3879: 
 3880: Although it may not be obvious, Forth is actually prompting you for
 3881: input. Type a number and press the <return> key:
 3882: 
 3883: 45<return>  ok
 3884: 
 3885: Rather than give you a prompt to invite you to input something, the
 3886: text interpreter prints a status message *after* it has processed a
 3887: line of input. The status message in this case (" ok" followed by
 3888: carriage-return) indicates that the text interpreter was able to
 3889: process all of your input successfully. Now type something illegal:
 3890: 
 3891: qwer341<return>
 3892: ^^^^^^^
 3893: Error: Undefined word
 3894: 
 3895: When the text interpreter detects an error, it discards any remaining
 3896: text on a line, resets certain internal state (including returning to
 3897: "Interpret" state) and prints an error message.
 3898: 
 3899: The text interpreter works on input one line at a time. Starting at
 3900: the beginning of the line, it skips leading spaces (called
 3901: "delimiters") then parses a string (a sequence of non-space
 3902: characters) until it either reaches a space character or it
 3903: reaches the end of the line. Having parsed a string, it then makes two
 3904: attempts to do something with it:
 3905: 
 3906: * It looks the string up in a dictionary of definitions. If the string
 3907:   is found in the dictionary, the string names a "definition" (also
 3908:   known as a "word") and the dictionary search will return an
 3909:   "Execution token" (xt) for the definition and some flags that show
 3910:   when the definition can be used legally. If the definition can be
 3911:   legally executed in "Interpret" mode then the text interpreter will
 3912:   use the xt to execute it, otherwise it will issue an error
 3913:   message. The dictionary is described in more detail in <blah>.
 3914: 
 3915: * If the string is not found in the dictionary, the text interpreter
 3916:   attempts to treat it as a number in the current radix (base 10 after
 3917:   initial startup). If the string represents a legal number in the
 3918:   current radix, the number is pushed onto the appropriate parameter
 3919:   stack. Stacks are discussed in more detail in <blah>. Number
 3920:   conversion is described in more detail in <section about +, -
 3921:   numbers and different number formats>.
 3922: 
 3923: If both of these attempts fail, the remainer of the input line is
 3924: discarded and the text interpreter isses an error message. If one of
 3925: these attempts succeeds, the text interpreter repeats the parsing
 3926: process until the end of the line has been reached. At this point, 
 3927: it prints the status message "  ok" and waits for more input.
 3928: 
 3929: There are two important things to note about the behaviour of the text
 3930: interpreter:
 3931: 
 3932: * it processes each input string to completion before parsing
 3933:   additional characters from the input line.
 3934: 
 3935: * it keeps track of its position in the input line using a variable
 3936:   (called >IN, pronounced "to-in"). The value of >IN can be modified
 3937:   by the execution of definitions in the input line. This means that
 3938:   definitions can "trick" the text interpreter either into skipping
 3939:   sections of the input line or into parsing a section of the
 3940:   input line more than once.
 3941: 
 3942: 
 3943: Stacks, postfix notation and parameter passing
 3944: ----------------------------------------------
 3945: 
 3946: In procedural programming languages (like C and Pascal), the
 3947: building-block of programs is the function or procedure. These
 3948: functions or procedures are called with explicit parameters. For
 3949: example, in C we might write:
 3950: 
 3951: total = total + new_volume(length,height,depth);
 3952: 
 3953: where total, length, height, depth are all variables and new_volume is
 3954: a function-call to another piece of code.
 3955: 
 3956: In Forth, the equivalent to the function or procedure is the
 3957: "definition" and parameters are implicitly passed between definitions
 3958: using a shared stack that is visible to the programmer. Although Forth
 3959: does support variables, the existence of the stack means that they are
 3960: used far less often than in most other programming languages. When the
 3961: text interpreter encounters a number, it will place it on the
 3962: stack. There are several stacks (the actual number is
 3963: implementation-dependent ..) and the particular stack used for any
 3964: operation is implied unambiguously by the operation being
 3965: performed. The stack used for all integer operations is called the
 3966: "data stack", and since this is the stack used most commonly,
 3967: references to "the data stack" are often abbreviated to "the stack".
 3968: 
 3969: The stacks have a LIFO (last-in, first-out) organisation. If you type:
 3970: 
 3971: 1 2 3<return>  ok
 3972: 
 3973: then you have placed three numbers on the (data) stack. An analogy for
 3974: the behaviour of the stack is to take a pack of playing cards and deal
 3975: out the ace (1), 2 and 3 into a pile on the table. The 3 was the last
 3976: card onto the pile ("last-in") and if you take a card off the pile
 3977: then, unless you're prepared to fiddle a bit, the card that you take
 3978: off will be the 3 ("first-out"). The number that will be first-out of
 3979: the stack is called the "top of stack", which is often abbreviated to
 3980: TOS.
 3981: 
 3982: To see how parameters are passed in Forth, we will consider the
 3983: behaviour of the definition "+" (pronounced "plus"). You will not be
 3984: surprised to learn that this definition performs addition. More
 3985: precisely, it adds two number together and produces a result. Where
 3986: does it get the two numbers from? It takes the first two numbers off
 3987: the stack. Where does it place the result? On the stack. To continue
 3988: with the playing-cards analogy, you can perform the behaviour of "+"
 3989: like this:
 3990: 
 3991: - pick up two cards from the stack
 3992: - stare at them intently and ask yourself "what *is* the sum of these
 3993:   two numbers"
 3994: - decide that the answer is 5
 3995: - shuffle the two cards back into the pack and find a 5
 3996: - put a 5 on the remaining ace that's on the table.
 3997: 
 3998: If you don't have a pack of cards handy but you do have Forth running,
 3999: you can use the definition .s to show the current state of the stack,
 4000: without affecting the stack. If you already typed "1 2 3" then you
 4001: should see:
 4002: 
 4003: .s<return> <3> 1 2 3  ok
 4004: 
 4005: The "<3>" is the total number of items on the stack, and the item on
 4006: the far right-hand side is the TOS. You can now type:
 4007: 
 4008: + .s<return> <2> 1 5  ok
 4009: 
 4010: which is correct; there are now 2 items on the stack and the result of
 4011: the addition is 5.
 4012: 
 4013: If you're playing with cards, try doing a second addition; pick up the
 4014: two cards, work out that their sum is 6, shuffle them into the pack,
 4015: look for a 6 and place that on the table. You now have just one item
 4016: on the stack. What happens if you try to do a third addition? Pick up
 4017: the first card, pick up the second card - ah. There is no second
 4018: card. This is called a "stack underflow" and consitutes an error. If
 4019: you try to do the same thing with Forth it will report an error
 4020: (probably a Stack Underflow or an Invalid Memory Address error).
 4021: 
 4022: The opposite situation to a stack underflow is a stack overflow, which
 4023: simply accepts that there is a finite amount of storage space reserved
 4024: for the stack. To stretch the playing card analogy, if you had enough
 4025: packs of cards and you piled the cards up on the table, you would
 4026: eventually be unable to add another card; you'd hit the
 4027: ceiling. Gforth allows you to set the maximum size of the stacks. In
 4028: general, the only time that you will get a stack overflow is because a
 4029: definition has a bug in it and is generating data on the stack
 4030: uncontrollably.
 4031: 
 4032: There's one final use for the playing card analogy. If you model your
 4033: stack using a pack of playing cards, the maximum number of items on
 4034: your stack will be 52 (I assume you didn't use the Joker). The maximum
 4035: *value* of any item on the stack is 13 (the King). In fact, the only
 4036: possible numbers are positive integer numbers 1 through 13; you can't
 4037: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
 4038: think about some of the cards, you can accommodate different
 4039: numbers. For example, you could think of the Jack as representing 0,
 4040: the Queen as representing -1 and the King as representing -2. Your
 4041: *range* remains unchanged (you can still only represent a total of 13
 4042: numbers) but the numbers that you can represent are -2 through 10.
 4043: 
 4044: In that analogy, the limit was the amount of information that a single
 4045: stack entry could hold, and Forth has a similar limit. In Forth, the
 4046: size of a stack entry is called a "cell". The actual size of a cell is
 4047: implementation dependent and affects the maximum value that a stack
 4048: entry can hold. A Standard Forth provides a cell size of at least
 4049: 16-bits, and most desktop systems use a cell size of 32-bits.
 4050: 
 4051: Forth does not do any type checking for you, so you are free to
 4052: manipulate and combine stack items in any way you wish. A convenient
 4053: ways of treating stack items is as 2's complement signed integers, and
 4054: that is what Standard words like "+" do. Therefore you can type:
 4055: 
 4056: -5 12 + .s<return> <1> 7  ok
 4057: 
 4058: If you use numbers and definitions like "+" in order to turn Forth
 4059: into a great big pocket calculator, you will realise that it's rather
 4060: different from a normal calculator. Rather than typing 2 + 3 = you had
 4061: to type 2 3 + (ignore the fact that you had to use .s to see the
 4062: result). The terminology used to describe this difference is to say
 4063: that your calculator uses "Infix Notation" (parameters and operators
 4064: are mixed) whilst Forth uses "Postfix Notation" (parameters and
 4065: operators are separate), also called "Reverse Polish Notation".
 4066: 
 4067: Whilst postfix notation might look confusing to begin with, it has
 4068: several important advantages:
 4069: 
 4070: - it is unambiguous
 4071: - it is more concise
 4072: - it fits naturally with a stack-based system
 4073: 
 4074: To examine these claims in more detail, consider these sums:
 4075: 
 4076: 6 + 5 * 4 =
 4077: 4 * 5 + 6 =
 4078: 
 4079: If you're just learning maths or your maths is very rusty, you will
 4080: probably come up with the answer 44 for the first and 26 for the
 4081: second. If you are a bit of a whizz at maths you will remember the
 4082: *convention* that multiplication takes precendence over addition, and
 4083: you'd come up with the answer 26 both times. To explain the answer 26
 4084: to someone who got the answer 44, you'd probably rewrite the first sum
 4085: like this:
 4086: 
 4087: 6 + (5 * 4) =
 4088: 
 4089: If what you really wanted was to perform the addition before the
 4090: multiplication, you would have to use parentheses to force it.
 4091: 
 4092: If you did the first two sums on a pocket calculator you would probably
 4093: get the right answers, unless you were very cautious and entered them using
 4094: these keystroke sequences:
 4095: 
 4096: 6 + 5 = * 4 =
 4097: 4 * 5 = + 6 =
 4098: 
 4099: Postfix notation is unambiguous because the order that the operators
 4100: are applied is always explicit; that also means that parentheses are
 4101: never required. The operators are *active* (the act of quoting the
 4102: operator makes the operation occur) which removes the need for "=".
 4103: 
 4104: The sum 6 + 5 * 4 can be written (in postfix notation) in two
 4105: equivalent ways:
 4106: 
 4107: 6 5 4 * +      or:
 4108: 5 4 * 6 +
 4109: 
 4110: TODO point out that the order of number is never changed.
 4111: 
 4112: The Structure Of Programs In Forth
 4113: ----------------------------------
 4114: 
 4115: When you start up the Forth compiler, a large number of definitions
 4116: already exist. To develop a new application, use bottom-up programming
 4117: techniques to create new definitions that are defined in terms of
 4118: existing definitions. As you create each definition you can test it
 4119: interactively. Ultimately, you end up with an environment <blah blah>
 4120: 
 4121: Creating new definitions
 4122: ------------------------
 4123: 
 4124: The easiest way to create a new definition is to use a "colon
 4125: definition". In order to provide a few examples (and give you some
 4126: homework) I'm going to introduce a very small set of words but only
 4127: describe what they do very informally, by example.
 4128: 
 4129: +   add the top two numbers on the stack and place the result on the
 4130: stack
 4131: .   print the top stack item
 4132: ."  print text until a " delimiter is found
 4133: CR  print a carriage-return
 4134: :   start a new definition
 4135: ;   end a definition
 4136: DUP blah
 4137: DROP blah
 4138: 
 4139: example 1:
 4140: : greet ." Hello and welcome" ;<return>  ok
 4141: greet<return> Hello and welcome  ok
 4142: greet greet<return> Hello and welcomeHello and welcome  ok
 4143: 
 4144: When you try out this example, be careful to copy the spaces
 4145: accurately; there needs to be a space between each group of characters
 4146: that will be processed by the text interpreter.
 4147: 
 4148: 
 4149: example 2:
 4150: : add-two 2 + . ;<return>  ok
 4151: 5 add-two<return> 7  ok
 4152: 
 4153: 
 4154: - numbers and definitions
 4155: - redefining things .. what uses the old defn and what uses the new one
 4156: - boundary between system definitions and your definitions
 4157: - standards.. a double-edged sword
 4158: - philosophy
 4159: 
 4160: - your first set of definitions
 4161: 
 4162: 
 4163: 
 4164: .. interactive stuff
 4165: 5 3 +  . <return> 8  ok
 4166: 
 4167: could have been split over several lines
 4168: 
 4169: 5 . . <return> 
 4170: 
 4171: - cells and chars
 4172: 
 4173: - the text interpreter in "Compilation" state.
 4174: 
 4175: -- elements of a forth system
 4176:   - text interpreter (outer interpreter)
 4177:   - compiler
 4178:   - inner interpreter
 4179:   - dictionaries and wordlists
 4180:   - stacks
 4181: 
 4182: -- disparate spaces .. may be better to describe that elsewhere.
 4183: 
 4184: 
 4185: 
 4186: @node Number Conversion, Interpret/Compile states, The Text Interpreter, The Text Interpreter
 4187: @subsection Number Conversion
 4188: @cindex Number conversion
 4189: @cindex double-cell numbers, input format
 4190: @cindex input format for double-cell numbers
 4191: @cindex single-cell numbers, input format
 4192: @cindex input format for single-cell numbers
 4193: @cindex floating-point numbers, input format
 4194: @cindex input format for floating-point numbers
 4195: 
 4196: If the text interpreter fails to find a particular string in the name
 4197: dictionary, it attempts to convert it to a number using a set of rules.
 4198: 
 4199: Let <digit> represent any character that is a legal digit in the current
 4200: number base (for example, 0-9 when the number base is decimal or 0-9, A-F
 4201: when the number base is hexadecimal).
 4202: 
 4203: Let <decimal digit> represent any character in the range 0-9.
 4204: 
 4205: @comment TODO need to extend the next defn to support fp format
 4206: Let @{+ | -@} represent the optional presence of either a @code{+} or
 4207: @code{-} character.
 4208: 
 4209: Let * represent any number of instances of the previous character
 4210: (including none).
 4211: 
 4212: Let any other character represent itself.
 4213: 
 4214: Now, the conversion rules are:
 4215: 
 4216: @itemize @bullet
 4217: @item
 4218: A string of the form <digit><digit>* is treated as a single-precision
 4219: (CELL-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
 4220: @item
 4221: A string of the form -<digit><digit>* is treated as a single-precision
 4222: (CELL-sized) negative integer, and is represented using 2's-complement
 4223: arithmetic. Examples are -45 -5681 -0
 4224: @item
 4225: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
 4226: (double-CELL-sized) positive integer. Examples are 3465. 3.465 34.65
 4227: (and note that these all represent the same number).
 4228: @item
 4229: A string of the form -<digit><digit>*.<digit>* is treated as a
 4230: double-precision (double-CELL-sized) negative integer, and is
 4231: represented using 2's-complement arithmetic. Examples are -3465. -3.465
 4232: -34.65 (and note that these all represent the same number).
 4233: @item
 4234: A string of the form @{+ | -@}<decimal digit>@{.@}<decimal digit>*@{e | E@}@{+
 4235: | -@}<decimal digit><decimal digit>* is treated as floating-point
 4236: number. Examples are 1e0 1.e 1.e0 +1e+0 (which all represent the same
 4237: number) +12.E-4 
 4238: @end itemize
 4239: 
 4240: By default, the number base used for integer number conversion is given
 4241: by the contents of a variable named @code{BASE}. Base 10 (decimal) is
 4242: always used for floating-point number conversion.
 4243: 
 4244: doc-base
 4245: doc-hex
 4246: doc-decimal
 4247: 
 4248: @cindex '-prefix for character strings
 4249: @cindex &-prefix for decimal numbers
 4250: @cindex %-prefix for binary numbers
 4251: @cindex $-prefix for hexadecimal numbers
 4252: Gforth allows you to override the value of @code{BASE} by using a prefix
 4253: before the first digit of an (integer) number. Four prefixes are
 4254: supported:
 4255: 
 4256: @itemize @bullet
 4257: @item
 4258: @code{&} -- decimal number
 4259: @item
 4260: @code{%} -- binary number
 4261: @item
 4262: @code{$} -- hexadecimal number
 4263: @item
 4264: @code{'} -- base 256 number
 4265: @end itemize
 4266: 
 4267: Here are some examples, with the equivalent decimal number shown after
 4268: in braces:
 4269: 
 4270: -$41 (-65) %1001101 (205) %1001.0001 (145 - a double-precision number)
 4271: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66)
 4272: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98)
 4273: &905 (905) $abc (2478) $ABC (2478)
 4274: 
 4275: @cindex Number conversion - traps for the unwary
 4276: Number conversion has a number of traps for the unwary:
 4277: 
 4278: @itemize @bullet
 4279: @item
 4280: You cannot determine the current number base using the code sequence
 4281: @code{BASE @@ .} -- the number base is always 10 in the current number
 4282: base. Instead, use something like @code{BASE @@ DECIMAL DUP . BASE !}
 4283: @item
 4284: If the number base is set to a value greater than 14 (for example,
 4285: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
 4286: it to be intepreted as either a single-precision integer or a
 4287: floating-point number (Gforth treats it as an integer). The ambiguity
 4288: can be resolved by explicitly stating the sign of the mantissa and/or
 4289: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
 4290: ambiguity arises; either representation will be treated as a
 4291: floating-point number.
 4292: @item
 4293: There is a word @code{bin} but it does @var{not} set the number base!
 4294: It is used to specify file types.
 4295: @item
 4296: ANS Forth Standard requires the @code{.} of a double-precision number to
 4297: be the final character in the string. Allowing the @code{.} to be
 4298: anywhere after the first digit is a Gforth extension.
 4299: @item
 4300: The number conversion process does not check for overflow.
 4301: @item
 4302: In Gforth, number conversion to floating-point numbers always use base
 4303: 10, irrespective of the value of @code{BASE}. For the ANS Forth
 4304: Standard, conversion to floating-point numbers whilst the value of
 4305: @code{BASE} is not 10 is an ambiguous condition.
 4306: @end itemize
 4307: 
 4308: 
 4309: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
 4310: @subsection Interpret/Compile states
 4311: @cindex Interpret/Compile states
 4312: 
 4313: Blah
 4314: 
 4315: doc-state
 4316: doc-[
 4317: doc-]
 4318: 
 4319: 
 4320: 
 4321: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
 4322: @subsection Literals
 4323: @cindex Literals
 4324: 
 4325: Blah blah
 4326: 
 4327: doc-literal
 4328: doc-2literal
 4329: doc-fliteral
 4330: 
 4331: @node Interpreter Directives, ,Literals, The Text Interpreter
 4332: @subsection Interpreter Directives
 4333: @cindex Interpreter Directives
 4334: 
 4335: These words are usually used outside of definitions; for example, to
 4336: control which parts of a source file are processed by the text
 4337: interpreter. There are only a few ANS Forth Standard words, but Gforth
 4338: supplements these with a rich set of immediate control structure words
 4339: to compensate for the fact that the non-immediate versions can only be
 4340: used in compile state (@pxref{Control Structures}).
 4341: 
 4342: doc-[IF]
 4343: doc-[ELSE]
 4344: doc-[THEN]
 4345: doc-[ENDIF]
 4346: 
 4347: doc-[IFDEF]
 4348: doc-[IFUNDEF]
 4349: 
 4350: doc-[?DO]
 4351: doc-[DO]
 4352: doc-[FOR]
 4353: doc-[LOOP]
 4354: doc-[+LOOP]
 4355: doc-[NEXT]
 4356: 
 4357: doc-[BEGIN]
 4358: doc-[UNTIL]
 4359: doc-[AGAIN]
 4360: doc-[WHILE]
 4361: doc-[REPEAT]
 4362: 
 4363: 
 4364: @c ----------------------------------------------------------
 4365: @node Structures, Object-oriented Forth, The Text Interpreter, Words
 4366: @section  Structures
 4367: @cindex structures
 4368: @cindex records
 4369: 
 4370: This section presents the structure package that comes with Gforth. A
 4371: version of the package implemented in ANS Standard Forth is available in
 4372: @file{compat/struct.fs}. This package was inspired by a posting on
 4373: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
 4374: possibly John Hayes). A version of this section has been published in
 4375: ???. Marcel Hendrix provided helpful comments.
 4376: 
 4377: @menu
 4378: * Why explicit structure support?::  
 4379: * Structure Usage::             
 4380: * Structure Naming Convention::  
 4381: * Structure Implementation::    
 4382: * Structure Glossary::          
 4383: @end menu
 4384: 
 4385: @node Why explicit structure support?, Structure Usage, Structures, Structures
 4386: @subsection Why explicit structure support?
 4387: 
 4388: @cindex address arithmetic for structures
 4389: @cindex structures using address arithmetic
 4390: If we want to use a structure containing several fields, we could simply
 4391: reserve memory for it, and access the fields using address arithmetic
 4392: (@pxref{Address arithmetic}). As an example, consider a structure with
 4393: the following fields
 4394: 
 4395: @table @code
 4396: @item a
 4397: is a float
 4398: @item b
 4399: is a cell
 4400: @item c
 4401: is a float
 4402: @end table
 4403: 
 4404: Given the (float-aligned) base address of the structure we get the
 4405: address of the field
 4406: 
 4407: @table @code
 4408: @item a
 4409: without doing anything further.
 4410: @item b
 4411: with @code{float+}
 4412: @item c
 4413: with @code{float+ cell+ faligned}
 4414: @end table
 4415: 
 4416: It is easy to see that this can become quite tiring. 
 4417: 
 4418: Moreover, it is not very readable, because seeing a
 4419: @code{cell+} tells us neither which kind of structure is
 4420: accessed nor what field is accessed; we have to somehow infer the kind
 4421: of structure, and then look up in the documentation, which field of
 4422: that structure corresponds to that offset.
 4423: 
 4424: Finally, this kind of address arithmetic also causes maintenance
 4425: troubles: If you add or delete a field somewhere in the middle of the
 4426: structure, you have to find and change all computations for the fields
 4427: afterwards.
 4428: 
 4429: So, instead of using @code{cell+} and friends directly, how
 4430: about storing the offsets in constants:
 4431: 
 4432: @example
 4433: 0 constant a-offset
 4434: 0 float+ constant b-offset
 4435: 0 float+ cell+ faligned c-offset
 4436: @end example
 4437: 
 4438: Now we can get the address of field @code{x} with @code{x-offset
 4439: +}. This is much better in all respects. Of course, you still
 4440: have to change all later offset definitions if you add a field. You can
 4441: fix this by declaring the offsets in the following way:
 4442: 
 4443: @example
 4444: 0 constant a-offset
 4445: a-offset float+ constant b-offset
 4446: b-offset cell+ faligned constant c-offset
 4447: @end example
 4448: 
 4449: Since we always use the offsets with @code{+}, using a defining
 4450: word @code{cfield} that includes the @code{+} in the
 4451: action of the defined word offers itself:
 4452: 
 4453: @example
 4454: : cfield ( n "name" -- )
 4455:     create ,
 4456: does> ( name execution: addr1 -- addr2 )
 4457:     @@ + ;
 4458: 
 4459: 0 cfield a
 4460: 0 a float+ cfield b
 4461: 0 b cell+ faligned cfield c
 4462: @end example
 4463: 
 4464: Instead of @code{x-offset +}, we now simply write @code{x}.
 4465: 
 4466: The structure field words now can be used quite nicely. However,
 4467: their definition is still a bit cumbersome: We have to repeat the
 4468: name, the information about size and alignment is distributed before
 4469: and after the field definitions etc.  The structure package presented
 4470: here addresses these problems.
 4471: 
 4472: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
 4473: @subsection Structure Usage
 4474: @cindex structure usage
 4475: 
 4476: @cindex @code{field} usage
 4477: @cindex @code{struct} usage
 4478: @cindex @code{end-struct} usage
 4479: You can define a structure for a (data-less) linked list with
 4480: @example
 4481: struct
 4482:     cell% field list-next
 4483: end-struct list%
 4484: @end example
 4485: 
 4486: With the address of the list node on the stack, you can compute the
 4487: address of the field that contains the address of the next node with
 4488: @code{list-next}. E.g., you can determine the length of a list
 4489: with:
 4490: 
 4491: @example
 4492: : list-length ( list -- n )
 4493: \ "list" is a pointer to the first element of a linked list
 4494: \ "n" is the length of the list
 4495:     0 begin ( list1 n1 )
 4496:         over
 4497:     while ( list1 n1 )
 4498:         1+ swap list-next @@ swap
 4499:     repeat
 4500:     nip ;
 4501: @end example
 4502: 
 4503: You can reserve memory for a list node in the dictionary with
 4504: @code{list% %allot}, which leaves the address of the list node on the
 4505: stack. For the equivalent allocation on the heap you can use @code{list%
 4506: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
 4507: use @code{list% %allocate}). You can also get the the size of a list
 4508: node with @code{list% %size} and it's alignment with @code{list%
 4509: %alignment}.
 4510: 
 4511: Note that in ANS Forth the body of a @code{create}d word is
 4512: @code{aligned} but not necessarily @code{faligned};
 4513: therefore, if you do a
 4514: @example
 4515: create @emph{name} foo% %allot
 4516: @end example
 4517: 
 4518: then the memory alloted for @code{foo%} is
 4519: guaranteed to start at the body of @code{@emph{name}} only if
 4520: @code{foo%} contains only character, cell and double fields.
 4521: 
 4522: @cindex strcutures containing structures
 4523: You can also include a structure @code{foo%} as field of
 4524: another structure, with:
 4525: @example
 4526: struct
 4527: ...
 4528:     foo% field ...
 4529: ...
 4530: end-struct ...
 4531: @end example
 4532: 
 4533: @cindex structure extension
 4534: @cindex extended records
 4535: Instead of starting with an empty structure, you can also extend an
 4536: existing structure. E.g., a plain linked list without data, as defined
 4537: above, is hardly useful; You can extend it to a linked list of integers,
 4538: like this:@footnote{This feature is also known as @emph{extended
 4539: records}. It is the main innovation in the Oberon language; in other
 4540: words, adding this feature to Modula-2 led Wirth to create a new
 4541: language, write a new compiler etc.  Adding this feature to Forth just
 4542: requires a few lines of code.}
 4543: 
 4544: @example
 4545: list%
 4546:     cell% field intlist-int
 4547: end-struct intlist%
 4548: @end example
 4549: 
 4550: @code{intlist%} is a structure with two fields:
 4551: @code{list-next} and @code{intlist-int}.
 4552: 
 4553: @cindex structures containing arrays
 4554: You can specify an array type containing @emph{n} elements of
 4555: type @code{foo%} like this:
 4556: 
 4557: @example
 4558: foo% @emph{n} *
 4559: @end example
 4560: 
 4561: You can use this array type in any place where you can use a normal
 4562: type, e.g., when defining a @code{field}, or with
 4563: @code{%allot}.
 4564: 
 4565: @cindex first field optimization
 4566: The first field is at the base address of a structure and the word
 4567: for this field (e.g., @code{list-next}) actually does not change
 4568: the address on the stack. You may be tempted to leave it away in the
 4569: interest of run-time and space efficiency. This is not necessary,
 4570: because the structure package optimizes this case and compiling such
 4571: words does not generate any code. So, in the interest of readability
 4572: and maintainability you should include the word for the field when
 4573: accessing the field.
 4574: 
 4575: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
 4576: @subsection Structure Naming Convention
 4577: @cindex structure naming conventions
 4578: 
 4579: The field names that come to (my) mind are often quite generic, and,
 4580: if used, would cause frequent name clashes. E.g., many structures
 4581: probably contain a @code{counter} field. The structure names
 4582: that come to (my) mind are often also the logical choice for the names
 4583: of words that create such a structure.
 4584: 
 4585: Therefore, I have adopted the following naming conventions: 
 4586: 
 4587: @itemize @bullet
 4588: @cindex field naming convention
 4589: @item
 4590: The names of fields are of the form
 4591: @code{@emph{struct}-@emph{field}}, where
 4592: @code{@emph{struct}} is the basic name of the structure, and
 4593: @code{@emph{field}} is the basic name of the field. You can
 4594: think about field words as converting converts the (address of the)
 4595: structure into the (address of the) field.
 4596: 
 4597: @cindex structure naming convention
 4598: @item
 4599: The names of structures are of the form
 4600: @code{@emph{struct}%}, where
 4601: @code{@emph{struct}} is the basic name of the structure.
 4602: @end itemize
 4603: 
 4604: This naming convention does not work that well for fields of extended
 4605: structures; e.g., the integer list structure has a field
 4606: @code{intlist-int}, but has @code{list-next}, not
 4607: @code{intlist-next}.
 4608: 
 4609: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
 4610: @subsection Structure Implementation
 4611: @cindex structure implementation
 4612: @cindex implementation of structures
 4613: 
 4614: The central idea in the implementation is to pass the data about the
 4615: structure being built on the stack, not in some global
 4616: variable. Everything else falls into place naturally once this design
 4617: decision is made.
 4618: 
 4619: The type description on the stack is of the form @emph{align
 4620: size}. Keeping the size on the top-of-stack makes dealing with arrays
 4621: very simple.
 4622: 
 4623: @code{field} is a defining word that uses @code{Create}
 4624: and @code{DOES>}. The body of the field contains the offset
 4625: of the field, and the normal @code{DOES>} action is:
 4626: 
 4627: @example
 4628: @ +
 4629: @end example
 4630: 
 4631: @noindent
 4632: i.e., add the offset to the address, giving the stack effect
 4633: @code{addr1 -- addr2} for a field.
 4634: 
 4635: @cindex first field optimization, implementation
 4636: This simple structure is slightly complicated by the optimization
 4637: for fields with offset 0, which requires a different
 4638: @code{DOES>}-part (because we cannot rely on there being
 4639: something on the stack if such a field is invoked during
 4640: compilation). Therefore, we put the different @code{DOES>}-parts
 4641: in separate words, and decide which one to invoke based on the
 4642: offset. For a zero offset, the field is basically a noop; it is
 4643: immediate, and therefore no code is generated when it is compiled.
 4644: 
 4645: @node Structure Glossary,  , Structure Implementation, Structures
 4646: @subsection Structure Glossary
 4647: @cindex structure glossary
 4648: 
 4649: doc-%align
 4650: doc-%alignment
 4651: doc-%alloc
 4652: doc-%allocate
 4653: doc-%allot
 4654: doc-cell%
 4655: doc-char%
 4656: doc-dfloat%
 4657: doc-double%
 4658: doc-end-struct
 4659: doc-field
 4660: doc-float%
 4661: doc-nalign
 4662: doc-sfloat%
 4663: doc-%size
 4664: doc-struct
 4665: 
 4666: @c -------------------------------------------------------------
 4667: @node Object-oriented Forth, Tokens for Words, Structures, Words
 4668: @section Object-oriented Forth
 4669: 
 4670: Gforth comes with three packets for object-oriented programming,
 4671: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
 4672: is preloaded, so you have to @code{include} them before use. The most
 4673: important differences between these packets (and others) are discussed
 4674: in @ref{Comparison with other object models}. All packets are written
 4675: in ANS Forth and can be used with any other ANS Forth.
 4676: 
 4677: @menu
 4678: * Objects::                     
 4679: * OOF::                         
 4680: * Mini-OOF::                    
 4681: @end menu
 4682: 
 4683: @node Objects, OOF, Object-oriented Forth, Object-oriented Forth
 4684: @subsection Objects
 4685: @cindex objects
 4686: @cindex object-oriented programming
 4687: 
 4688: @cindex @file{objects.fs}
 4689: @cindex @file{oof.fs}
 4690: 
 4691: This section describes the @file{objects.fs} packet. This material also has been published in @cite{Yet Another Forth Objects Package} by Anton Ertl and appeared in Forth Dimensions 19(2), pages 37--43 (@url{http://www.complang.tuwien.ac.at/forth/objects/objects.html}).
 4692: @c McKewan's and Zsoter's packages
 4693: 
 4694: This section assumes (in some places) that you have read @ref{Structures}.
 4695: 
 4696: @menu
 4697: * Properties of the Objects model::  
 4698: * Why object-oriented programming?::  
 4699: * Object-Oriented Terminology::  
 4700: * Basic Objects Usage::         
 4701: * The class Object::            
 4702: * Creating objects::            
 4703: * Object-Oriented Programming Style::  
 4704: * Class Binding::               
 4705: * Method conveniences::         
 4706: * Classes and Scoping::         
 4707: * Object Interfaces::           
 4708: * Objects Implementation::      
 4709: * Comparison with other object models::  
 4710: * Objects Glossary::            
 4711: @end menu
 4712: 
 4713: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
 4714: and Bernd Paysan helped me with the related works section.
 4715: 
 4716: @node Properties of the Objects model, Why object-oriented programming?, Objects, Objects
 4717: @subsubsection Properties of the @file{objects.fs} model
 4718: @cindex @file{objects.fs} properties
 4719: 
 4720: @itemize @bullet
 4721: @item
 4722: It is straightforward to pass objects on the stack. Passing
 4723: selectors on the stack is a little less convenient, but possible.
 4724: 
 4725: @item
 4726: Objects are just data structures in memory, and are referenced by
 4727: their address. You can create words for objects with normal defining
 4728: words like @code{constant}. Likewise, there is no difference
 4729: between instance variables that contain objects and those
 4730: that contain other data.
 4731: 
 4732: @item
 4733: Late binding is efficient and easy to use.
 4734: 
 4735: @item
 4736: It avoids parsing, and thus avoids problems with state-smartness
 4737: and reduced extensibility; for convenience there are a few parsing
 4738: words, but they have non-parsing counterparts. There are also a few
 4739: defining words that parse. This is hard to avoid, because all standard
 4740: defining words parse (except @code{:noname}); however, such
 4741: words are not as bad as many other parsing words, because they are not
 4742: state-smart.
 4743: 
 4744: @item
 4745: It does not try to incorporate everything. It does a few things
 4746: and does them well (IMO). In particular, I did not intend to support
 4747: information hiding with this model (although it has features that may
 4748: help); you can use a separate package for achieving this.
 4749: 
 4750: @item
 4751: It is layered; you don't have to learn and use all features to use this
 4752: model. Only a few features are necessary (@xref{Basic Objects Usage},
 4753: @xref{The class Object}, @xref{Creating objects}.), the others
 4754: are optional and independent of each other.
 4755: 
 4756: @item
 4757: An implementation in ANS Forth is available.
 4758: 
 4759: @end itemize
 4760: 
 4761: I have used the technique, on which this model is based, for
 4762: implementing the parser generator Gray; we have also used this technique
 4763: in Gforth for implementing the various flavours of word lists (hashed or
 4764: not, case-sensitive or not, special-purpose word lists for locals etc.).
 4765: 
 4766: @node Why object-oriented programming?, Object-Oriented Terminology, Properties of the Objects model, Objects
 4767: @subsubsection Why object-oriented programming?
 4768: @cindex object-oriented programming motivation
 4769: @cindex motivation for object-oriented programming
 4770: 
 4771: Often we have to deal with several data structures (@emph{objects}),
 4772: that have to be treated similarly in some respects, but differ in
 4773: others. Graphical objects are the textbook example: circles,
 4774: triangles, dinosaurs, icons, and others, and we may want to add more
 4775: during program development. We want to apply some operations to any
 4776: graphical object, e.g., @code{draw} for displaying it on the
 4777: screen. However, @code{draw} has to do something different for
 4778: every kind of object.
 4779: 
 4780: We could implement @code{draw} as a big @code{CASE}
 4781: control structure that executes the appropriate code depending on the
 4782: kind of object to be drawn. This would be not be very elegant, and,
 4783: moreover, we would have to change @code{draw} every time we add
 4784: a new kind of graphical object (say, a spaceship).
 4785: 
 4786: What we would rather do is: When defining spaceships, we would tell
 4787: the system: "Here's how you @code{draw} a spaceship; you figure
 4788: out the rest."
 4789: 
 4790: This is the problem that all systems solve that (rightfully) call
 4791: themselves object-oriented, and the object-oriented package I present
 4792: here also solves this problem (and not much else).
 4793: 
 4794: @node Object-Oriented Terminology, Basic Objects Usage, Why object-oriented programming?, Objects
 4795: @subsubsection Object-Oriented Terminology
 4796: @cindex object-oriented terminology
 4797: @cindex terminology for object-oriented programming
 4798: 
 4799: This section is mainly for reference, so you don't have to understand
 4800: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
 4801: short:
 4802: 
 4803: @table @emph
 4804: @cindex class
 4805: @item class
 4806: a data structure definition with some extras.
 4807: 
 4808: @cindex object
 4809: @item object
 4810: an instance of the data structure described by the class definition.
 4811: 
 4812: @cindex instance variables
 4813: @item instance variables
 4814: fields of the data structure.
 4815: 
 4816: @cindex selector
 4817: @cindex method selector
 4818: @cindex virtual function
 4819: @item selector
 4820: (or @emph{method selector}) a word (e.g.,
 4821: @code{draw}) for performing an operation on a variety of data
 4822: structures (classes). A selector describes @emph{what} operation to
 4823: perform. In C++ terminology: a (pure) virtual function.
 4824: 
 4825: @cindex method
 4826: @item method
 4827: the concrete definition that performs the operation
 4828: described by the selector for a specific class. A method specifies
 4829: @emph{how} the operation is performed for a specific class.
 4830: 
 4831: @cindex selector invocation
 4832: @cindex message send
 4833: @cindex invoking a selector
 4834: @item selector invocation
 4835: a call of a selector. One argument of the call (the TOS (top-of-stack))
 4836: is used for determining which method is used. In Smalltalk terminology:
 4837: a message (consisting of the selector and the other arguments) is sent
 4838: to the object.
 4839: 
 4840: @cindex receiving object
 4841: @item receiving object
 4842: the object used for determining the method executed by a selector
 4843: invocation. In our model it is the object that is on the TOS when the
 4844: selector is invoked. (@emph{Receiving} comes from Smalltalks
 4845: @emph{message} terminology.)
 4846: 
 4847: @cindex child class
 4848: @cindex parent class
 4849: @cindex inheritance
 4850: @item child class
 4851: a class that has (@emph{inherits}) all properties (instance variables,
 4852: selectors, methods) from a @emph{parent class}. In Smalltalk
 4853: terminology: The subclass inherits from the superclass. In C++
 4854: terminology: The derived class inherits from the base class.
 4855: 
 4856: @end table
 4857: 
 4858: @c If you wonder about the message sending terminology, it comes from
 4859: @c a time when each object had it's own task and objects communicated via
 4860: @c message passing; eventually the Smalltalk developers realized that
 4861: @c they can do most things through simple (indirect) calls. They kept the
 4862: @c terminology.
 4863: 
 4864: @node Basic Objects Usage, The class Object, Object-Oriented Terminology, Objects
 4865: @subsubsection Basic Objects Usage
 4866: @cindex basic objects usage
 4867: @cindex objects, basic usage
 4868: 
 4869: You can define a class for graphical objects like this:
 4870: 
 4871: @cindex @code{class} usage
 4872: @cindex @code{end-class} usage
 4873: @cindex @code{selector} usage
 4874: @example
 4875: object class \ "object" is the parent class
 4876:   selector draw ( x y graphical -- )
 4877: end-class graphical
 4878: @end example
 4879: 
 4880: This code defines a class @code{graphical} with an
 4881: operation @code{draw}.  We can perform the operation
 4882: @code{draw} on any @code{graphical} object, e.g.:
 4883: 
 4884: @example
 4885: 100 100 t-rex draw
 4886: @end example
 4887: 
 4888: where @code{t-rex} is a word (say, a constant) that produces a
 4889: graphical object.
 4890: 
 4891: @cindex abstract class
 4892: How do we create a graphical object? With the present definitions,
 4893: we cannot create a useful graphical object. The class
 4894: @code{graphical} describes graphical objects in general, but not
 4895: any concrete graphical object type (C++ users would call it an
 4896: @emph{abstract class}); e.g., there is no method for the selector
 4897: @code{draw} in the class @code{graphical}.
 4898: 
 4899: For concrete graphical objects, we define child classes of the
 4900: class @code{graphical}, e.g.:
 4901: 
 4902: @cindex @code{overrides} usage
 4903: @cindex @code{field} usage in class definition
 4904: @example
 4905: graphical class \ "graphical" is the parent class
 4906:   cell% field circle-radius
 4907: 
 4908: :noname ( x y circle -- )
 4909:   circle-radius @@ draw-circle ;
 4910: overrides draw
 4911: 
 4912: :noname ( n-radius circle -- )
 4913:   circle-radius ! ;
 4914: overrides construct
 4915: 
 4916: end-class circle
 4917: @end example
 4918: 
 4919: Here we define a class @code{circle} as a child of @code{graphical},
 4920: with a field @code{circle-radius} (which behaves just like a field in
 4921: @pxref{Structures}); it defines new methods for the selectors
 4922: @code{draw} and @code{construct} (@code{construct} is defined in
 4923: @code{object}, the parent class of @code{graphical}).
 4924: 
 4925: Now we can create a circle on the heap (i.e.,
 4926: @code{allocate}d memory) with
 4927: 
 4928: @cindex @code{heap-new} usage
 4929: @example
 4930: 50 circle heap-new constant my-circle
 4931: @end example
 4932: 
 4933: @code{heap-new} invokes @code{construct}, thus
 4934: initializing the field @code{circle-radius} with 50. We can draw
 4935: this new circle at (100,100) with
 4936: 
 4937: @example
 4938: 100 100 my-circle draw
 4939: @end example
 4940: 
 4941: @cindex selector invocation, restrictions
 4942: @cindex class definition, restrictions
 4943: Note: You can invoke a selector only if the object on the TOS
 4944: (the receiving object) belongs to the class where the selector was
 4945: defined or one of its descendents; e.g., you can invoke
 4946: @code{draw} only for objects belonging to @code{graphical}
 4947: or its descendents (e.g., @code{circle}).  Immediately before
 4948: @code{end-class}, the search order has to be the same as
 4949: immediately after @code{class}.
 4950: 
 4951: @node The class Object, Creating objects, Basic Objects Usage, Objects
 4952: @subsubsection The class @code{object}
 4953: @cindex @code{object} class
 4954: 
 4955: When you define a class, you have to specify a parent class.  So how do
 4956: you start defining classes? There is one class available from the start:
 4957: @code{object}. You can use it as ancestor for all classes. It is the
 4958: only class that has no parent. It has two selectors: @code{construct}
 4959: and @code{print}.
 4960: 
 4961: @node Creating objects, Object-Oriented Programming Style, The class Object, Objects
 4962: @subsubsection Creating objects
 4963: @cindex creating objects
 4964: @cindex object creation
 4965: @cindex object allocation options
 4966: 
 4967: @cindex @code{heap-new} discussion
 4968: @cindex @code{dict-new} discussion
 4969: @cindex @code{construct} discussion
 4970: You can create and initialize an object of a class on the heap with
 4971: @code{heap-new} ( ... class -- object ) and in the dictionary
 4972: (allocation with @code{allot}) with @code{dict-new} (
 4973: ... class -- object ). Both words invoke @code{construct}, which
 4974: consumes the stack items indicated by "..." above.
 4975: 
 4976: @cindex @code{init-object} discussion
 4977: @cindex @code{class-inst-size} discussion
 4978: If you want to allocate memory for an object yourself, you can get its
 4979: alignment and size with @code{class-inst-size 2@@} ( class --
 4980: align size ). Once you have memory for an object, you can initialize
 4981: it with @code{init-object} ( ... class object -- );
 4982: @code{construct} does only a part of the necessary work.
 4983: 
 4984: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
 4985: @subsubsection Object-Oriented Programming Style
 4986: @cindex object-oriented programming style
 4987: 
 4988: This section is not exhaustive.
 4989: 
 4990: @cindex stack effects of selectors
 4991: @cindex selectors and stack effects
 4992: In general, it is a good idea to ensure that all methods for the
 4993: same selector have the same stack effect: when you invoke a selector,
 4994: you often have no idea which method will be invoked, so, unless all
 4995: methods have the same stack effect, you will not know the stack effect
 4996: of the selector invocation.
 4997: 
 4998: One exception to this rule is methods for the selector
 4999: @code{construct}. We know which method is invoked, because we
 5000: specify the class to be constructed at the same place. Actually, I
 5001: defined @code{construct} as a selector only to give the users a
 5002: convenient way to specify initialization. The way it is used, a
 5003: mechanism different from selector invocation would be more natural
 5004: (but probably would take more code and more space to explain).
 5005: 
 5006: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
 5007: @subsubsection Class Binding
 5008: @cindex class binding
 5009: @cindex early binding
 5010: 
 5011: @cindex late binding
 5012: Normal selector invocations determine the method at run-time depending
 5013: on the class of the receiving object (late binding).
 5014: 
 5015: Sometimes we want to invoke a different method. E.g., assume that
 5016: you want to use the simple method for @code{print}ing
 5017: @code{object}s instead of the possibly long-winded
 5018: @code{print} method of the receiver class. You can achieve this
 5019: by replacing the invocation of @code{print} with
 5020: 
 5021: @cindex @code{[bind]} usage
 5022: @example
 5023: [bind] object print
 5024: @end example
 5025: 
 5026: in compiled code or
 5027: 
 5028: @cindex @code{bind} usage
 5029: @example
 5030: bind object print
 5031: @end example
 5032: 
 5033: @cindex class binding, alternative to
 5034: in interpreted code. Alternatively, you can define the method with a
 5035: name (e.g., @code{print-object}), and then invoke it through the
 5036: name. Class binding is just a (often more convenient) way to achieve
 5037: the same effect; it avoids name clutter and allows you to invoke
 5038: methods directly without naming them first.
 5039: 
 5040: @cindex superclass binding
 5041: @cindex parent class binding
 5042: A frequent use of class binding is this: When we define a method
 5043: for a selector, we often want the method to do what the selector does
 5044: in the parent class, and a little more. There is a special word for
 5045: this purpose: @code{[parent]}; @code{[parent]
 5046: @emph{selector}} is equivalent to @code{[bind] @emph{parent
 5047: selector}}, where @code{@emph{parent}} is the parent
 5048: class of the current class. E.g., a method definition might look like:
 5049: 
 5050: @cindex @code{[parent]} usage
 5051: @example
 5052: :noname
 5053:   dup [parent] foo \ do parent's foo on the receiving object
 5054:   ... \ do some more
 5055: ; overrides foo
 5056: @end example
 5057: 
 5058: @cindex class binding as optimization
 5059: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
 5060: March 1997), Andrew McKewan presents class binding as an optimization
 5061: technique. I recommend not using it for this purpose unless you are in
 5062: an emergency. Late binding is pretty fast with this model anyway, so the
 5063: benefit of using class binding is small; the cost of using class binding
 5064: where it is not appropriate is reduced maintainability.
 5065: 
 5066: While we are at programming style questions: You should bind
 5067: selectors only to ancestor classes of the receiving object. E.g., say,
 5068: you know that the receiving object is of class @code{foo} or its
 5069: descendents; then you should bind only to @code{foo} and its
 5070: ancestors.
 5071: 
 5072: @node Method conveniences, Classes and Scoping, Class Binding, Objects
 5073: @subsubsection Method conveniences
 5074: @cindex method conveniences
 5075: 
 5076: In a method you usually access the receiving object pretty often.  If
 5077: you define the method as a plain colon definition (e.g., with
 5078: @code{:noname}), you may have to do a lot of stack
 5079: gymnastics. To avoid this, you can define the method with @code{m:
 5080: ... ;m}. E.g., you could define the method for
 5081: @code{draw}ing a @code{circle} with
 5082: 
 5083: @cindex @code{this} usage
 5084: @cindex @code{m:} usage
 5085: @cindex @code{;m} usage
 5086: @example
 5087: m: ( x y circle -- )
 5088:   ( x y ) this circle-radius @@ draw-circle ;m
 5089: @end example
 5090: 
 5091: @cindex @code{exit} in @code{m: ... ;m}
 5092: @cindex @code{exitm} discussion
 5093: @cindex @code{catch} in @code{m: ... ;m}
 5094: When this method is executed, the receiver object is removed from the
 5095: stack; you can access it with @code{this} (admittedly, in this
 5096: example the use of @code{m: ... ;m} offers no advantage). Note
 5097: that I specify the stack effect for the whole method (i.e. including
 5098: the receiver object), not just for the code between @code{m:}
 5099: and @code{;m}. You cannot use @code{exit} in
 5100: @code{m:...;m}; instead, use
 5101: @code{exitm}.@footnote{Moreover, for any word that calls
 5102: @code{catch} and was defined before loading
 5103: @code{objects.fs}, you have to redefine it like I redefined
 5104: @code{catch}: @code{: catch this >r catch r> to-this ;}}
 5105: 
 5106: @cindex @code{inst-var} usage
 5107: You will frequently use sequences of the form @code{this
 5108: @emph{field}} (in the example above: @code{this
 5109: circle-radius}). If you use the field only in this way, you can
 5110: define it with @code{inst-var} and eliminate the
 5111: @code{this} before the field name. E.g., the @code{circle}
 5112: class above could also be defined with:
 5113: 
 5114: @example
 5115: graphical class
 5116:   cell% inst-var radius
 5117: 
 5118: m: ( x y circle -- )
 5119:   radius @@ draw-circle ;m
 5120: overrides draw
 5121: 
 5122: m: ( n-radius circle -- )
 5123:   radius ! ;m
 5124: overrides construct
 5125: 
 5126: end-class circle
 5127: @end example
 5128: 
 5129: @code{radius} can only be used in @code{circle} and its
 5130: descendent classes and inside @code{m:...;m}.
 5131: 
 5132: @cindex @code{inst-value} usage
 5133: You can also define fields with @code{inst-value}, which is
 5134: to @code{inst-var} what @code{value} is to
 5135: @code{variable}.  You can change the value of such a field with
 5136: @code{[to-inst]}.  E.g., we could also define the class
 5137: @code{circle} like this:
 5138: 
 5139: @example
 5140: graphical class
 5141:   inst-value radius
 5142: 
 5143: m: ( x y circle -- )
 5144:   radius draw-circle ;m
 5145: overrides draw
 5146: 
 5147: m: ( n-radius circle -- )
 5148:   [to-inst] radius ;m
 5149: overrides construct
 5150: 
 5151: end-class circle
 5152: @end example
 5153: 
 5154: 
 5155: @node Classes and Scoping, Object Interfaces, Method conveniences, Objects
 5156: @subsubsection Classes and Scoping
 5157: @cindex classes and scoping
 5158: @cindex scoping and classes
 5159: 
 5160: Inheritance is frequent, unlike structure extension. This exacerbates
 5161: the problem with the field name convention (@pxref{Structure Naming
 5162: Convention}): One always has to remember in which class the field was
 5163: originally defined; changing a part of the class structure would require
 5164: changes for renaming in otherwise unaffected code.
 5165: 
 5166: @cindex @code{inst-var} visibility
 5167: @cindex @code{inst-value} visibility
 5168: To solve this problem, I added a scoping mechanism (which was not in my
 5169: original charter): A field defined with @code{inst-var} (or
 5170: @code{inst-value}) is visible only in the class where it is defined and in
 5171: the descendent classes of this class.  Using such fields only makes
 5172: sense in @code{m:}-defined methods in these classes anyway.
 5173: 
 5174: This scoping mechanism allows us to use the unadorned field name,
 5175: because name clashes with unrelated words become much less likely.
 5176: 
 5177: @cindex @code{protected} discussion
 5178: @cindex @code{private} discussion
 5179: Once we have this mechanism, we can also use it for controlling the
 5180: visibility of other words: All words defined after
 5181: @code{protected} are visible only in the current class and its
 5182: descendents. @code{public} restores the compilation
 5183: (i.e. @code{current}) word list that was in effect before. If you
 5184: have several @code{protected}s without an intervening
 5185: @code{public} or @code{set-current}, @code{public}
 5186: will restore the compilation word list in effect before the first of
 5187: these @code{protected}s.
 5188: 
 5189: @node Object Interfaces, Objects Implementation, Classes and Scoping, Objects
 5190: @subsubsection Object Interfaces
 5191: @cindex object interfaces
 5192: @cindex interfaces for objects
 5193: 
 5194: In this model you can only call selectors defined in the class of the
 5195: receiving objects or in one of its ancestors. If you call a selector
 5196: with a receiving object that is not in one of these classes, the
 5197: result is undefined; if you are lucky, the program crashes
 5198: immediately.
 5199: 
 5200: @cindex selectors common to hardly-related classes
 5201: Now consider the case when you want to have a selector (or several)
 5202: available in two classes: You would have to add the selector to a
 5203: common ancestor class, in the worst case to @code{object}. You
 5204: may not want to do this, e.g., because someone else is responsible for
 5205: this ancestor class.
 5206: 
 5207: The solution for this problem is interfaces. An interface is a
 5208: collection of selectors. If a class implements an interface, the
 5209: selectors become available to the class and its descendents. A class
 5210: can implement an unlimited number of interfaces. For the problem
 5211: discussed above, we would define an interface for the selector(s), and
 5212: both classes would implement the interface.
 5213: 
 5214: As an example, consider an interface @code{storage} for
 5215: writing objects to disk and getting them back, and a class
 5216: @code{foo} foo that implements it. The code for this would look
 5217: like this:
 5218: 
 5219: @cindex @code{interface} usage
 5220: @cindex @code{end-interface} usage
 5221: @cindex @code{implementation} usage
 5222: @example
 5223: interface
 5224:   selector write ( file object -- )
 5225:   selector read1 ( file object -- )
 5226: end-interface storage
 5227: 
 5228: bar class
 5229:   storage implementation
 5230: 
 5231: ... overrides write
 5232: ... overrides read
 5233: ...
 5234: end-class foo
 5235: @end example
 5236: 
 5237: (I would add a word @code{read} ( file -- object ) that uses
 5238: @code{read1} internally, but that's beyond the point illustrated
 5239: here.)
 5240: 
 5241: Note that you cannot use @code{protected} in an interface; and
 5242: of course you cannot define fields.
 5243: 
 5244: In the Neon model, all selectors are available for all classes;
 5245: therefore it does not need interfaces. The price you pay in this model
 5246: is slower late binding, and therefore, added complexity to avoid late
 5247: binding.
 5248: 
 5249: @node Objects Implementation, Comparison with other object models, Object Interfaces, Objects
 5250: @subsubsection @file{objects.fs} Implementation
 5251: @cindex @file{objects.fs} implementation
 5252: 
 5253: @cindex @code{object-map} discussion
 5254: An object is a piece of memory, like one of the data structures
 5255: described with @code{struct...end-struct}. It has a field
 5256: @code{object-map} that points to the method map for the object's
 5257: class.
 5258: 
 5259: @cindex method map
 5260: @cindex virtual function table
 5261: The @emph{method map}@footnote{This is Self terminology; in C++
 5262: terminology: virtual function table.} is an array that contains the
 5263: execution tokens (XTs) of the methods for the object's class. Each
 5264: selector contains an offset into the method maps.
 5265: 
 5266: @cindex @code{selector} implementation, class
 5267: @code{selector} is a defining word that uses
 5268: @code{create} and @code{does>}. The body of the
 5269: selector contains the offset; the @code{does>} action for a
 5270: class selector is, basically:
 5271: 
 5272: @example
 5273: ( object addr ) @@ over object-map @@ + @@ execute
 5274: @end example
 5275: 
 5276: Since @code{object-map} is the first field of the object, it
 5277: does not generate any code. As you can see, calling a selector has a
 5278: small, constant cost.
 5279: 
 5280: @cindex @code{current-interface} discussion
 5281: @cindex class implementation and representation
 5282: A class is basically a @code{struct} combined with a method
 5283: map. During the class definition the alignment and size of the class
 5284: are passed on the stack, just as with @code{struct}s, so
 5285: @code{field} can also be used for defining class
 5286: fields. However, passing more items on the stack would be
 5287: inconvenient, so @code{class} builds a data structure in memory,
 5288: which is accessed through the variable
 5289: @code{current-interface}. After its definition is complete, the
 5290: class is represented on the stack by a pointer (e.g., as parameter for
 5291: a child class definition).
 5292: 
 5293: At the start, a new class has the alignment and size of its parent,
 5294: and a copy of the parent's method map. Defining new fields extends the
 5295: size and alignment; likewise, defining new selectors extends the
 5296: method map. @code{overrides} just stores a new XT in the method
 5297: map at the offset given by the selector.
 5298: 
 5299: @cindex class binding, implementation
 5300: Class binding just gets the XT at the offset given by the selector
 5301: from the class's method map and @code{compile,}s (in the case of
 5302: @code{[bind]}) it.
 5303: 
 5304: @cindex @code{this} implementation
 5305: @cindex @code{catch} and @code{this}
 5306: @cindex @code{this} and @code{catch}
 5307: I implemented @code{this} as a @code{value}. At the
 5308: start of an @code{m:...;m} method the old @code{this} is
 5309: stored to the return stack and restored at the end; and the object on
 5310: the TOS is stored @code{TO this}. This technique has one
 5311: disadvantage: If the user does not leave the method via
 5312: @code{;m}, but via @code{throw} or @code{exit},
 5313: @code{this} is not restored (and @code{exit} may
 5314: crash). To deal with the @code{throw} problem, I have redefined
 5315: @code{catch} to save and restore @code{this}; the same
 5316: should be done with any word that can catch an exception. As for
 5317: @code{exit}, I simply forbid it (as a replacement, there is
 5318: @code{exitm}).
 5319: 
 5320: @cindex @code{inst-var} implementation
 5321: @code{inst-var} is just the same as @code{field}, with
 5322: a different @code{does>} action:
 5323: @example
 5324: @@ this +
 5325: @end example
 5326: Similar for @code{inst-value}.
 5327: 
 5328: @cindex class scoping implementation
 5329: Each class also has a word list that contains the words defined with
 5330: @code{inst-var} and @code{inst-value}, and its protected
 5331: words. It also has a pointer to its parent. @code{class} pushes
 5332: the word lists of the class an all its ancestors on the search order,
 5333: and @code{end-class} drops them.
 5334: 
 5335: @cindex interface implementation
 5336: An interface is like a class without fields, parent and protected
 5337: words; i.e., it just has a method map. If a class implements an
 5338: interface, its method map contains a pointer to the method map of the
 5339: interface. The positive offsets in the map are reserved for class
 5340: methods, therefore interface map pointers have negative
 5341: offsets. Interfaces have offsets that are unique throughout the
 5342: system, unlike class selectors, whose offsets are only unique for the
 5343: classes where the selector is available (invokable).
 5344: 
 5345: This structure means that interface selectors have to perform one
 5346: indirection more than class selectors to find their method. Their body
 5347: contains the interface map pointer offset in the class method map, and
 5348: the method offset in the interface method map. The
 5349: @code{does>} action for an interface selector is, basically:
 5350: 
 5351: @example
 5352: ( object selector-body )
 5353: 2dup selector-interface @@ ( object selector-body object interface-offset )
 5354: swap object-map @@ + @@ ( object selector-body map )
 5355: swap selector-offset @@ + @@ execute
 5356: @end example
 5357: 
 5358: where @code{object-map} and @code{selector-offset} are
 5359: first fields and generate no code.
 5360: 
 5361: As a concrete example, consider the following code:
 5362: 
 5363: @example
 5364: interface
 5365:   selector if1sel1
 5366:   selector if1sel2
 5367: end-interface if1
 5368: 
 5369: object class
 5370:   if1 implementation
 5371:   selector cl1sel1
 5372:   cell% inst-var cl1iv1
 5373: 
 5374: ' m1 overrides construct
 5375: ' m2 overrides if1sel1
 5376: ' m3 overrides if1sel2
 5377: ' m4 overrides cl1sel2
 5378: end-class cl1
 5379: 
 5380: create obj1 object dict-new drop
 5381: create obj2 cl1    dict-new drop
 5382: @end example
 5383: 
 5384: The data structure created by this code (including the data structure
 5385: for @code{object}) is shown in the <a
 5386: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
 5387: 
 5388: @node Comparison with other object models, Objects Glossary, Objects Implementation, Objects
 5389: @subsubsection Comparison with other object models
 5390: @cindex comparison of object models
 5391: @cindex object models, comparison
 5392: 
 5393: Many object-oriented Forth extensions have been proposed (@cite{A survey
 5394: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
 5395: J. Rodriguez and W. F. S. Poehlman lists 17). Here I'll discuss the
 5396: relation of @file{objects.fs} to two well-known and two closely-related
 5397: (by the use of method maps) models.
 5398: 
 5399: @cindex Neon model
 5400: The most popular model currently seems to be the Neon model (see
 5401: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
 5402: 1997) by Andrew McKewan). The Neon model uses a @code{@emph{selector
 5403: object}} syntax, which makes it unnatural to pass objects on the
 5404: stack. It also requires that the selector parses the input stream (at
 5405: compile time); this leads to reduced extensibility and to bugs that are
 5406: hard to find. Finally, it allows using every selector to every object;
 5407: this eliminates the need for classes, but makes it harder to create
 5408: efficient implementations. A longer version of this critique can be
 5409: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
 5410: Dimensions, May 1997) by Anton Ertl.
 5411: 
 5412: @cindex Pountain's object-oriented model
 5413: Another well-known publication is @cite{Object-Oriented Forth} (Academic
 5414: Press, London, 1987) by Dick Pountain. However, it is not really about
 5415: object-oriented programming, because it hardly deals with late
 5416: binding. Instead, it focuses on features like information hiding and
 5417: overloading that are characteristic of modular languages like Ada (83).
 5418: 
 5419: @cindex Zsoter's object-oriented model
 5420: In @cite{Does late binding have to be slow?} (Forth Dimensions ??? 1996)
 5421: Andras Zsoter describes a model that makes heavy use of an active object
 5422: (like @code{this} in @file{objects.fs}): The active object is not only
 5423: used for accessing all fields, but also specifies the receiving object
 5424: of every selector invocation; you have to change the active object
 5425: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
 5426: changes more or less implicitly at @code{m: ... ;m}. Such a change at
 5427: the method entry point is unnecessary with the Zsoter's model, because
 5428: the receiving object is the active object already; OTOH, the explicit
 5429: change is absolutely necessary in that model, because otherwise no one
 5430: could ever change the active object. An ANS Forth implementation of this
 5431: model is available at @url{http://www.forth.org/fig/oopf.html}.
 5432: 
 5433: @cindex @file{oof.fs}, differences to other models
 5434: The @file{oof.fs} model combines information hiding and overloading
 5435: resolution (by keeping names in various word lists) with object-oriented
 5436: programming. It sets the active object implicitly on method entry, but
 5437: also allows explicit changing (with @code{>o...o>} or with
 5438: @code{with...endwith}). It uses parsing and state-smart objects and
 5439: classes for resolving overloading and for early binding: the object or
 5440: class parses the selector and determines the method from this. If the
 5441: selector is not parsed by an object or class, it performs a call to the
 5442: selector for the active object (late binding), like Zsoter's model.
 5443: Fields are always accessed through the active object. The big
 5444: disadvantage of this model is the parsing and the state-smartness, which
 5445: reduces extensibility and increases the opportunities for subtle bugs;
 5446: essentially, you are only safe if you never tick or @code{postpone} an
 5447: object or class (Bernd disagrees, but I (Anton) am not convinced).
 5448: 
 5449: @cindex @file{mini-oof.fs}, differences to other models
 5450: The Mini-OOF model is quite similar to a very stripped-down version of
 5451: the Objects model, but syntactically it is a mixture of the Objects and
 5452: the OOF model.
 5453: 
 5454: 
 5455: @node Objects Glossary,  , Comparison with other object models, Objects
 5456: @subsubsection @file{objects.fs} Glossary
 5457: @cindex @file{objects.fs} Glossary
 5458: 
 5459: doc---objects-bind
 5460: doc---objects-<bind>
 5461: doc---objects-bind'
 5462: doc---objects-[bind]
 5463: doc---objects-class
 5464: doc---objects-class->map
 5465: doc---objects-class-inst-size
 5466: doc---objects-class-override!
 5467: doc---objects-construct
 5468: doc---objects-current'
 5469: doc---objects-[current]
 5470: doc---objects-current-interface
 5471: doc---objects-dict-new
 5472: doc---objects-drop-order
 5473: doc---objects-end-class
 5474: doc---objects-end-class-noname
 5475: doc---objects-end-interface
 5476: doc---objects-end-interface-noname
 5477: doc---objects-exitm
 5478: doc---objects-heap-new
 5479: doc---objects-implementation
 5480: doc---objects-init-object
 5481: doc---objects-inst-value
 5482: doc---objects-inst-var
 5483: doc---objects-interface
 5484: doc---objects-;m
 5485: doc---objects-m:
 5486: doc---objects-method
 5487: doc---objects-object
 5488: doc---objects-overrides
 5489: doc---objects-[parent]
 5490: doc---objects-print
 5491: doc---objects-protected
 5492: doc---objects-public
 5493: doc---objects-push-order
 5494: doc---objects-selector
 5495: doc---objects-this
 5496: doc---objects-<to-inst>
 5497: doc---objects-[to-inst]
 5498: doc---objects-to-this
 5499: doc---objects-xt-new
 5500: 
 5501: @c -------------------------------------------------------------
 5502: @node OOF, Mini-OOF, Objects, Object-oriented Forth
 5503: @subsection OOF
 5504: @cindex oof
 5505: @cindex object-oriented programming
 5506: 
 5507: @cindex @file{objects.fs}
 5508: @cindex @file{oof.fs}
 5509: 
 5510: This section describes the @file{oof.fs} packet. This section uses the
 5511: same rationale why using object-oriented programming, and the same
 5512: terminology.
 5513: 
 5514: The packet described in this section is used in bigFORTH since 1991, and
 5515: used for two large applications: a chromatographic system used to
 5516: create new medicaments, and a graphic user interface library (MINOS).
 5517: 
 5518: You can find a description (in German) of @file{oof.fs} in @cite{Object
 5519: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
 5520: 10(2), 1994.
 5521: 
 5522: @menu
 5523: * Properties of the OOF model::
 5524: * Basic OOF Usage::
 5525: * The base class object::
 5526: * Class Declaration::
 5527: * Class Implementation::
 5528: @end menu
 5529: 
 5530: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
 5531: @subsubsection Properties of the OOF model
 5532: @cindex @file{oof.fs} properties
 5533: 
 5534: @itemize @bullet
 5535: @item
 5536: This model combines object oriented programming with information
 5537: hiding. It helps you writing large application, where scoping is
 5538: necessary, because it provides class-oriented scoping.
 5539: 
 5540: @item
 5541: Named objects, object pointers, and object arrays can be created,
 5542: selector invocation uses the "object selector" syntax. Selector invocation
 5543: to objects and/or selectors on the stack is a bit less convenient, but
 5544: possible.
 5545: 
 5546: @item
 5547: Selector invocation and instance variable usage of the active object is
 5548: straight forward, since both make use of the active object.
 5549: 
 5550: @item
 5551: Late binding is efficient and easy to use.
 5552: 
 5553: @item
 5554: State-smart objects parse selectors. However, extensibility is provided
 5555: using a (parsing) selector @code{postpone} and a selector @code{'}.
 5556: 
 5557: @item
 5558: An implementation in ANS Forth is available.
 5559: 
 5560: @end itemize
 5561: 
 5562: 
 5563: @node Basic OOF Usage, The base class object, Properties of the OOF model, OOF
 5564: @subsubsection Basic OOF Usage
 5565: @cindex @file{oof.fs} usage
 5566: 
 5567: Here, I use the same example as for @code{objects} (@pxref{Basic Objects Usage}).
 5568: 
 5569: You can define a class for graphical objects like this:
 5570: 
 5571: @cindex @code{class} usage
 5572: @cindex @code{class;} usage
 5573: @cindex @code{method} usage
 5574: @example
 5575: object class graphical \ "object" is the parent class
 5576:   method draw ( x y graphical -- )
 5577: class;
 5578: @end example
 5579: 
 5580: This code defines a class @code{graphical} with an
 5581: operation @code{draw}.  We can perform the operation
 5582: @code{draw} on any @code{graphical} object, e.g.:
 5583: 
 5584: @example
 5585: 100 100 t-rex draw
 5586: @end example
 5587: 
 5588: where @code{t-rex} is an object or object pointer, created with e.g.
 5589: @code{graphical : t-rex}.
 5590: 
 5591: @cindex abstract class
 5592: How do we create a graphical object? With the present definitions,
 5593: we cannot create a useful graphical object. The class
 5594: @code{graphical} describes graphical objects in general, but not
 5595: any concrete graphical object type (C++ users would call it an
 5596: @emph{abstract class}); e.g., there is no method for the selector
 5597: @code{draw} in the class @code{graphical}.
 5598: 
 5599: For concrete graphical objects, we define child classes of the
 5600: class @code{graphical}, e.g.:
 5601: 
 5602: @example
 5603: graphical class circle \ "graphical" is the parent class
 5604:   cell var circle-radius
 5605: how:
 5606:   : draw ( x y -- )
 5607:     circle-radius @@ draw-circle ;
 5608: 
 5609:   : init ( n-radius -- (
 5610:     circle-radius ! ;
 5611: class;
 5612: @end example
 5613: 
 5614: Here we define a class @code{circle} as a child of @code{graphical},
 5615: with a field @code{circle-radius}; it defines new methods for the
 5616: selectors @code{draw} and @code{init} (@code{init} is defined in
 5617: @code{object}, the parent class of @code{graphical}).
 5618: 
 5619: Now we can create a circle in the dictionary with
 5620: 
 5621: @example
 5622: 50 circle : my-circle
 5623: @end example
 5624: 
 5625: @code{:} invokes @code{init}, thus initializing the field
 5626: @code{circle-radius} with 50. We can draw this new circle at (100,100)
 5627: with
 5628: 
 5629: @example
 5630: 100 100 my-circle draw
 5631: @end example
 5632: 
 5633: @cindex selector invocation, restrictions
 5634: @cindex class definition, restrictions
 5635: Note: You can invoke a selector only if the receiving object belongs to
 5636: the class where the selector was defined or one of its descendents;
 5637: e.g., you can invoke @code{draw} only for objects belonging to
 5638: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
 5639: mechanism will check if you try to invoke a selector that is not
 5640: defined in this class hierarchy, so you'll get an error at compilation
 5641: time.
 5642: 
 5643: 
 5644: @node The base class object, Class Declaration, Basic OOF Usage, OOF
 5645: @subsubsection The base class @file{object}
 5646: @cindex @file{oof.fs} base class
 5647: 
 5648: When you define a class, you have to specify a parent class.  So how do
 5649: you start defining classes? There is one class available from the start:
 5650: @code{object}. You have to use it as ancestor for all classes. It is the
 5651: only class that has no parent. Classes are also objects, except that
 5652: they don't have instance variables; class manipulation such as
 5653: inheritance or changing definitions of a class is handled through
 5654: selectors of the class @code{object}.
 5655: 
 5656: @code{object} provides a number of selectors:
 5657: 
 5658: @itemize @bullet
 5659: @item
 5660: @code{class} for subclassing, @code{definitions} to add definitions
 5661: later on, and @code{class?} to get type informations (is the class a
 5662: subclass of the class passed on the stack?).
 5663: doc---object-class
 5664: doc---object-definitions
 5665: doc---object-class?
 5666: 
 5667: @item
 5668: @code{init} and @code{dispose} as constructor and destroctor of the
 5669: object. @code{init} is invocated after the object's memory is allocated,
 5670: while @code{dispose} also handles deallocation. Thus if you redefine
 5671: @code{dispose}, you have to call the parent's dispose with @code{super
 5672: dispose}, too.
 5673: doc---object-init
 5674: doc---object-dispose
 5675: 
 5676: @item
 5677: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
 5678: @code{[]} to create named and unnamed objects and object arrays or
 5679: object pointers.
 5680: doc---object-new
 5681: doc---object-new[]
 5682: doc---object-:
 5683: doc---object-ptr
 5684: doc---object-asptr
 5685: doc---object-[]
 5686: 
 5687: @item
 5688: @code{::} and @code{super} for explicit scoping. You should use expicit
 5689: scoping only for super classes or classes with the same set of instance
 5690: variables. Explicit scoped selectors use early binding.
 5691: doc---object-::
 5692: doc---object-super
 5693: 
 5694: @item
 5695: @code{self} to get the address of the object
 5696: doc---object-self
 5697: 
 5698: @item
 5699: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
 5700: pointers and instance defers.
 5701: doc---object-bind
 5702: doc---object-bound
 5703: doc---object-link
 5704: doc---object-is
 5705: 
 5706: @item
 5707: @code{'} to obtain selector tokens, @code{send} to invocate selectors
 5708: form the stack, and @code{postpone} to generate selector invocation code.
 5709: doc---object-'
 5710: doc---object-postpone
 5711: 
 5712: @item
 5713: @code{with} and @code{endwith} to select the active object from the
 5714: stack, and enabling it's scope. Using @code{with} and @code{endwith}
 5715: also allows to create code using selector @code{postpone} without being
 5716: trapped bye the state-smart objects.
 5717: doc---object-with
 5718: doc---object-endwith
 5719: 
 5720: @end itemize
 5721: 
 5722: @node Class Declaration, Class Implementation, The base class object, OOF
 5723: @subsubsection Class Declaration
 5724: @cindex class declaration
 5725: 
 5726: @itemize @bullet
 5727: @item
 5728: Instance variables
 5729: doc---oof-var
 5730: 
 5731: @item
 5732: Object pointers
 5733: doc---oof-ptr
 5734: doc---oof-asptr
 5735: 
 5736: @item
 5737: Instance defers
 5738: doc---oof-defer
 5739: 
 5740: @item
 5741: Method selectors
 5742: doc---oof-early
 5743: doc---oof-method
 5744: 
 5745: @item
 5746: Class wide variables
 5747: doc---oof-static
 5748: 
 5749: @item
 5750: End declaration
 5751: doc---oof-how:
 5752: doc---oof-class;
 5753: 
 5754: @end itemize
 5755: 
 5756: @c -------------------------------------------------------------
 5757: @node Class Implementation,  , Class Declaration, OOF
 5758: @subsubsection Class Implementation
 5759: @cindex class implementation
 5760: 
 5761: @c -------------------------------------------------------------
 5762: @node Mini-OOF, , OOF, Object-oriented Forth
 5763: @subsection Mini-OOF
 5764: @cindex mini-oof
 5765: 
 5766: Gforth's third object oriented Forth package is a 12-liner. It uses a
 5767: bit of a mixture of the @file{object.fs} and the @file{oof.fs} syntax,
 5768: and reduces to the bare minimum of features. This is based on a posting
 5769: of Bernd Paysan in comp.arch.
 5770: 
 5771: @menu
 5772: * Mini-OOF Usage::
 5773: * Mini-OOF Example::
 5774: * Mini-OOF Implementation::
 5775: @end menu
 5776: 
 5777: @c -------------------------------------------------------------
 5778: @node Mini-OOF Usage, Mini-OOF Example, , Mini-OOF
 5779: @subsubsection Usage
 5780: @cindex mini-oof usage
 5781: 
 5782: Basically, there are seven words, to define a method, a variable, a
 5783: class; to end a class, to define a method, to allocate an object, to
 5784: resolve binding, and the base class (which allocates one cell for the
 5785: object pointer).
 5786: 
 5787: doc-method
 5788: 
 5789: Defines a method
 5790: 
 5791: doc-var
 5792: 
 5793: Defines a variable with size bytes
 5794: 
 5795: doc-class
 5796: 
 5797: Starts the definition of a sub-class
 5798: 
 5799: doc-end-class
 5800: 
 5801: Ends the definition of a class
 5802: 
 5803: doc-defines
 5804: 
 5805: Binds the xt to the method name in the class
 5806: 
 5807: doc-new
 5808: 
 5809: Creates a new incarnation of the class
 5810: 
 5811: doc-::
 5812: 
 5813: Compiles the method name of the class (not immediate!)
 5814: 
 5815: doc-object
 5816: 
 5817: Is the base class of all objects
 5818: 
 5819: @c -------------------------------------------------------------
 5820: @node Mini-OOF Example, Mini-OOF Implementation, Mini-OOF Usage, Mini-OOF
 5821: @subsubsection Mini-OOF Example
 5822: @cindex mini-oof example
 5823: 
 5824: A short example shows how to use this package.
 5825: 
 5826: @example
 5827: object class
 5828:   method init
 5829:   method draw
 5830: end-class graphical
 5831: @end example
 5832: 
 5833: This code defines a class @code{graphical} with an
 5834: operation @code{draw}.  We can perform the operation
 5835: @code{draw} on any @code{graphical} object, e.g.:
 5836: 
 5837: @example
 5838: 100 100 t-rex draw
 5839: @end example
 5840: 
 5841: where @code{t-rex} is an object or object pointer, created with e.g.
 5842: @code{graphical new Constant t-rex}.
 5843: 
 5844: For concrete graphical objects, we define child classes of the
 5845: class @code{graphical}, e.g.:
 5846: 
 5847: @example
 5848: graphical class
 5849:   cell var circle-radius
 5850: end-class circle \ "graphical" is the parent class
 5851: 
 5852: :noname ( x y -- )
 5853:   circle-radius @@ draw-circle ; circle defines draw
 5854: :noname ( r -- )
 5855:   circle-radius ! ; circle defines init
 5856: @end example
 5857: 
 5858: There is no implicit init method, so we have to define one. The creation
 5859: code of the object now has to call init explicitely.
 5860: 
 5861: @example
 5862: circle new Constant my-circle
 5863: 50 my-circle init
 5864: @end example
 5865: 
 5866: It is also possible to add a function to create named objects with
 5867: automatic call of @code{init}, given that all objects have @code{init}
 5868: on the same place
 5869: 
 5870: @example
 5871: : new: ( .. o "name" -- )
 5872:     new dup Constant init ;
 5873: 80 circle new: large-circle
 5874: @end example
 5875: 
 5876: We can draw this new circle at (100,100)
 5877: with
 5878: 
 5879: @example
 5880: 100 100 my-circle draw
 5881: @end example
 5882: 
 5883: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
 5884: @subsubsection Mini-OOF Implementation
 5885: 
 5886: Object oriented system with late binding typically use a
 5887: "vtable"-approach: the first variable in each object is a pointer to a
 5888: table, which contains the methods as function pointers. This vtable
 5889: may contain some other informations, too.
 5890: 
 5891: So first, let's declare methods:
 5892: 
 5893: @example
 5894: : method ( m v -- m' v ) Create  over , swap cell+ swap
 5895:   DOES> ( ... o -- ... ) @ over @ + @ execute ;
 5896: @end example
 5897: 
 5898: During method declaration, the number of methods and instance
 5899: variables is on the stack (in address units). @code{method} creates
 5900: one method and increments the method number. To execute a method, it
 5901: takes the object, fetches the vtable pointer, adds the offset, and
 5902: executes the xt stored there. Each method takes the object it is
 5903: invoked from as top of stack parameter. The method itself should
 5904: consume that object.
 5905: 
 5906: Now, we also have to declare instance variables
 5907: 
 5908: @example
 5909: : var ( m v size -- m v' ) Create  over , +
 5910:   DOES> ( o -- addr ) @ + ;
 5911: @end example
 5912: 
 5913: Same as above, a word is created with the current offset. Instance
 5914: variables can have different sizes (cells, floats, doubles, chars), so
 5915: all we do is take the size and add it to the offset. If your machine
 5916: has alignment restrictions, put the proper @code{aligned} or
 5917: @code{faligned} before the variable, it will adjust the variable
 5918: offset. That's why it is on the top of stack.
 5919: 
 5920: We need a starting point (the empty object) and some syntactic sugar:
 5921: 
 5922: @example
 5923: Create object  1 cells , 2 cells ,
 5924: : class ( class -- class methods vars ) dup 2@ ;
 5925: @end example
 5926: 
 5927: Now, for inheritance, the vtable of the parent object has to be
 5928: copied, when a new, derived class is declared. This gives all the
 5929: methods of the parent class, which can be overridden, though.
 5930: 
 5931: @example
 5932: : end-class  ( class methods vars -- )
 5933:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
 5934:   cell+ dup cell+ r> rot @ 2 cells /string move ;
 5935: @end example
 5936: 
 5937: The first line creates the vtable, initialized with
 5938: @code{noop}s. The second line is the inheritance mechanism, it
 5939: copies the xts from the parent vtable.
 5940: 
 5941: We still have no way to define new methods, let's do that now:
 5942: 
 5943: @example
 5944: : defines ( xt class -- ) ' >body @ + ! ;
 5945: @end example
 5946: 
 5947: To allocate a new object, we need a word, too:
 5948: 
 5949: @example
 5950: : new ( class -- o )  here over @ allot swap over ! ;
 5951: @end example
 5952: 
 5953: And sometimes derived classes want to access the method of the
 5954: parent object. There are two ways to achieve this with this OOF:
 5955: first, you could use named words, and second, you could look up the
 5956: vtable of the parent object.
 5957: 
 5958: @example
 5959: : :: ( class "name" -- ) ' >body @ + @ compile, ;
 5960: @end example
 5961: 
 5962: <H2>An Example</H2>
 5963: 
 5964: Nothing can be more confusing than a good example, so here is
 5965: one. First let's declare a text object (further called
 5966: @code{button}), that stores text and position:
 5967: 
 5968: @example
 5969: object class
 5970:   cell var text
 5971:   cell var len
 5972:   cell var x
 5973:   cell var y
 5974:   method init
 5975:   method draw
 5976: end-class button
 5977: @end example
 5978: 
 5979: Now, implement the two methods, @code{draw} and @code{init}:
 5980: 
 5981: @example
 5982: :noname ( o -- ) >r
 5983:  r@ x @ r@ y @ at-xy  r@ text @ r> len @ type ;
 5984:  button defines draw
 5985: :noname ( addr u o -- ) >r
 5986:  0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
 5987:  button defines init
 5988: @end example
 5989: 
 5990: For inheritance, we define a class @code{bold-button}, with no
 5991: new data and no new methods.
 5992: 
 5993: @example
 5994: button class
 5995: end-class bold-button
 5996: 
 5997: : bold   27 emit ." [1m" ;
 5998: : normal 27 emit ." [0m" ;
 5999: 
 6000: :noname bold [ button :: draw ] normal ; bold-button defines draw
 6001: @end example
 6002: 
 6003: And finally, some code to demonstrate how to create objects and
 6004: apply methods:
 6005: 
 6006: @example
 6007: button new Constant foo
 6008: s" thin foo" foo init
 6009: page
 6010: foo draw
 6011: bold-button new Constant bar
 6012: s" fat bar" bar init
 6013: 1 bar y !
 6014: bar draw
 6015: @end example
 6016: 
 6017: @c -------------------------------------------------------------
 6018: @node Tokens for Words, Word Lists, Object-oriented Forth, Words
 6019: @section Tokens for Words
 6020: @cindex tokens for words
 6021: 
 6022: This chapter describes the creation and use of tokens that represent
 6023: words on the stack (and in data space).
 6024: 
 6025: Named words have interpretation and compilation semantics. Unnamed words
 6026: just have execution semantics.
 6027: 
 6028: @comment TODO ?normally interpretation semantics are the execution semantics.
 6029: @comment this should all be covered in earlier ss
 6030: 
 6031: @cindex execution token
 6032: An @dfn{execution token} represents the execution semantics of an
 6033: unnamed word. An execution token occupies one cell. As explained in
 6034: @ref{Supplying names}, the execution token of the last word
 6035: defined can be produced with @code{lastxt}.
 6036: 
 6037: You can perform the semantics represented by an execution token with:
 6038: doc-execute
 6039: You can compile the word with:
 6040: doc-compile,
 6041: 
 6042: @cindex code field address
 6043: @cindex CFA
 6044: In Gforth, the abstract data type @emph{execution token} is implemented
 6045: as CFA (code field address).
 6046: @comment TODO note that the standard does not say what it represents..
 6047: @comment and you cannot necessarily compile it in all Forths (eg native
 6048: @comment compilers?).
 6049: 
 6050: The interpretation semantics of a named word are also represented by an
 6051: execution token. You can get it with
 6052: 
 6053: doc-[']
 6054: doc-'
 6055: 
 6056: For literals, you use @code{'} in interpreted code and @code{[']} in
 6057: compiled code. Gforth's @code{'} and @code{[']} behave somewhat unusual
 6058: by complaining about compile-only words. To get an execution token for a
 6059: compiling word @var{X}, use @code{COMP' @var{X} drop} or @code{[COMP']
 6060: @var{X} drop}.
 6061: 
 6062: @cindex compilation token
 6063: The compilation semantics are represented by a @dfn{compilation token}
 6064: consisting of two cells: @var{w xt}. The top cell @var{xt} is an
 6065: execution token. The compilation semantics represented by the
 6066: compilation token can be performed with @code{execute}, which consumes
 6067: the whole compilation token, with an additional stack effect determined
 6068: by the represented compilation semantics.
 6069: 
 6070: doc-[comp']
 6071: doc-comp'
 6072: 
 6073: You can compile the compilation semantics with @code{postpone,}. I.e.,
 6074: @code{COMP' @var{word} POSTPONE,} is equivalent to @code{POSTPONE
 6075: @var{word}}.
 6076: 
 6077: doc-postpone,
 6078: 
 6079: At present, the @var{w} part of a compilation token is an execution
 6080: token, and the @var{xt} part represents either @code{execute} or
 6081: @code{compile,}. However, don't rely on that knowledge, unless necessary;
 6082: we may introduce unusual compilation tokens in the future (e.g.,
 6083: compilation tokens representing the compilation semantics of literals).
 6084: 
 6085: @cindex name token
 6086: @cindex name field address
 6087: @cindex NFA
 6088: Named words are also represented by the @dfn{name token}. The abstract
 6089: data type @emph{name token} is implemented as NFA (name field address).
 6090: 
 6091: doc-find-name
 6092: doc-name>int
 6093: doc-name?int
 6094: doc-name>comp
 6095: doc-name>string
 6096: 
 6097: @node Word Lists, Environmental Queries, Tokens for Words, Words
 6098: @section Word Lists
 6099: @cindex word lists
 6100: @cindex name dictionary
 6101: 
 6102: @cindex wid
 6103: All definitions other than those created by @code{:noname} have an entry
 6104: in the name dictionary. The name dictionary is fragmented into a number
 6105: of parts, called @var{word lists}. A word list is identified by a
 6106: cell-sized word list identifier (@var{wid}) in much the same way as a
 6107: file is identified by a file handle. The numerical value of the wid has
 6108: no (portable) meaning, and might change from session to session.
 6109: 
 6110: @cindex compilation word list
 6111: At any one time, a single word list is defined as the word list to which
 6112: all new definitions will be added -- this is called the @var{compilation
 6113: word list}. When Gforth is started, the compilation word list is the
 6114: word list called @code{FORTH-WORDLIST}.
 6115: 
 6116: @cindex search order stack
 6117: Forth maintains a stack of word lists, representing the @var{search
 6118: order}.  When the name dictionary is searched (for example, when
 6119: attempting to find a word's execution token during compilation), only
 6120: those word lists that are currently in the search order are
 6121: searched. The most recently-defined word in the word list at the top of
 6122: the word list stack is searched first, and the search proceeds until
 6123: either the word is located or the oldest definition in the word list at
 6124: the bottom of the stack is reached. Definitions of the word may exist in
 6125: more than one word lists; the search order determines which version will
 6126: be found.
 6127: 
 6128: The ANS Forth Standard "Search order" word set is intended to provide a
 6129: set of low-level tools that allow various different schemes to be
 6130: implemented. Gforth provides @code{vocabulary}, a traditional Forth
 6131: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
 6132: Standard Forth.
 6133: 
 6134: TODO: locals section refers to here, saying that every word list (aka
 6135: vocabulary) has its own methods for searching etc. Need to document that.
 6136: 
 6137: doc-forth-wordlist
 6138: doc-definitions
 6139: doc-get-current
 6140: doc-set-current
 6141: 
 6142: @comment TODO when a defn (like set-order) is instanced twice, the second instance gets documented.
 6143: @comment In general that might be fine, but in this example (search.fs) the second instance is an
 6144: @comment alias, so it would not naturally have documentation
 6145: 
 6146: doc-get-order
 6147: doc-set-order
 6148: doc-wordlist
 6149: doc-also
 6150: doc-forth
 6151: doc-only
 6152: doc-order
 6153: doc-previous
 6154: 
 6155: doc-find
 6156: doc-search-wordlist
 6157: 
 6158: doc-words
 6159: doc-vlist
 6160: 
 6161: doc-mappedwordlist
 6162: doc-root
 6163: doc-vocabulary
 6164: doc-seal
 6165: doc-vocs
 6166: doc-current
 6167: doc-context
 6168: 
 6169: @menu
 6170: * Why use word lists?::
 6171: * Word list examples::
 6172: @end menu
 6173: 
 6174: @node Why use word lists?, Word list examples, Word Lists, Word Lists
 6175: @subsection Why use word lists?
 6176: @cindex word lists - why use them?
 6177: 
 6178: There are several reasons for using multiple word lists:
 6179: 
 6180: @itemize @bullet
 6181: @item
 6182: To improve compilation speed by reducing the number of name dictionary
 6183: entries that must be searched. This is achieved by creating a new
 6184: word list that contains all of the definitions that are used in the
 6185: definition of a Forth system but which would not usually be used by
 6186: programs running on that system. That word list would be on the search
 6187: list when the Forth system was compiled but would be removed from the
 6188: search list for normal operation. This can be a useful technique for
 6189: low-performance systems (for example, 8-bit processors in embedded
 6190: systems) but is unlikely to be necessary in high-performance desktop
 6191: systems.
 6192: @item
 6193: To prevent a set of words from being used outside the context in which
 6194: they are valid. Two classic examples of this are an integrated editor
 6195: (all of the edit commands are defined in a separate word list; the
 6196: search order is set to the editor word list when the editor is invoked;
 6197: the old search order is restored when the editor is terminated) and an
 6198: integrated assembler (the op-codes for the machine are defined in a
 6199: separate word list which is used when a @code{CODE} word is defined).
 6200: @item
 6201: To prevent a name-space clash between multiple definitions with the same
 6202: name. For example, when building a cross-compiler you might have a word
 6203: @code{IF} that generates conditional code for your target system. By
 6204: placing this definition in a different word list you can control whether
 6205: the host system's @code{IF} or the target system's @code{IF} get used in
 6206: any particular context by controlling the order of the word lists on the
 6207: search order stack.
 6208: @end itemize
 6209: 
 6210: @node Word list examples, ,Why use word lists?, Word Lists
 6211: @subsection Word list examples
 6212: @cindex word lists - examples
 6213: 
 6214: Here is an example of creating and using a new wordlist using ANS
 6215: Standard words:
 6216: 
 6217: @example
 6218: wordlist constant my-new-words-wordlist
 6219: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
 6220: 
 6221: \ add it to the search order
 6222: also my-new-words
 6223: 
 6224: \ alternatively, add it to the search order and make it
 6225: \ the compilation word list
 6226: also my-new-words definitions
 6227: \ type "order" to see the problem
 6228: @end example
 6229: 
 6230: The problem with this example is that @code{order} has no way to
 6231: associate the name @code{my-new-words} with the wid of the word list (in
 6232: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
 6233: that has no associated name). There is no Standard way of associating a
 6234: name with a wid.
 6235: 
 6236: In Gforth, this example can be re-coded using @code{vocabulary}, which
 6237: associates a name with a wid:
 6238: 
 6239: @example
 6240: vocabulary my-new-words
 6241: 
 6242: \ add it to the search order
 6243: my-new-words
 6244: 
 6245: \ alternatively, add it to the search order and make it
 6246: \ the compilation word list
 6247: my-new-words definitions
 6248: \ type "order" to see that the problem is solved
 6249: @end example
 6250: 
 6251: 
 6252: @node Environmental Queries, Files, Word Lists, Words
 6253: @section Environmental Queries
 6254: @cindex environmental queries
 6255: @comment TODO more index entries
 6256: 
 6257: The ANS Standard introduced the idea of "environmental queries" as a way
 6258: for a program running on a system to determine certain characteristics of the system.
 6259: The Standard specifies a number of strings that might be recognised by a system.
 6260: 
 6261: The Standard requires that the name space used for environmental queries
 6262: be distinct from the name space used for definitions.
 6263: 
 6264: Typically, environmental queries are supported by creating a set of
 6265: definitions in a word set that is @var{only} used during environmental
 6266: queries; that is what Gforth does. There is no Standard way of adding
 6267: definitions to the set of recognised environmental queries, but any
 6268: implementation that supports the loading of optional word sets must have
 6269: some mechanism for doing this (after loading the word set, the
 6270: associated environmental query string must return @code{true}). In
 6271: Gforth, the word set used to honour environmental queries can be
 6272: manipulated just like any other word set.
 6273: 
 6274: doc-environment?
 6275: doc-environment-wordlist
 6276: 
 6277: doc-gforth
 6278: doc-os-class
 6279: 
 6280: Note that, whilst the documentation for (eg) @code{gforth} shows it
 6281: returning two items on the stack, querying it using @code{environment?}
 6282: will return an additional item; the @code{true} flag that shows that the
 6283: string was recognised.
 6284: 
 6285: TODO Document the standard strings or note where they are documented herein
 6286: 
 6287: Here are some examples of using environmental queries:
 6288: 
 6289: @example
 6290: s" address-unit-bits" environment? 0=
 6291: [IF]
 6292:      cr .( environmental attribute address-units-bits unknown... ) cr
 6293: [THEN]
 6294: 
 6295: s" block" environment? [IF] DROP include block.fs [THEN]
 6296: 
 6297: s" gforth" environment? [IF] 2DROP include compat/vocabulary.fs [THEN]
 6298: 
 6299: s" gforth" environment? [IF] .( Gforth version ) TYPE [ELSE] .( Not Gforth..) [THEN]
 6300: 
 6301: @end example
 6302: 
 6303: 
 6304: Here is an example of adding a definition to the environment word list:
 6305: 
 6306: @example
 6307: get-current environment-wordlist set-current
 6308: true constant block
 6309: true constant block-ext
 6310: set-current
 6311: @end example
 6312: 
 6313: You can see what definitions are in the environment word list like this:
 6314: 
 6315: @example
 6316: get-order 1+ environment-wordlist swap set-order words previous
 6317: @end example
 6318: 
 6319: 
 6320: 
 6321: @node Files, Including Files, Environmental Queries, Words
 6322: @section Files
 6323: 
 6324: This chapter describes how to operate on files from Forth.
 6325: 
 6326: Files are opened/created by name and type. The following types are
 6327: recognised:
 6328: 
 6329: doc-r/o
 6330: doc-r/w
 6331: doc-w/o
 6332: doc-bin
 6333: 
 6334: When a file is opened/created, it returns a file identifier,
 6335: @var{wfileid} that is used for all other file commands. All file
 6336: commands also return a status value, @var{wior}, that is 0 for a
 6337: successful operation and an implementation-defined non-zero value in the
 6338: case of an error.
 6339: 
 6340: doc-open-file
 6341: doc-create-file
 6342: 
 6343: doc-close-file
 6344: doc-delete-file
 6345: doc-rename-file
 6346: doc-read-file
 6347: doc-read-line
 6348: doc-write-file
 6349: doc-write-line
 6350: doc-emit-file
 6351: doc-flush-file
 6352: 
 6353: doc-file-status
 6354: doc-file-position
 6355: doc-reposition-file
 6356: doc-file-size
 6357: doc-resize-file
 6358: 
 6359: @node Including Files, Blocks, Files, Words
 6360: @section Including Files
 6361: @cindex including files
 6362: 
 6363: @menu
 6364: * Words for Including::         
 6365: * Search Path::                 
 6366: * Forth Search Paths::    
 6367: * General Search Paths::        
 6368: @end menu
 6369: 
 6370: @node Words for Including, Search Path, Including Files, Including Files
 6371: @subsection Words for Including
 6372: 
 6373: doc-include-file
 6374: doc-included
 6375: doc-include
 6376: 
 6377: Usually you want to include a file only if it is not included already
 6378: (by, say, another source file):
 6379: @comment TODO describe what happens on error. Describes how the require
 6380: @comment stuff works and describe how to clear/reset the history (eg
 6381: @comment for debug). Might want to include that in the MARKER example.
 6382: 
 6383: doc-required
 6384: doc-require
 6385: doc-needs
 6386: 
 6387: A definition in ANS Standard Forth for @code{required} is provided in
 6388: @file{compat/required.fs}.
 6389: 
 6390: @cindex stack effect of included files
 6391: @cindex including files, stack effect
 6392: I recommend that you write your source files such that interpreting them
 6393: does not change the stack. This allows using these files with
 6394: @code{required} and friends without complications. E.g.,
 6395: 
 6396: @example
 6397: 1 require foo.fs drop
 6398: @end example
 6399: 
 6400: @node Search Path, Forth Search Paths, Words for Including, Including Files
 6401: @subsection Search Path
 6402: @cindex path for @code{included}
 6403: @cindex file search path
 6404: @cindex include search path
 6405: @cindex search path for files
 6406: 
 6407: @comment what uses these search paths.. just inc;lude and friends?
 6408: If you specify an absolute filename (i.e., a filename starting with
 6409: @file{/} or @file{~}, or with @file{:} in the second position (as in
 6410: @samp{C:...})) for @code{included} and friends, that file is included
 6411: just as you would expect.
 6412: 
 6413: For relative filenames, Gforth uses a search path similar to Forth's
 6414: search order (@pxref{Word Lists}). It tries to find the given filename in
 6415: the directories present in the path, and includes the first one it
 6416: finds.
 6417: 
 6418: If the search path contains the directory @file{.} (as it should), this
 6419: refers to the directory that the present file was @code{included}
 6420: from. This allows files to include other files relative to their own
 6421: position (irrespective of the current working directory or the absolute
 6422: position).  This feature is essential for libraries consisting of
 6423: several files, where a file may include other files from the library.
 6424: It corresponds to @code{#include "..."} in C. If the current input
 6425: source is not a file, @file{.} refers to the directory of the innermost
 6426: file being included, or, if there is no file being included, to the
 6427: current working directory.
 6428: 
 6429: Use @file{~+} to refer to the current working directory (as in the
 6430: @code{bash}).
 6431: 
 6432: If the filename starts with @file{./}, the search path is not searched
 6433: (just as with absolute filenames), and the @file{.} has the same meaning
 6434: as described above.
 6435: 
 6436: @node Forth Search Paths, General Search Paths, Search Path, Including Files
 6437: @subsection Forth Search Paths
 6438: @cindex search path control - forth
 6439: 
 6440: The search path is initialized when you start Gforth (@pxref{Invoking
 6441: Gforth}). You can display it with
 6442: 
 6443: doc-.fpath
 6444: 
 6445: You can change it later with the following words:
 6446: 
 6447: doc-fpath+
 6448: doc-fpath=
 6449: 
 6450: Using fpath and require would look like:
 6451: 
 6452: @example
 6453: fpath= /usr/lib/forth/|./
 6454: 
 6455: require timer.fs
 6456: @end example
 6457: 
 6458: If you have the need to look for a file in the Forth search path, you could
 6459: use this Gforth feature in your application:
 6460: 
 6461: doc-open-fpath-file
 6462: 
 6463: @node General Search Paths,  , Forth Search Paths, Including Files
 6464: @subsection General Search Paths
 6465: @cindex search path control - for user applications
 6466: 
 6467: Your application may need to search files in sevaral directories, like
 6468: @code{included} does. For this purpose you can define and use your own
 6469: search paths. Create a search path like this:
 6470: 
 6471: @example
 6472: \ Make a buffer for the path:
 6473: create mypath   100 chars ,     \ maximum length (is checked)
 6474:                 0 ,             \ real len
 6475:                 100 chars allot \ space for path
 6476: @end example
 6477: 
 6478: You have the same functions for the forth search path in a generic version
 6479: for different paths.
 6480: 
 6481: Gforth also provides generic equivalents of the Forth search path words:
 6482: 
 6483: doc-.path
 6484: doc-path+
 6485: doc-path=
 6486: doc-open-path-file
 6487: 
 6488: 
 6489: @node Blocks, Other I/O, Including Files, Words
 6490: @section Blocks
 6491: 
 6492: This chapter describes how to use block files within Gforth.
 6493: 
 6494: Block files are traditionally means of data and source storage in
 6495: Forth. They have been very important in resource-starved computers
 6496: without OS in the past. Gforth doesn't encourage to use blocks as
 6497: source, and provides blocks only for backward compatibility. The ANS
 6498: standard requires blocks to be available when files are.
 6499: 
 6500: @comment TODO what about errors on open-blocks?
 6501: doc-open-blocks
 6502: doc-use
 6503: doc-scr
 6504: doc-blk
 6505: doc-get-block-fid
 6506: doc-block-position
 6507: doc-update
 6508: doc-save-buffers
 6509: doc-save-buffer
 6510: doc-empty-buffers
 6511: doc-empty-buffer
 6512: doc-flush
 6513: doc-get-buffer
 6514: doc---block-block
 6515: doc-buffer
 6516: doc-updated?
 6517: doc-list
 6518: doc-load
 6519: doc-thru
 6520: doc-+load
 6521: doc-+thru
 6522: doc---block--->
 6523: doc-block-included
 6524: 
 6525: @node Other I/O, Programming Tools, Blocks, Words
 6526: @section Other I/O
 6527: @comment TODO more index entries
 6528: 
 6529: @menu
 6530: * Simple numeric output::       Predefined formats
 6531: * Formatted numeric output::    Formatted (pictured) output
 6532: * String Formats::              How Forth stores strings in memory
 6533: * Displaying characters and strings:: Other stuff
 6534: * Input::                       Input
 6535: @end menu
 6536: 
 6537: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
 6538: @subsection Simple numeric output
 6539: @cindex Simple numeric output
 6540: @comment TODO more index entries
 6541: 
 6542: The simplest output functions are those that display numbers from the
 6543: data or floating-point stacks. Floating-point output is always displayed
 6544: using base 10. Numbers displayed from the data stack use the value stored
 6545: in @code{base}.
 6546: 
 6547: doc-.
 6548: doc-dec.
 6549: doc-hex.
 6550: doc-u.
 6551: doc-.r
 6552: doc-u.r
 6553: doc-d.
 6554: doc-ud.
 6555: doc-d.r
 6556: doc-ud.r
 6557: doc-f.
 6558: doc-fe.
 6559: doc-fs.
 6560: 
 6561: Examples of printing the number 1234.5678E23 in the different floating-point output
 6562: formats are shown below:
 6563: 
 6564: @example
 6565: f. 123456779999999000000000000.
 6566: fe. 123.456779999999E24
 6567: fs. 1.23456779999999E26
 6568: @end example
 6569: 
 6570: 
 6571: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
 6572: @subsection Formatted numeric output
 6573: @cindex Formatted numeric output
 6574: @cindex pictured numeric output
 6575: @comment TODO more index entries
 6576: 
 6577: Forth traditionally uses a technique called @var{pictured numeric
 6578: output} for formatted printing of integers.  In this technique,
 6579: digits are extracted from the number (using the current output radix
 6580: defined by @code{base}), converted to ASCII codes and appended to a
 6581: string that is built in a scratch-pad area of memory
 6582: (@pxref{core-idef,Implementation-defined options}). During the extraction
 6583: sequence, other arbitrary characters can be appended to the string. The
 6584: completed string is specified by an address and length and can
 6585: be manipulated (@code{TYPE}ed, copied, modified) under program control.
 6586: 
 6587: All of the words described in the previous section for simple numeric
 6588: output are implemented in Gforth using pictured numeric output.
 6589: 
 6590: Three important things to remember about Pictured Numeric Output:
 6591: 
 6592: @itemize @bullet
 6593: @item
 6594: It always operates on double-precision numbers; to display a single-precision number,
 6595: convert it first (@pxref{Double precision} for ways of doing this).
 6596: @item
 6597: It always treats the double-precision number as though it were unsigned. Refer to
 6598: the examples below for ways of printing signed numbers.
 6599: @item
 6600: The string is built up from right to left; least significant digit first.
 6601: @end itemize
 6602: 
 6603: doc-<#
 6604: doc-#
 6605: doc-#s
 6606: doc-hold
 6607: doc-sign
 6608: doc-#>
 6609: 
 6610: doc-represent
 6611: 
 6612: Here are some examples of using pictured numeric output:
 6613: 
 6614: @example
 6615: : my-u. ( u -- )
 6616:   \ Simplest use of pns.. behaves like Standard u. 
 6617:   0              \ convert to unsigned double
 6618:   <#             \ start conversion
 6619:   #s             \ convert all digits
 6620:   #>             \ complete conversion
 6621:   TYPE SPACE ;   \ display, with trailing space
 6622: 
 6623: : cents-only ( u -- )
 6624:   0              \ convert to unsigned double
 6625:   <#             \ start conversion
 6626:   # #            \ convert two least-significant digits
 6627:   #>             \ complete conversion, discard other digits
 6628:   TYPE SPACE ;   \ display, with trailing space
 6629: 
 6630: : dollars-and-cents ( u -- )
 6631:   0              \ convert to unsigned double
 6632:   <#             \ start conversion
 6633:   # #            \ convert two least-significant digits
 6634:   [char] . hold  \ insert decimal point
 6635:   #s             \ convert remaining digits
 6636:   [char] $ hold  \ append currency symbol
 6637:   #>             \ complete conversion
 6638:   TYPE SPACE ;   \ display, with trailing space
 6639: 
 6640: : my-. ( n -- )
 6641:   \ handling negatives.. behaves like Standard .
 6642:   s>d            \ convert to signed double
 6643:   swap over dabs \ leave sign byte followed by unsigned double
 6644:   <#             \ start conversion
 6645:   #s             \ convert all digits
 6646:   rot sign       \ get at sign byte, append "-" if needed
 6647:   #>             \ complete conversion
 6648:   TYPE SPACE ;   \ display, with trailing space
 6649: 
 6650: : account. ( n -- )
 6651:   \ accountants don't like minus signs, they use braces
 6652:   \ for negative numbers
 6653:   s>d            \ convert to signed double
 6654:   swap over dabs \ leave sign byte followed by unsigned double
 6655:   <#             \ start conversion
 6656:   2 pick         \ get copy of sign byte
 6657:   0< IF [char] ) hold THEN \ right-most character of output
 6658:   #s             \ convert all digits
 6659:   rot            \ get at sign byte
 6660:   0< IF [char] ( hold THEN
 6661:   #>             \ complete conversion
 6662:   TYPE SPACE ;   \ display, with trailing space
 6663: @end example
 6664: 
 6665: Here are some examples of using these words:
 6666: 
 6667: @example
 6668: 1 my-u. 1
 6669: hex -1 my-u. decimal FFFFFFFF
 6670: 1 cents-only 01
 6671: 1234 cents-only 34
 6672: 2 dollars-and-cents $0.02
 6673: 1234 dollars-and-cents $12.34
 6674: 123 my-. 123
 6675: -123 my. -123
 6676: 123 account. 123
 6677: -456 account. (456)
 6678: @end example
 6679: 
 6680: 
 6681: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
 6682: @subsection String Formats
 6683: @cindex string formats
 6684: 
 6685: @comment TODO more index entries
 6686: 
 6687: Forth commonly uses two different methods for representing a string:
 6688: 
 6689: @itemize @bullet
 6690: @item
 6691: @cindex address of counted string
 6692: As a @var{counted string}, represented by a c-addr. The char addressed
 6693: by c-addr contains a character-count, n,  of the string and the string
 6694: occupies the subsequent n char addresses in memory.
 6695: @item
 6696: As cell pair on the stack; c-addr u, where u is the length of the string
 6697: in characters, and c-addr is the address of the first byte of the string.
 6698: @end itemize
 6699: 
 6700: The ANS Forth Standard encourages the use of the second format when
 6701: representing strings on the stack, whilst conceeding that the counted
 6702: string format remains useful as a way of storing strings in memory.
 6703: 
 6704: doc-count
 6705: 
 6706: @xref{Memory Blocks} for words that move, copy and search
 6707: for strings. @xref{Displaying characters and strings,} for words that
 6708: display characters and strings.
 6709: 
 6710: 
 6711: @node Displaying characters and strings, Input, String Formats, Other I/O
 6712: @subsection Displaying characters and strings
 6713: @cindex displaying characters and strings
 6714: @cindex compiling characters and strings
 6715: @cindex cursor control
 6716: 
 6717: @comment TODO more index entries
 6718: 
 6719: This section starts with a glossary of Forth words and ends with a set
 6720: of examples.
 6721: 
 6722: doc-bl
 6723: doc-space
 6724: doc-spaces
 6725: doc-emit
 6726: doc-."
 6727: doc-.(
 6728: doc-type
 6729: doc-cr
 6730: doc-at-xy
 6731: doc-page
 6732: doc-s"
 6733: doc-c"
 6734: doc-char
 6735: doc-[char]
 6736: doc-sliteral
 6737: 
 6738: As an example, consider the following text, stored in a file @file{test.fs}:
 6739: 
 6740: @example
 6741: .( text-1)
 6742: : my-word
 6743:   ." text-2" cr
 6744:   .( text-3)
 6745: ;
 6746: 
 6747: ." text-4"
 6748: 
 6749: : my-char
 6750:   [char] ALPHABET emit
 6751:   char emit
 6752: ;
 6753: @end example
 6754: 
 6755: When you load this code into Gforth, the following output is generated:
 6756: 
 6757: @example
 6758: @kbd{include test.fs} text-1text-3text-4 ok
 6759: @end example
 6760: 
 6761: @itemize @bullet
 6762: @item
 6763: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
 6764: is an immediate word; it behaves in the same way whether it is used inside
 6765: or outside a colon definition.
 6766: @item
 6767: Message @code{text-4} is displayed because of Gforth's added interpretation
 6768: semantics for @code{."}.
 6769: @item
 6770: Message @code{text-2} is @var{not} displayed, because the text interpreter
 6771: performs the compilation semantics for @code{."} within the definition of
 6772: @code{my-word}.
 6773: @end itemize
 6774: 
 6775: Here are some examples of executing @code{my-word} and @code{my-char}:
 6776: 
 6777: @example
 6778: my-word text-2
 6779:  ok
 6780: @kbd{my-char fred} Af ok
 6781: @kbd{my-char jim} Aj ok
 6782: @end example
 6783: 
 6784: @itemize @bullet
 6785: @item
 6786: Message @code{text-2} is displayed because of the run-time behaviour of
 6787: @code{."}.
 6788: @item
 6789: @code{[char]} compiles the "A" from "ALPHABET" and puts its display code
 6790: on the stack at run-time. @code{emit} always displays the character
 6791: when @code{my-char} is executed.
 6792: @item
 6793: @code{char} parses a string at run-time and the second @code{emit} displays
 6794: the first character of the string.
 6795: @item
 6796: If you type @code{see my-char} you can see that @code{[char]} discarded
 6797: the text "LPHABET" and only compiled the display code for "A" into the
 6798: definition of @code{my-char}.
 6799: @end itemize
 6800: 
 6801: 
 6802: 
 6803: @node Input, , Displaying characters and strings, Other I/O
 6804: @subsection Input
 6805: @cindex Input
 6806: @comment TODO more index entries
 6807: 
 6808: Blah on traditional and recommended string formats.
 6809: 
 6810: doc-tib
 6811: doc-#tib
 6812: doc--trailing
 6813: doc-/string
 6814: doc-convert
 6815: doc->number
 6816: doc->float
 6817: doc-accept
 6818: doc-query
 6819: doc-expect
 6820: doc-evaluate
 6821: doc-key
 6822: doc-key?
 6823: 
 6824: TODO reference the block move stuff elsewhere
 6825: 
 6826: TODO convert and >number might be better in the numeric input section.
 6827: 
 6828: TODO maybe some of these shouldn't be here but should be in a "parsing" section
 6829: 
 6830: 
 6831: @node Programming Tools, Assembler and Code Words, Other I/O, Words
 6832: @section Programming Tools
 6833: @cindex programming tools
 6834: 
 6835: @menu
 6836: * Debugging::                   Simple and quick.
 6837: * Assertions::                  Making your programs self-checking.
 6838: * Singlestep Debugger::		Executing your program word by word.
 6839: @end menu
 6840: 
 6841: @node Debugging, Assertions, Programming Tools, Programming Tools
 6842: @subsection Debugging
 6843: @cindex debugging
 6844: 
 6845: Languages with a slow edit/compile/link/test development loop tend to
 6846: require sophisticated tracing/stepping debuggers to facilate
 6847: productive debugging.
 6848: 
 6849: A much better (faster) way in fast-compiling languages is to add
 6850: printing code at well-selected places, let the program run, look at
 6851: the output, see where things went wrong, add more printing code, etc.,
 6852: until the bug is found.
 6853: 
 6854: The simple debugging aids provided in @file{debugs.fs}
 6855: are meant to support this style of debugging. In addition, there are
 6856: words for non-destructively inspecting the stack and memory:
 6857: 
 6858: doc-.s
 6859: doc-f.s
 6860: 
 6861: There is a word @code{.r} but it does @var{not} display the return
 6862: stack! It is used for formatted numeric output.
 6863: 
 6864: doc-depth
 6865: doc-fdepth
 6866: doc-clearstack
 6867: doc-?
 6868: doc-dump
 6869: 
 6870: The word @code{~~} prints debugging information (by default the source
 6871: location and the stack contents). It is easy to insert. If you use Emacs
 6872: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
 6873: query-replace them with nothing). The deferred words
 6874: @code{printdebugdata} and @code{printdebugline} control the output of
 6875: @code{~~}. The default source location output format works well with
 6876: Emacs' compilation mode, so you can step through the program at the
 6877: source level using @kbd{C-x `} (the advantage over a stepping debugger
 6878: is that you can step in any direction and you know where the crash has
 6879: happened or where the strange data has occurred).
 6880: 
 6881: Note that the default actions clobber the contents of the pictured
 6882: numeric output string, so you should not use @code{~~}, e.g., between
 6883: @code{<#} and @code{#>}.
 6884: 
 6885: doc-~~
 6886: doc-printdebugdata
 6887: doc-printdebugline
 6888: 
 6889: doc-see
 6890: doc-marker
 6891: 
 6892: Here's an example of using @code{marker} at the start of a source file
 6893: that you are debugging; it ensures that you only ever have one copy of
 6894: the file's definitions compiled at any time:
 6895: 
 6896: @example
 6897: [IFDEF] my-code
 6898:     my-code
 6899: [ENDIF]
 6900: 
 6901: marker my-code
 6902: 
 6903: \ .. definitions start here
 6904: \ .
 6905: \ .
 6906: \ end
 6907: @end example
 6908: 
 6909: 
 6910: 
 6911: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
 6912: @subsection Assertions
 6913: @cindex assertions
 6914: 
 6915: It is a good idea to make your programs self-checking, in particular, if
 6916: you use an assumption (e.g., that a certain field of a data structure is
 6917: never zero) that may become wrong during maintenance. Gforth supports
 6918: assertions for this purpose. They are used like this:
 6919: 
 6920: @example
 6921: assert( @var{flag} )
 6922: @end example
 6923: 
 6924: The code between @code{assert(} and @code{)} should compute a flag, that
 6925: should be true if everything is alright and false otherwise. It should
 6926: not change anything else on the stack. The overall stack effect of the
 6927: assertion is @code{( -- )}. E.g.
 6928: 
 6929: @example
 6930: assert( 1 1 + 2 = ) \ what we learn in school
 6931: assert( dup 0<> ) \ assert that the top of stack is not zero
 6932: assert( false ) \ this code should not be reached
 6933: @end example
 6934: 
 6935: The need for assertions is different at different times. During
 6936: debugging, we want more checking, in production we sometimes care more
 6937: for speed. Therefore, assertions can be turned off, i.e., the assertion
 6938: becomes a comment. Depending on the importance of an assertion and the
 6939: time it takes to check it, you may want to turn off some assertions and
 6940: keep others turned on. Gforth provides several levels of assertions for
 6941: this purpose:
 6942: 
 6943: doc-assert0(
 6944: doc-assert1(
 6945: doc-assert2(
 6946: doc-assert3(
 6947: doc-assert(
 6948: doc-)
 6949: 
 6950: @code{Assert(} is the same as @code{assert1(}. The variable
 6951: @code{assert-level} specifies the highest assertions that are turned
 6952: on. I.e., at the default @code{assert-level} of one, @code{assert0(} and
 6953: @code{assert1(} assertions perform checking, while @code{assert2(} and
 6954: @code{assert3(} assertions are treated as comments.
 6955: 
 6956: Note that the @code{assert-level} is evaluated at compile-time, not at
 6957: run-time. I.e., you cannot turn assertions on or off at run-time, you
 6958: have to set the @code{assert-level} appropriately before compiling a
 6959: piece of code. You can compile several pieces of code at several
 6960: @code{assert-level}s (e.g., a trusted library at level 1 and newly
 6961: written code at level 3).
 6962: 
 6963: doc-assert-level
 6964: 
 6965: If an assertion fails, a message compatible with Emacs' compilation mode
 6966: is produced and the execution is aborted (currently with @code{ABORT"}.
 6967: If there is interest, we will introduce a special throw code. But if you
 6968: intend to @code{catch} a specific condition, using @code{throw} is
 6969: probably more appropriate than an assertion).
 6970: 
 6971: Definitions in ANS Standard Forth for these assertion words are provided
 6972: in @file{compat/assert.fs}.
 6973: 
 6974: 
 6975: @node Singlestep Debugger, , Assertions, Programming Tools
 6976: @subsection Singlestep Debugger
 6977: @cindex singlestep Debugger
 6978: @cindex debugging Singlestep
 6979: @cindex @code{dbg}
 6980: @cindex @code{BREAK:}
 6981: @cindex @code{BREAK"}
 6982: 
 6983: When a new word is created there's often the need to check whether it behaves
 6984: correctly or not. You can do this by typing @code{dbg badword}.
 6985: 
 6986: doc-dbg
 6987: 
 6988: This might look like:
 6989: 
 6990: @example
 6991: : badword 0 DO i . LOOP ;  ok
 6992: 2 dbg badword 
 6993: : badword  
 6994: Scanning code...
 6995: 
 6996: Nesting debugger ready!
 6997: 
 6998: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
 6999: 400D4740  8049F68 DO             -> [ 0 ] 
 7000: 400D4744  804A0C8 i              -> [ 1 ] 00000 
 7001: 400D4748 400C5E60 .              -> 0 [ 0 ] 
 7002: 400D474C  8049D0C LOOP           -> [ 0 ] 
 7003: 400D4744  804A0C8 i              -> [ 1 ] 00001 
 7004: 400D4748 400C5E60 .              -> 1 [ 0 ] 
 7005: 400D474C  8049D0C LOOP           -> [ 0 ] 
 7006: 400D4758  804B384 ;              ->  ok
 7007: @end example
 7008: 
 7009: Each line displayed is one step. You always have to hit return to
 7010: execute the next word that is displayed. If you don't want to execute
 7011: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
 7012: an overview what keys are available:
 7013: 
 7014: @table @i
 7015: 
 7016: @item <return>
 7017: Next; Execute the next word.
 7018: 
 7019: @item n
 7020: Nest; Single step through next word.
 7021: 
 7022: @item u
 7023: Unnest; Stop debugging and execute rest of word. If we got to this word
 7024: with nest, continue debugging with the calling word.
 7025: 
 7026: @item d
 7027: Done; Stop debugging and execute rest.
 7028: 
 7029: @item s
 7030: Stopp; Abort immediately.
 7031: 
 7032: @end table
 7033: 
 7034: Debugging large application with this mechanism is very difficult, because
 7035: you have to nest very deep into the program before the interesting part
 7036: begins. This takes a lot of time. 
 7037: 
 7038: To do it more directly put a @code{BREAK:} command into your source code.
 7039: When program execution reaches @code{BREAK:} the single step debugger is
 7040: invoked and you have all the features described above.
 7041: 
 7042: If you have more than one part to debug it is useful to know where the
 7043: program has stopped at the moment. You can do this by the 
 7044: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
 7045: string is typed out when the ``breakpoint'' is reached.
 7046: 
 7047: @node Assembler and Code Words, Threading Words, Programming Tools, Words
 7048: @section Assembler and Code Words
 7049: @cindex assembler
 7050: @cindex code words
 7051: 
 7052: Gforth provides some words for defining primitives (words written in
 7053: machine code), and for defining the the machine-code equivalent of
 7054: @code{DOES>}-based defining words. However, the machine-independent
 7055: nature of Gforth poses a few problems: First of all, Gforth runs on
 7056: several architectures, so it can provide no standard assembler. What's
 7057: worse is that the register allocation not only depends on the processor,
 7058: but also on the @code{gcc} version and options used.
 7059: 
 7060: The words that Gforth offers encapsulate some system dependences (e.g., the
 7061: header structure), so a system-independent assembler may be used in
 7062: Gforth. If you do not have an assembler, you can compile machine code
 7063: directly with @code{,} and @code{c,}.
 7064: 
 7065: doc-assembler
 7066: doc-code
 7067: doc-end-code
 7068: doc-;code
 7069: doc-flush-icache
 7070: 
 7071: If @code{flush-icache} does not work correctly, @code{code} words
 7072: etc. will not work (reliably), either.
 7073: 
 7074: These words are rarely used. Therefore they reside in @code{code.fs},
 7075: which is usually not loaded (except @code{flush-icache}, which is always
 7076: present). You can load them with @code{require code.fs}.
 7077: 
 7078: @cindex registers of the inner interpreter
 7079: In the assembly code you will want to refer to the inner interpreter's
 7080: registers (e.g., the data stack pointer) and you may want to use other
 7081: registers for temporary storage. Unfortunately, the register allocation
 7082: is installation-dependent.
 7083: 
 7084: The easiest solution is to use explicit register declarations
 7085: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
 7086: GNU C Manual}) for all of the inner interpreter's registers: You have to
 7087: compile Gforth with @code{-DFORCE_REG} (configure option
 7088: @code{--enable-force-reg}) and the appropriate declarations must be
 7089: present in the @code{machine.h} file (see @code{mips.h} for an example;
 7090: you can find a full list of all declarable register symbols with
 7091: @code{grep register engine.c}). If you give explicit registers to all
 7092: variables that are declared at the beginning of @code{engine()}, you
 7093: should be able to use the other caller-saved registers for temporary
 7094: storage. Alternatively, you can use the @code{gcc} option
 7095: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
 7096: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
 7097: (however, this restriction on register allocation may slow Gforth
 7098: significantly).
 7099: 
 7100: If this solution is not viable (e.g., because @code{gcc} does not allow
 7101: you to explicitly declare all the registers you need), you have to find
 7102: out by looking at the code where the inner interpreter's registers
 7103: reside and which registers can be used for temporary storage. You can
 7104: get an assembly listing of the engine's code with @code{make engine.s}.
 7105: 
 7106: In any case, it is good practice to abstract your assembly code from the
 7107: actual register allocation. E.g., if the data stack pointer resides in
 7108: register @code{$17}, create an alias for this register called @code{sp},
 7109: and use that in your assembly code.
 7110: 
 7111: @cindex code words, portable
 7112: Another option for implementing normal and defining words efficiently
 7113: is: adding the wanted functionality to the source of Gforth. For normal
 7114: words you just have to edit @file{primitives} (@pxref{Automatic
 7115: Generation}), defining words (equivalent to @code{;CODE} words, for fast
 7116: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
 7117: @file{prims2x.fs}, and possibly @file{cross.fs}.
 7118: 
 7119: 
 7120: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
 7121: @section Threading Words
 7122: @cindex threading words
 7123: 
 7124: @cindex code address
 7125: These words provide access to code addresses and other threading stuff
 7126: in Gforth (and, possibly, other interpretive Forths). It more or less
 7127: abstracts away the differences between direct and indirect threading
 7128: (and, for direct threading, the machine dependences). However, at
 7129: present this wordset is still incomplete. It is also pretty low-level;
 7130: some day it will hopefully be made unnecessary by an internals wordset
 7131: that abstracts implementation details away completely.
 7132: 
 7133: doc-threading-method
 7134: doc->code-address
 7135: doc->does-code
 7136: doc-code-address!
 7137: doc-does-code!
 7138: doc-does-handler!
 7139: doc-/does-handler
 7140: 
 7141: The code addresses produced by various defining words are produced by
 7142: the following words:
 7143: 
 7144: doc-docol:
 7145: doc-docon:
 7146: doc-dovar:
 7147: doc-douser:
 7148: doc-dodefer:
 7149: doc-dofield:
 7150: 
 7151: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
 7152: with @code{>DOES-CODE}. If the word was defined in that way, the value
 7153: returned is different from 0 and identifies the @code{DOES>} used by the
 7154: defining word.
 7155: @comment TODO should that be "identifies the xt of the DOES> ??
 7156: 
 7157: @node Passing Commands to the OS, Miscellaneous Words, Threading Words, Words
 7158: @section Passing Commands to the Operating System
 7159: @cindex operating system - passing commands
 7160: @cindex shell commands
 7161: 
 7162: Gforth allows you to pass an arbitrary string to the host operating
 7163: system shell (if such a thing exists) for execution.
 7164: 
 7165: doc-sh
 7166: doc-system
 7167: doc-$?
 7168: 
 7169: 
 7170: @node Miscellaneous Words,  , Passing Commands to the OS, Words
 7171: @section Miscellaneous Words
 7172: @cindex miscellaneous words
 7173: 
 7174: These section lists the ANS Standard Forth words that are not documented
 7175: elsewhere in this manual. Ultimately, they all need proper homes.
 7176: 
 7177: doc-,
 7178: doc-allocate
 7179: doc-allot
 7180: doc-c,
 7181: doc-here
 7182: doc-ms
 7183: doc-pad
 7184: doc-parse
 7185: doc-postpone
 7186: doc-resize
 7187: doc-restore-input
 7188: doc-save-input
 7189: doc-source
 7190: doc-source-id
 7191: doc-span
 7192: doc-time&date
 7193: doc-unused
 7194: doc-word
 7195: doc-[compile]
 7196: 
 7197: These ANS Standard Forth words are not currently implemented in Gforth
 7198: (see TODO section on dependencies)
 7199: 
 7200: The following ANS Standard Forth words are not currently supported by Gforth 
 7201: (@pxref{ANS conformance})
 7202: 
 7203: @code{EDITOR} 
 7204: @code{EKEY} 
 7205: @code{EKEY>CHAR} 
 7206: @code{EKEY?} 
 7207: @code{EMIT?} 
 7208: @code{FORGET} 
 7209: 
 7210: 
 7211: @c ******************************************************************
 7212: @node Tools, ANS conformance, Words, Top
 7213: @chapter Tools
 7214: 
 7215: @menu
 7216: * ANS Report::                  Report the words used, sorted by wordset.
 7217: @end menu
 7218: 
 7219: See also @ref{Emacs and Gforth}.
 7220: 
 7221: @node ANS Report,  , Tools, Tools
 7222: @section @file{ans-report.fs}: Report the words used, sorted by wordset
 7223: @cindex @file{ans-report.fs}
 7224: @cindex report the words used in your program
 7225: @cindex words used in your program
 7226: 
 7227: If you want to label a Forth program as ANS Forth Program, you must
 7228: document which wordsets the program uses; for extension wordsets, it is
 7229: helpful to list the words the program requires from these wordsets
 7230: (because Forth systems are allowed to provide only some words of them).
 7231: 
 7232: The @file{ans-report.fs} tool makes it easy for you to determine which
 7233: words from which wordset and which non-ANS words your application
 7234: uses. You simply have to include @file{ans-report.fs} before loading the
 7235: program you want to check. After loading your program, you can get the
 7236: report with @code{print-ans-report}. A typical use is to run this as
 7237: batch job like this:
 7238: @example
 7239: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
 7240: @end example
 7241: 
 7242: The output looks like this (for @file{compat/control.fs}):
 7243: @example
 7244: The program uses the following words
 7245: from CORE :
 7246: : POSTPONE THEN ; immediate ?dup IF 0= 
 7247: from BLOCK-EXT :
 7248: \ 
 7249: from FILE :
 7250: ( 
 7251: @end example
 7252: 
 7253: @subsection Caveats
 7254: 
 7255: Note that @file{ans-report.fs} just checks which words are used, not whether
 7256: they are used in an ANS Forth conforming way!
 7257: 
 7258: Some words are defined in several wordsets in the
 7259: standard. @file{ans-report.fs} reports them for only one of the
 7260: wordsets, and not necessarily the one you expect. It depends on usage
 7261: which wordset is the right one to specify. E.g., if you only use the
 7262: compilation semantics of @code{S"}, it is a Core word; if you also use
 7263: its interpretation semantics, it is a File word.
 7264: 
 7265: @c ******************************************************************
 7266: @node ANS conformance, Model, Tools, Top
 7267: @chapter ANS conformance
 7268: @cindex ANS conformance of Gforth
 7269: 
 7270: To the best of our knowledge, Gforth is an
 7271: 
 7272: ANS Forth System
 7273: @itemize @bullet
 7274: @item providing the Core Extensions word set
 7275: @item providing the Block word set
 7276: @item providing the Block Extensions word set
 7277: @item providing the Double-Number word set
 7278: @item providing the Double-Number Extensions word set
 7279: @item providing the Exception word set
 7280: @item providing the Exception Extensions word set
 7281: @item providing the Facility word set
 7282: @item providing @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
 7283: @item providing the File Access word set
 7284: @item providing the File Access Extensions word set
 7285: @item providing the Floating-Point word set
 7286: @item providing the Floating-Point Extensions word set
 7287: @item providing the Locals word set
 7288: @item providing the Locals Extensions word set
 7289: @item providing the Memory-Allocation word set
 7290: @item providing the Memory-Allocation Extensions word set (that one's easy)
 7291: @item providing the Programming-Tools word set
 7292: @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
 7293: @item providing the Search-Order word set
 7294: @item providing the Search-Order Extensions word set
 7295: @item providing the String word set
 7296: @item providing the String Extensions word set (another easy one)
 7297: @end itemize
 7298: 
 7299: @cindex system documentation
 7300: In addition, ANS Forth systems are required to document certain
 7301: implementation choices. This chapter tries to meet these
 7302: requirements. In many cases it gives a way to ask the system for the
 7303: information instead of providing the information directly, in
 7304: particular, if the information depends on the processor, the operating
 7305: system or the installation options chosen, or if they are likely to
 7306: change during the maintenance of Gforth.
 7307: 
 7308: @comment The framework for the rest has been taken from pfe.
 7309: 
 7310: @menu
 7311: * The Core Words::              
 7312: * The optional Block word set::  
 7313: * The optional Double Number word set::  
 7314: * The optional Exception word set::  
 7315: * The optional Facility word set::  
 7316: * The optional File-Access word set::  
 7317: * The optional Floating-Point word set::  
 7318: * The optional Locals word set::  
 7319: * The optional Memory-Allocation word set::  
 7320: * The optional Programming-Tools word set::  
 7321: * The optional Search-Order word set::  
 7322: @end menu
 7323: 
 7324: 
 7325: @c =====================================================================
 7326: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
 7327: @comment  node-name,  next,  previous,  up
 7328: @section The Core Words
 7329: @c =====================================================================
 7330: @cindex core words, system documentation
 7331: @cindex system documentation, core words
 7332: 
 7333: @menu
 7334: * core-idef::                   Implementation Defined Options                   
 7335: * core-ambcond::                Ambiguous Conditions                
 7336: * core-other::                  Other System Documentation                  
 7337: @end menu
 7338: 
 7339: @c ---------------------------------------------------------------------
 7340: @node core-idef, core-ambcond, The Core Words, The Core Words
 7341: @subsection Implementation Defined Options
 7342: @c ---------------------------------------------------------------------
 7343: @cindex core words, implementation-defined options
 7344: @cindex implementation-defined options, core words
 7345: 
 7346: 
 7347: @table @i
 7348: @item (Cell) aligned addresses:
 7349: @cindex cell-aligned addresses
 7350: @cindex aligned addresses
 7351: processor-dependent. Gforth's alignment words perform natural alignment
 7352: (e.g., an address aligned for a datum of size 8 is divisible by
 7353: 8). Unaligned accesses usually result in a @code{-23 THROW}.
 7354: 
 7355: @item @code{EMIT} and non-graphic characters:
 7356: @cindex @code{EMIT} and non-graphic characters
 7357: @cindex non-graphic characters and @code{EMIT}
 7358: The character is output using the C library function (actually, macro)
 7359: @code{putc}.
 7360: 
 7361: @item character editing of @code{ACCEPT} and @code{EXPECT}:
 7362: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
 7363: @cindex editing in @code{ACCEPT} and @code{EXPECT}
 7364: @cindex @code{ACCEPT}, editing
 7365: @cindex @code{EXPECT}, editing
 7366: This is modeled on the GNU readline library (@pxref{Readline
 7367: Interaction, , Command Line Editing, readline, The GNU Readline
 7368: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
 7369: producing a full word completion every time you type it (instead of
 7370: producing the common prefix of all completions).
 7371: 
 7372: @item character set:
 7373: @cindex character set
 7374: The character set of your computer and display device. Gforth is
 7375: 8-bit-clean (but some other component in your system may make trouble).
 7376: 
 7377: @item Character-aligned address requirements:
 7378: @cindex character-aligned address requirements
 7379: installation-dependent. Currently a character is represented by a C
 7380: @code{unsigned char}; in the future we might switch to @code{wchar_t}
 7381: (Comments on that requested).
 7382: 
 7383: @item character-set extensions and matching of names:
 7384: @cindex character-set extensions and matching of names
 7385: @cindex case sensitivity for name lookup
 7386: @cindex name lookup, case sensitivity
 7387: @cindex locale and case sensitivity
 7388: Any character except the ASCII NUL character can be used in a
 7389: name. Matching is case-insensitive (except in @code{TABLE}s). The
 7390: matching is performed using the C function @code{strncasecmp}, whose
 7391: function is probably influenced by the locale. E.g., the @code{C} locale
 7392: does not know about accents and umlauts, so they are matched
 7393: case-sensitively in that locale. For portability reasons it is best to
 7394: write programs such that they work in the @code{C} locale. Then one can
 7395: use libraries written by a Polish programmer (who might use words
 7396: containing ISO Latin-2 encoded characters) and by a French programmer
 7397: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
 7398: funny results for some of the words (which ones, depends on the font you
 7399: are using)). Also, the locale you prefer may not be available in other
 7400: operating systems. Hopefully, Unicode will solve these problems one day.
 7401: 
 7402: @item conditions under which control characters match a space delimiter:
 7403: @cindex space delimiters
 7404: @cindex control characters as delimiters
 7405: If @code{WORD} is called with the space character as a delimiter, all
 7406: white-space characters (as identified by the C macro @code{isspace()})
 7407: are delimiters. @code{PARSE}, on the other hand, treats space like other
 7408: delimiters. @code{PARSE-WORD} treats space like @code{WORD}, but behaves
 7409: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
 7410: interpreter (aka text interpreter) by default, treats all white-space
 7411: characters as delimiters.
 7412: 
 7413: @item format of the control flow stack:
 7414: @cindex control flow stack, format
 7415: The data stack is used as control flow stack. The size of a control flow
 7416: stack item in cells is given by the constant @code{cs-item-size}. At the
 7417: time of this writing, an item consists of a (pointer to a) locals list
 7418: (third), an address in the code (second), and a tag for identifying the
 7419: item (TOS). The following tags are used: @code{defstart},
 7420: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
 7421: @code{scopestart}.
 7422: 
 7423: @item conversion of digits > 35
 7424: @cindex digits > 35
 7425: The characters @code{[\]^_'} are the digits with the decimal value
 7426: 36@minus{}41. There is no way to input many of the larger digits.
 7427: 
 7428: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
 7429: @cindex @code{EXPECT}, display after end of input
 7430: @cindex @code{ACCEPT}, display after end of input
 7431: The cursor is moved to the end of the entered string. If the input is
 7432: terminated using the @kbd{Return} key, a space is typed.
 7433: 
 7434: @item exception abort sequence of @code{ABORT"}:
 7435: @cindex exception abort sequence of @code{ABORT"}
 7436: @cindex @code{ABORT"}, exception abort sequence
 7437: The error string is stored into the variable @code{"error} and a
 7438: @code{-2 throw} is performed.
 7439: 
 7440: @item input line terminator:
 7441: @cindex input line terminator
 7442: @cindex line terminator on input
 7443: @cindex newline charcter on input
 7444: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
 7445: lines. One of these characters is typically produced when you type the
 7446: @kbd{Enter} or @kbd{Return} key.
 7447: 
 7448: @item maximum size of a counted string:
 7449: @cindex maximum size of a counted string
 7450: @cindex counted string, maximum size
 7451: @code{s" /counted-string" environment? drop .}. Currently 255 characters
 7452: on all ports, but this may change.
 7453: 
 7454: @item maximum size of a parsed string:
 7455: @cindex maximum size of a parsed string
 7456: @cindex parsed string, maximum size
 7457: Given by the constant @code{/line}. Currently 255 characters.
 7458: 
 7459: @item maximum size of a definition name, in characters:
 7460: @cindex maximum size of a definition name, in characters
 7461: @cindex name, maximum length
 7462: 31
 7463: 
 7464: @item maximum string length for @code{ENVIRONMENT?}, in characters:
 7465: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
 7466: @cindex @code{ENVIRONMENT?} string length, maximum
 7467: 31
 7468: 
 7469: @item method of selecting the user input device:
 7470: @cindex user input device, method of selecting
 7471: The user input device is the standard input. There is currently no way to
 7472: change it from within Gforth. However, the input can typically be
 7473: redirected in the command line that starts Gforth.
 7474: 
 7475: @item method of selecting the user output device:
 7476: @cindex user output device, method of selecting
 7477: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
 7478: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
 7479: output when the user output device is a terminal, otherwise the output
 7480: is buffered.
 7481: 
 7482: @item methods of dictionary compilation:
 7483: What are we expected to document here?
 7484: 
 7485: @item number of bits in one address unit:
 7486: @cindex number of bits in one address unit
 7487: @cindex address unit, size in bits
 7488: @code{s" address-units-bits" environment? drop .}. 8 in all current
 7489: ports.
 7490: 
 7491: @item number representation and arithmetic:
 7492: @cindex number representation and arithmetic
 7493: Processor-dependent. Binary two's complement on all current ports.
 7494: 
 7495: @item ranges for integer types:
 7496: @cindex ranges for integer types
 7497: @cindex integer types, ranges
 7498: Installation-dependent. Make environmental queries for @code{MAX-N},
 7499: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
 7500: unsigned (and positive) types is 0. The lower bound for signed types on
 7501: two's complement and one's complement machines machines can be computed
 7502: by adding 1 to the upper bound.
 7503: 
 7504: @item read-only data space regions:
 7505: @cindex read-only data space regions
 7506: @cindex data-space, read-only regions
 7507: The whole Forth data space is writable.
 7508: 
 7509: @item size of buffer at @code{WORD}:
 7510: @cindex size of buffer at @code{WORD}
 7511: @cindex @code{WORD} buffer size
 7512: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
 7513: shared with the pictured numeric output string. If overwriting
 7514: @code{PAD} is acceptable, it is as large as the remaining dictionary
 7515: space, although only as much can be sensibly used as fits in a counted
 7516: string.
 7517: 
 7518: @item size of one cell in address units:
 7519: @cindex cell size
 7520: @code{1 cells .}.
 7521: 
 7522: @item size of one character in address units:
 7523: @cindex char size
 7524: @code{1 chars .}. 1 on all current ports.
 7525: 
 7526: @item size of the keyboard terminal buffer:
 7527: @cindex size of the keyboard terminal buffer
 7528: @cindex terminal buffer, size
 7529: Varies. You can determine the size at a specific time using @code{lp@@
 7530: tib - .}. It is shared with the locals stack and TIBs of files that
 7531: include the current file. You can change the amount of space for TIBs
 7532: and locals stack at Gforth startup with the command line option
 7533: @code{-l}.
 7534: 
 7535: @item size of the pictured numeric output buffer:
 7536: @cindex size of the pictured numeric output buffer
 7537: @cindex pictured numeric output buffer, size
 7538: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
 7539: shared with @code{WORD}.
 7540: 
 7541: @item size of the scratch area returned by @code{PAD}:
 7542: @cindex size of the scratch area returned by @code{PAD}
 7543: @cindex @code{PAD} size
 7544: The remainder of dictionary space. @code{unused pad here - - .}.
 7545: 
 7546: @item system case-sensitivity characteristics:
 7547: @cindex case-sensitivity characteristics
 7548: Dictionary searches are case insensitive (except in
 7549: @code{TABLE}s). However, as explained above under @i{character-set
 7550: extensions}, the matching for non-ASCII characters is determined by the
 7551: locale you are using. In the default @code{C} locale all non-ASCII
 7552: characters are matched case-sensitively.
 7553: 
 7554: @item system prompt:
 7555: @cindex system prompt
 7556: @cindex prompt
 7557: @code{ ok} in interpret state, @code{ compiled} in compile state.
 7558: 
 7559: @item division rounding:
 7560: @cindex division rounding
 7561: installation dependent. @code{s" floored" environment? drop .}. We leave
 7562: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
 7563: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
 7564: 
 7565: @item values of @code{STATE} when true:
 7566: @cindex @code{STATE} values
 7567: -1.
 7568: 
 7569: @item values returned after arithmetic overflow:
 7570: On two's complement machines, arithmetic is performed modulo
 7571: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
 7572: arithmetic (with appropriate mapping for signed types). Division by zero
 7573: typically results in a @code{-55 throw} (Floating-point unidentified
 7574: fault), although a @code{-10 throw} (divide by zero) would be more
 7575: appropriate.
 7576: 
 7577: @item whether the current definition can be found after @t{DOES>}:
 7578: @cindex @t{DOES>}, visibility of current definition
 7579: No.
 7580: 
 7581: @end table
 7582: 
 7583: @c ---------------------------------------------------------------------
 7584: @node core-ambcond, core-other, core-idef, The Core Words
 7585: @subsection Ambiguous conditions
 7586: @c ---------------------------------------------------------------------
 7587: @cindex core words, ambiguous conditions
 7588: @cindex ambiguous conditions, core words
 7589: 
 7590: @table @i
 7591: 
 7592: @item a name is neither a word nor a number:
 7593: @cindex name not found
 7594: @cindex Undefined word
 7595: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
 7596: preserves the data and FP stack, so you don't lose more work than
 7597: necessary.
 7598: 
 7599: @item a definition name exceeds the maximum length allowed:
 7600: @cindex Word name too long
 7601: @code{-19 throw} (Word name too long)
 7602: 
 7603: @item addressing a region not inside the various data spaces of the forth system:
 7604: @cindex Invalid memory address
 7605: The stacks, code space and name space are accessible. Machine code space is
 7606: typically readable. Accessing other addresses gives results dependent on
 7607: the operating system. On decent systems: @code{-9 throw} (Invalid memory
 7608: address).
 7609: 
 7610: @item argument type incompatible with parameter:
 7611: @cindex Argument type mismatch
 7612: This is usually not caught. Some words perform checks, e.g., the control
 7613: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
 7614: mismatch).
 7615: 
 7616: @item attempting to obtain the execution token of a word with undefined execution semantics:
 7617: @cindex Interpreting a compile-only word, for @code{'} etc.
 7618: @cindex execution token of words with undefined execution semantics
 7619: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
 7620: get an execution token for @code{compile-only-error} (which performs a
 7621: @code{-14 throw} when executed).
 7622: 
 7623: @item dividing by zero:
 7624: @cindex dividing by zero
 7625: @cindex floating point unidentified fault, integer division
 7626: @cindex divide by zero
 7627: typically results in a @code{-55 throw} (floating point unidentified
 7628: fault), although a @code{-10 throw} (divide by zero) would be more
 7629: appropriate.
 7630: 
 7631: @item insufficient data stack or return stack space:
 7632: @cindex insufficient data stack or return stack space
 7633: @cindex stack overflow
 7634: @cindex Address alignment exception, stack overflow
 7635: @cindex Invalid memory address, stack overflow
 7636: Depending on the operating system, the installation, and the invocation
 7637: of Gforth, this is either checked by the memory management hardware, or
 7638: it is not checked. If it is checked, you typically get a @code{-9 throw}
 7639: (Invalid memory address) as soon as the overflow happens. If it is not
 7640: checked, overflows typically result in mysterious illegal memory accesses,
 7641: producing @code{-9 throw} (Invalid memory address) or @code{-23 throw}
 7642: (Address alignment exception); they might also destroy the internal data
 7643: structure of @code{ALLOCATE} and friends, resulting in various errors in
 7644: these words.
 7645: 
 7646: @item insufficient space for loop control parameters:
 7647: @cindex insufficient space for loop control parameters
 7648: like other return stack overflows.
 7649: 
 7650: @item insufficient space in the dictionary:
 7651: @cindex insufficient space in the dictionary
 7652: @cindex dictionary overflow
 7653: If you try to allot (either directly with @code{allot}, or indirectly
 7654: with @code{,}, @code{create} etc.) more memory than available in the
 7655: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
 7656: to access memory beyond the end of the dictionary, the results are
 7657: similar to stack overflows.
 7658: 
 7659: @item interpreting a word with undefined interpretation semantics:
 7660: @cindex interpreting a word with undefined interpretation semantics
 7661: @cindex Interpreting a compile-only word
 7662: For some words, we have defined interpretation semantics. For the
 7663: others: @code{-14 throw} (Interpreting a compile-only word).
 7664: 
 7665: @item modifying the contents of the input buffer or a string literal:
 7666: @cindex modifying the contents of the input buffer or a string literal
 7667: These are located in writable memory and can be modified.
 7668: 
 7669: @item overflow of the pictured numeric output string:
 7670: @cindex overflow of the pictured numeric output string
 7671: @cindex pictured numeric output string, overflow
 7672: Not checked. Runs into the dictionary and destroys it (at least,
 7673: partially).
 7674: 
 7675: @item parsed string overflow:
 7676: @cindex parsed string overflow
 7677: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
 7678: 
 7679: @item producing a result out of range:
 7680: @cindex result out of range
 7681: On two's complement machines, arithmetic is performed modulo
 7682: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
 7683: arithmetic (with appropriate mapping for signed types). Division by zero
 7684: typically results in a @code{-55 throw} (floatingpoint unidentified
 7685: fault), although a @code{-10 throw} (divide by zero) would be more
 7686: appropriate. @code{convert} and @code{>number} currently overflow
 7687: silently.
 7688: 
 7689: @item reading from an empty data or return stack:
 7690: @cindex stack empty
 7691: @cindex stack underflow
 7692: The data stack is checked by the outer (aka text) interpreter after
 7693: every word executed. If it has underflowed, a @code{-4 throw} (Stack
 7694: underflow) is performed. Apart from that, stacks may be checked or not,
 7695: depending on operating system, installation, and invocation. The
 7696: consequences of stack underflows are similar to the consequences of
 7697: stack overflows. Note that even if the system uses checking (through the
 7698: MMU), your program may have to underflow by a significant number of
 7699: stack items to trigger the reaction (the reason for this is that the
 7700: MMU, and therefore the checking, works with a page-size granularity).
 7701: 
 7702: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
 7703: @cindex unexpected end of the input buffer
 7704: @cindex zero-length string as a name
 7705: @cindex Attempt to use zero-length string as a name
 7706: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
 7707: use zero-length string as a name). Words like @code{'} probably will not
 7708: find what they search. Note that it is possible to create zero-length
 7709: names with @code{nextname} (should it not?).
 7710: 
 7711: @item @code{>IN} greater than input buffer:
 7712: @cindex @code{>IN} greater than input buffer
 7713: The next invocation of a parsing word returns a string with length 0.
 7714: 
 7715: @item @code{RECURSE} appears after @code{DOES>}:
 7716: @cindex @code{RECURSE} appears after @code{DOES>}
 7717: Compiles a recursive call to the defining word, not to the defined word.
 7718: 
 7719: @item argument input source different than current input source for @code{RESTORE-INPUT}:
 7720: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
 7721: @cindex Argument type mismatch, @code{RESTORE-INPUT}
 7722: @cindex @code{RESTORE-INPUT}, Argument type mismatch
 7723: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
 7724: the end of the file was reached), its source-id may be
 7725: reused. Therefore, restoring an input source specification referencing a
 7726: closed file may lead to unpredictable results instead of a @code{-12
 7727: THROW}.
 7728: 
 7729: In the future, Gforth may be able to restore input source specifications
 7730: from other than the current input source.
 7731: 
 7732: @item data space containing definitions gets de-allocated:
 7733: @cindex data space containing definitions gets de-allocated
 7734: Deallocation with @code{allot} is not checked. This typically results in
 7735: memory access faults or execution of illegal instructions.
 7736: 
 7737: @item data space read/write with incorrect alignment:
 7738: @cindex data space read/write with incorrect alignment
 7739: @cindex alignment faults
 7740: @cindex Address alignment exception
 7741: Processor-dependent. Typically results in a @code{-23 throw} (Address
 7742: alignment exception). Under Linux-Intel on a 486 or later processor with
 7743: alignment turned on, incorrect alignment results in a @code{-9 throw}
 7744: (Invalid memory address). There are reportedly some processors with
 7745: alignment restrictions that do not report violations.
 7746: 
 7747: @item data space pointer not properly aligned, @code{,}, @code{C,}:
 7748: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
 7749: Like other alignment errors.
 7750: 
 7751: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
 7752: Like other stack underflows.
 7753: 
 7754: @item loop control parameters not available:
 7755: @cindex loop control parameters not available
 7756: Not checked. The counted loop words simply assume that the top of return
 7757: stack items are loop control parameters and behave accordingly.
 7758: 
 7759: @item most recent definition does not have a name (@code{IMMEDIATE}):
 7760: @cindex most recent definition does not have a name (@code{IMMEDIATE})
 7761: @cindex last word was headerless
 7762: @code{abort" last word was headerless"}.
 7763: 
 7764: @item name not defined by @code{VALUE} used by @code{TO}:
 7765: @cindex name not defined by @code{VALUE} used by @code{TO}
 7766: @cindex @code{TO} on non-@code{VALUE}s
 7767: @cindex Invalid name argument, @code{TO}
 7768: @code{-32 throw} (Invalid name argument) (unless name is a local or was
 7769: defined by @code{CONSTANT}; in the latter case it just changes the constant).
 7770: 
 7771: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
 7772: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
 7773: @cindex Undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
 7774: @code{-13 throw} (Undefined word)
 7775: 
 7776: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
 7777: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
 7778: Gforth behaves as if they were of the same type. I.e., you can predict
 7779: the behaviour by interpreting all parameters as, e.g., signed.
 7780: 
 7781: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
 7782: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
 7783: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
 7784: compilation semantics of @code{TO}.
 7785: 
 7786: @item String longer than a counted string returned by @code{WORD}:
 7787: @cindex String longer than a counted string returned by @code{WORD}
 7788: @cindex @code{WORD}, string overflow
 7789: Not checked. The string will be ok, but the count will, of course,
 7790: contain only the least significant bits of the length.
 7791: 
 7792: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
 7793: @cindex @code{LSHIFT}, large shift counts
 7794: @cindex @code{RSHIFT}, large shift counts
 7795: Processor-dependent. Typical behaviours are returning 0 and using only
 7796: the low bits of the shift count.
 7797: 
 7798: @item word not defined via @code{CREATE}:
 7799: @cindex @code{>BODY} of non-@code{CREATE}d words
 7800: @code{>BODY} produces the PFA of the word no matter how it was defined.
 7801: 
 7802: @cindex @code{DOES>} of non-@code{CREATE}d words
 7803: @code{DOES>} changes the execution semantics of the last defined word no
 7804: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
 7805: @code{CREATE , DOES>}.
 7806: 
 7807: @item words improperly used outside @code{<#} and @code{#>}:
 7808: Not checked. As usual, you can expect memory faults.
 7809: 
 7810: @end table
 7811: 
 7812: 
 7813: @c ---------------------------------------------------------------------
 7814: @node core-other,  , core-ambcond, The Core Words
 7815: @subsection Other system documentation
 7816: @c ---------------------------------------------------------------------
 7817: @cindex other system documentation, core words
 7818: @cindex core words, other system documentation
 7819: 
 7820: @table @i
 7821: @item nonstandard words using @code{PAD}:
 7822: @cindex @code{PAD} use by nonstandard words
 7823: None.
 7824: 
 7825: @item operator's terminal facilities available:
 7826: @cindex operator's terminal facilities available
 7827: After processing the command line, Gforth goes into interactive mode,
 7828: and you can give commands to Gforth interactively. The actual facilities
 7829: available depend on how you invoke Gforth.
 7830: 
 7831: @item program data space available:
 7832: @cindex program data space available
 7833: @cindex data space available
 7834: @code{UNUSED .} gives the remaining dictionary space. The total
 7835: dictionary space can be specified with the @code{-m} switch
 7836: (@pxref{Invoking Gforth}) when Gforth starts up.
 7837: 
 7838: @item return stack space available:
 7839: @cindex return stack space available
 7840: You can compute the total return stack space in cells with
 7841: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
 7842: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
 7843: 
 7844: @item stack space available:
 7845: @cindex stack space available
 7846: You can compute the total data stack space in cells with
 7847: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
 7848: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
 7849: 
 7850: @item system dictionary space required, in address units:
 7851: @cindex system dictionary space required, in address units
 7852: Type @code{here forthstart - .} after startup. At the time of this
 7853: writing, this gives 80080 (bytes) on a 32-bit system.
 7854: @end table
 7855: 
 7856: 
 7857: @c =====================================================================
 7858: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
 7859: @section The optional Block word set
 7860: @c =====================================================================
 7861: @cindex system documentation, block words
 7862: @cindex block words, system documentation
 7863: 
 7864: @menu
 7865: * block-idef::                  Implementation Defined Options
 7866: * block-ambcond::               Ambiguous Conditions               
 7867: * block-other::                 Other System Documentation                 
 7868: @end menu
 7869: 
 7870: 
 7871: @c ---------------------------------------------------------------------
 7872: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
 7873: @subsection Implementation Defined Options
 7874: @c ---------------------------------------------------------------------
 7875: @cindex implementation-defined options, block words
 7876: @cindex block words, implementation-defined options
 7877: 
 7878: @table @i
 7879: @item the format for display by @code{LIST}:
 7880: @cindex @code{LIST} display format
 7881: First the screen number is displayed, then 16 lines of 64 characters,
 7882: each line preceded by the line number.
 7883: 
 7884: @item the length of a line affected by @code{\}:
 7885: @cindex length of a line affected by @code{\}
 7886: @cindex @code{\}, line length in blocks
 7887: 64 characters.
 7888: @end table
 7889: 
 7890: 
 7891: @c ---------------------------------------------------------------------
 7892: @node block-ambcond, block-other, block-idef, The optional Block word set
 7893: @subsection Ambiguous conditions
 7894: @c ---------------------------------------------------------------------
 7895: @cindex block words, ambiguous conditions
 7896: @cindex ambiguous conditions, block words
 7897: 
 7898: @table @i
 7899: @item correct block read was not possible:
 7900: @cindex block read not possible
 7901: Typically results in a @code{throw} of some OS-derived value (between
 7902: -512 and -2048). If the blocks file was just not long enough, blanks are
 7903: supplied for the missing portion.
 7904: 
 7905: @item I/O exception in block transfer:
 7906: @cindex I/O exception in block transfer
 7907: @cindex block transfer, I/O exception
 7908: Typically results in a @code{throw} of some OS-derived value (between
 7909: -512 and -2048).
 7910: 
 7911: @item invalid block number:
 7912: @cindex invalid block number
 7913: @cindex block number invalid
 7914: @code{-35 throw} (Invalid block number)
 7915: 
 7916: @item a program directly alters the contents of @code{BLK}:
 7917: @cindex @code{BLK}, altering @code{BLK}
 7918: The input stream is switched to that other block, at the same
 7919: position. If the storing to @code{BLK} happens when interpreting
 7920: non-block input, the system will get quite confused when the block ends.
 7921: 
 7922: @item no current block buffer for @code{UPDATE}:
 7923: @cindex @code{UPDATE}, no current block buffer
 7924: @code{UPDATE} has no effect.
 7925: 
 7926: @end table
 7927: 
 7928: @c ---------------------------------------------------------------------
 7929: @node block-other,  , block-ambcond, The optional Block word set
 7930: @subsection Other system documentation
 7931: @c ---------------------------------------------------------------------
 7932: @cindex other system documentation, block words
 7933: @cindex block words, other system documentation
 7934: 
 7935: @table @i
 7936: @item any restrictions a multiprogramming system places on the use of buffer addresses:
 7937: No restrictions (yet).
 7938: 
 7939: @item the number of blocks available for source and data:
 7940: depends on your disk space.
 7941: 
 7942: @end table
 7943: 
 7944: 
 7945: @c =====================================================================
 7946: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
 7947: @section The optional Double Number word set
 7948: @c =====================================================================
 7949: @cindex system documentation, double words
 7950: @cindex double words, system documentation
 7951: 
 7952: @menu
 7953: * double-ambcond::              Ambiguous Conditions              
 7954: @end menu
 7955: 
 7956: 
 7957: @c ---------------------------------------------------------------------
 7958: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
 7959: @subsection Ambiguous conditions
 7960: @c ---------------------------------------------------------------------
 7961: @cindex double words, ambiguous conditions
 7962: @cindex ambiguous conditions, double words
 7963: 
 7964: @table @i
 7965: @item @var{d} outside of range of @var{n} in @code{D>S}:
 7966: @cindex @code{D>S}, @var{d} out of range of @var{n} 
 7967: The least significant cell of @var{d} is produced.
 7968: 
 7969: @end table
 7970: 
 7971: 
 7972: @c =====================================================================
 7973: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
 7974: @section The optional Exception word set
 7975: @c =====================================================================
 7976: @cindex system documentation, exception words
 7977: @cindex exception words, system documentation
 7978: 
 7979: @menu
 7980: * exception-idef::              Implementation Defined Options              
 7981: @end menu
 7982: 
 7983: 
 7984: @c ---------------------------------------------------------------------
 7985: @node exception-idef,  , The optional Exception word set, The optional Exception word set
 7986: @subsection Implementation Defined Options
 7987: @c ---------------------------------------------------------------------
 7988: @cindex implementation-defined options, exception words
 7989: @cindex exception words, implementation-defined options
 7990: 
 7991: @table @i
 7992: @item @code{THROW}-codes used in the system:
 7993: @cindex @code{THROW}-codes used in the system
 7994: The codes -256@minus{}-511 are used for reporting signals. The mapping
 7995: from OS signal numbers to throw codes is -256@minus{}@var{signal}. The
 7996: codes -512@minus{}-2047 are used for OS errors (for file and memory
 7997: allocation operations). The mapping from OS error numbers to throw codes
 7998: is -512@minus{}@code{errno}. One side effect of this mapping is that
 7999: undefined OS errors produce a message with a strange number; e.g.,
 8000: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
 8001: @end table
 8002: 
 8003: @c =====================================================================
 8004: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
 8005: @section The optional Facility word set
 8006: @c =====================================================================
 8007: @cindex system documentation, facility words
 8008: @cindex facility words, system documentation
 8009: 
 8010: @menu
 8011: * facility-idef::               Implementation Defined Options               
 8012: * facility-ambcond::            Ambiguous Conditions            
 8013: @end menu
 8014: 
 8015: 
 8016: @c ---------------------------------------------------------------------
 8017: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
 8018: @subsection Implementation Defined Options
 8019: @c ---------------------------------------------------------------------
 8020: @cindex implementation-defined options, facility words
 8021: @cindex facility words, implementation-defined options
 8022: 
 8023: @table @i
 8024: @item encoding of keyboard events (@code{EKEY}):
 8025: @cindex keyboard events, encoding in @code{EKEY}
 8026: @cindex @code{EKEY}, encoding of keyboard events
 8027: Not yet implemented.
 8028: 
 8029: @item duration of a system clock tick:
 8030: @cindex duration of a system clock tick
 8031: @cindex clock tick duration
 8032: System dependent. With respect to @code{MS}, the time is specified in
 8033: microseconds. How well the OS and the hardware implement this, is
 8034: another question.
 8035: 
 8036: @item repeatability to be expected from the execution of @code{MS}:
 8037: @cindex repeatability to be expected from the execution of @code{MS}
 8038: @cindex @code{MS}, repeatability to be expected
 8039: System dependent. On Unix, a lot depends on load. If the system is
 8040: lightly loaded, and the delay is short enough that Gforth does not get
 8041: swapped out, the performance should be acceptable. Under MS-DOS and
 8042: other single-tasking systems, it should be good.
 8043: 
 8044: @end table
 8045: 
 8046: 
 8047: @c ---------------------------------------------------------------------
 8048: @node facility-ambcond,  , facility-idef, The optional Facility word set
 8049: @subsection Ambiguous conditions
 8050: @c ---------------------------------------------------------------------
 8051: @cindex facility words, ambiguous conditions
 8052: @cindex ambiguous conditions, facility words
 8053: 
 8054: @table @i
 8055: @item @code{AT-XY} can't be performed on user output device:
 8056: @cindex @code{AT-XY} can't be performed on user output device
 8057: Largely terminal dependent. No range checks are done on the arguments.
 8058: No errors are reported. You may see some garbage appearing, you may see
 8059: simply nothing happen.
 8060: 
 8061: @end table
 8062: 
 8063: 
 8064: @c =====================================================================
 8065: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
 8066: @section The optional File-Access word set
 8067: @c =====================================================================
 8068: @cindex system documentation, file words
 8069: @cindex file words, system documentation
 8070: 
 8071: @menu
 8072: * file-idef::                   Implementation Defined Options
 8073: * file-ambcond::                Ambiguous Conditions                
 8074: @end menu
 8075: 
 8076: @c ---------------------------------------------------------------------
 8077: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
 8078: @subsection Implementation Defined Options
 8079: @c ---------------------------------------------------------------------
 8080: @cindex implementation-defined options, file words
 8081: @cindex file words, implementation-defined options
 8082: 
 8083: @table @i
 8084: @item file access methods used:
 8085: @cindex file access methods used
 8086: @code{R/O}, @code{R/W} and @code{BIN} work as you would
 8087: expect. @code{W/O} translates into the C file opening mode @code{w} (or
 8088: @code{wb}): The file is cleared, if it exists, and created, if it does
 8089: not (with both @code{open-file} and @code{create-file}).  Under Unix
 8090: @code{create-file} creates a file with 666 permissions modified by your
 8091: umask.
 8092: 
 8093: @item file exceptions:
 8094: @cindex file exceptions
 8095: The file words do not raise exceptions (except, perhaps, memory access
 8096: faults when you pass illegal addresses or file-ids).
 8097: 
 8098: @item file line terminator:
 8099: @cindex file line terminator
 8100: System-dependent. Gforth uses C's newline character as line
 8101: terminator. What the actual character code(s) of this are is
 8102: system-dependent.
 8103: 
 8104: @item file name format:
 8105: @cindex file name format
 8106: System dependent. Gforth just uses the file name format of your OS.
 8107: 
 8108: @item information returned by @code{FILE-STATUS}:
 8109: @cindex @code{FILE-STATUS}, returned information
 8110: @code{FILE-STATUS} returns the most powerful file access mode allowed
 8111: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
 8112: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
 8113: along with the returned mode.
 8114: 
 8115: @item input file state after an exception when including source:
 8116: @cindex exception when including source
 8117: All files that are left via the exception are closed.
 8118: 
 8119: @item @var{ior} values and meaning:
 8120: @cindex @var{ior} values and meaning
 8121: The @var{ior}s returned by the file and memory allocation words are
 8122: intended as throw codes. They typically are in the range
 8123: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
 8124: @var{ior}s is -512@minus{}@var{errno}.
 8125: 
 8126: @item maximum depth of file input nesting:
 8127: @cindex maximum depth of file input nesting
 8128: @cindex file input nesting, maximum depth
 8129: limited by the amount of return stack, locals/TIB stack, and the number
 8130: of open files available. This should not give you troubles.
 8131: 
 8132: @item maximum size of input line:
 8133: @cindex maximum size of input line
 8134: @cindex input line size, maximum
 8135: @code{/line}. Currently 255.
 8136: 
 8137: @item methods of mapping block ranges to files:
 8138: @cindex mapping block ranges to files
 8139: @cindex files containing blocks
 8140: @cindex blocks in files
 8141: By default, blocks are accessed in the file @file{blocks.fb} in the
 8142: current working directory. The file can be switched with @code{USE}.
 8143: 
 8144: @item number of string buffers provided by @code{S"}:
 8145: @cindex @code{S"}, number of string buffers
 8146: 1
 8147: 
 8148: @item size of string buffer used by @code{S"}:
 8149: @cindex @code{S"}, size of string buffer
 8150: @code{/line}. currently 255.
 8151: 
 8152: @end table
 8153: 
 8154: @c ---------------------------------------------------------------------
 8155: @node file-ambcond,  , file-idef, The optional File-Access word set
 8156: @subsection Ambiguous conditions
 8157: @c ---------------------------------------------------------------------
 8158: @cindex file words, ambiguous conditions
 8159: @cindex ambiguous conditions, file words
 8160: 
 8161: @table @i
 8162: @item attempting to position a file outside its boundaries:
 8163: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
 8164: @code{REPOSITION-FILE} is performed as usual: Afterwards,
 8165: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
 8166: 
 8167: @item attempting to read from file positions not yet written:
 8168: @cindex reading from file positions not yet written
 8169: End-of-file, i.e., zero characters are read and no error is reported.
 8170: 
 8171: @item @var{file-id} is invalid (@code{INCLUDE-FILE}):
 8172: @cindex @code{INCLUDE-FILE}, @var{file-id} is invalid 
 8173: An appropriate exception may be thrown, but a memory fault or other
 8174: problem is more probable.
 8175: 
 8176: @item I/O exception reading or closing @var{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
 8177: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @var{file-id}
 8178: @cindex @code{INCLUDED}, I/O exception reading or closing @var{file-id}
 8179: The @var{ior} produced by the operation, that discovered the problem, is
 8180: thrown.
 8181: 
 8182: @item named file cannot be opened (@code{INCLUDED}):
 8183: @cindex @code{INCLUDED}, named file cannot be opened
 8184: The @var{ior} produced by @code{open-file} is thrown.
 8185: 
 8186: @item requesting an unmapped block number:
 8187: @cindex unmapped block numbers
 8188: There are no unmapped legal block numbers. On some operating systems,
 8189: writing a block with a large number may overflow the file system and
 8190: have an error message as consequence.
 8191: 
 8192: @item using @code{source-id} when @code{blk} is non-zero:
 8193: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
 8194: @code{source-id} performs its function. Typically it will give the id of
 8195: the source which loaded the block. (Better ideas?)
 8196: 
 8197: @end table
 8198: 
 8199: 
 8200: @c =====================================================================
 8201: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
 8202: @section The optional Floating-Point word set
 8203: @c =====================================================================
 8204: @cindex system documentation, floating-point words
 8205: @cindex floating-point words, system documentation
 8206: 
 8207: @menu
 8208: * floating-idef::               Implementation Defined Options
 8209: * floating-ambcond::            Ambiguous Conditions            
 8210: @end menu
 8211: 
 8212: 
 8213: @c ---------------------------------------------------------------------
 8214: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
 8215: @subsection Implementation Defined Options
 8216: @c ---------------------------------------------------------------------
 8217: @cindex implementation-defined options, floating-point words
 8218: @cindex floating-point words, implementation-defined options
 8219: 
 8220: @table @i
 8221: @item format and range of floating point numbers:
 8222: @cindex format and range of floating point numbers
 8223: @cindex floating point numbers, format and range
 8224: System-dependent; the @code{double} type of C.
 8225: 
 8226: @item results of @code{REPRESENT} when @var{float} is out of range:
 8227: @cindex  @code{REPRESENT}, results when @var{float} is out of range
 8228: System dependent; @code{REPRESENT} is implemented using the C library
 8229: function @code{ecvt()} and inherits its behaviour in this respect.
 8230: 
 8231: @item rounding or truncation of floating-point numbers:
 8232: @cindex rounding of floating-point numbers
 8233: @cindex truncation of floating-point numbers
 8234: @cindex floating-point numbers, rounding or truncation
 8235: System dependent; the rounding behaviour is inherited from the hosting C
 8236: compiler. IEEE-FP-based (i.e., most) systems by default round to
 8237: nearest, and break ties by rounding to even (i.e., such that the last
 8238: bit of the mantissa is 0).
 8239: 
 8240: @item size of floating-point stack:
 8241: @cindex floating-point stack size
 8242: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
 8243: the floating-point stack (in floats). You can specify this on startup
 8244: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
 8245: 
 8246: @item width of floating-point stack:
 8247: @cindex floating-point stack width 
 8248: @code{1 floats}.
 8249: 
 8250: @end table
 8251: 
 8252: 
 8253: @c ---------------------------------------------------------------------
 8254: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
 8255: @subsection Ambiguous conditions
 8256: @c ---------------------------------------------------------------------
 8257: @cindex floating-point words, ambiguous conditions
 8258: @cindex ambiguous conditions, floating-point words
 8259: 
 8260: @table @i
 8261: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
 8262: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
 8263: System-dependent. Typically results in a @code{-23 THROW} like other
 8264: alignment violations.
 8265: 
 8266: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
 8267: @cindex @code{f@@} used with an address that is not float aligned
 8268: @cindex @code{f!} used with an address that is not float aligned
 8269: System-dependent. Typically results in a @code{-23 THROW} like other
 8270: alignment violations.
 8271: 
 8272: @item floating-point result out of range:
 8273: @cindex floating-point result out of range
 8274: System-dependent. Can result in a @code{-55 THROW} (Floating-point
 8275: unidentified fault), or can produce a special value representing, e.g.,
 8276: Infinity.
 8277: 
 8278: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
 8279: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
 8280: System-dependent. Typically results in an alignment fault like other
 8281: alignment violations.
 8282: 
 8283: @item @code{BASE} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
 8284: @cindex @code{BASE} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
 8285: The floating-point number is converted into decimal nonetheless.
 8286: 
 8287: @item Both arguments are equal to zero (@code{FATAN2}):
 8288: @cindex @code{FATAN2}, both arguments are equal to zero
 8289: System-dependent. @code{FATAN2} is implemented using the C library
 8290: function @code{atan2()}.
 8291: 
 8292: @item Using @code{FTAN} on an argument @var{r1} where cos(@var{r1}) is zero:
 8293: @cindex @code{FTAN} on an argument @var{r1} where cos(@var{r1}) is zero
 8294: System-dependent. Anyway, typically the cos of @var{r1} will not be zero
 8295: because of small errors and the tan will be a very large (or very small)
 8296: but finite number.
 8297: 
 8298: @item @var{d} cannot be presented precisely as a float in @code{D>F}:
 8299: @cindex @code{D>F}, @var{d} cannot be presented precisely as a float
 8300: The result is rounded to the nearest float.
 8301: 
 8302: @item dividing by zero:
 8303: @cindex dividing by zero, floating-point
 8304: @cindex floating-point dividing by zero
 8305: @cindex floating-point unidentified fault, FP divide-by-zero
 8306: @code{-55 throw} (Floating-point unidentified fault)
 8307: 
 8308: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
 8309: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
 8310: System dependent. On IEEE-FP based systems the number is converted into
 8311: an infinity.
 8312: 
 8313: @item @var{float}<1 (@code{FACOSH}):
 8314: @cindex @code{FACOSH}, @var{float}<1
 8315: @cindex floating-point unidentified fault, @code{FACOSH}
 8316: @code{-55 throw} (Floating-point unidentified fault)
 8317: 
 8318: @item @var{float}=<-1 (@code{FLNP1}):
 8319: @cindex @code{FLNP1}, @var{float}=<-1
 8320: @cindex floating-point unidentified fault, @code{FLNP1}
 8321: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
 8322: negative infinity is typically produced for @var{float}=-1.
 8323: 
 8324: @item @var{float}=<0 (@code{FLN}, @code{FLOG}):
 8325: @cindex @code{FLN}, @var{float}=<0
 8326: @cindex @code{FLOG}, @var{float}=<0
 8327: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
 8328: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
 8329: negative infinity is typically produced for @var{float}=0.
 8330: 
 8331: @item @var{float}<0 (@code{FASINH}, @code{FSQRT}):
 8332: @cindex @code{FASINH}, @var{float}<0
 8333: @cindex @code{FSQRT}, @var{float}<0
 8334: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
 8335: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
 8336: produces values for these inputs on my Linux box (Bug in the C library?)
 8337: 
 8338: @item |@var{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
 8339: @cindex @code{FACOS}, |@var{float}|>1
 8340: @cindex @code{FASIN}, |@var{float}|>1
 8341: @cindex @code{FATANH}, |@var{float}|>1
 8342: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
 8343: @code{-55 throw} (Floating-point unidentified fault).
 8344: 
 8345: @item integer part of float cannot be represented by @var{d} in @code{F>D}:
 8346: @cindex @code{F>D}, integer part of float cannot be represented by @var{d}
 8347: @cindex floating-point unidentified fault, @code{F>D}
 8348: @code{-55 throw} (Floating-point unidentified fault).
 8349: 
 8350: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
 8351: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
 8352: This does not happen.
 8353: @end table
 8354: 
 8355: @c =====================================================================
 8356: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
 8357: @section The optional Locals word set
 8358: @c =====================================================================
 8359: @cindex system documentation, locals words
 8360: @cindex locals words, system documentation
 8361: 
 8362: @menu
 8363: * locals-idef::                 Implementation Defined Options                 
 8364: * locals-ambcond::              Ambiguous Conditions              
 8365: @end menu
 8366: 
 8367: 
 8368: @c ---------------------------------------------------------------------
 8369: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
 8370: @subsection Implementation Defined Options
 8371: @c ---------------------------------------------------------------------
 8372: @cindex implementation-defined options, locals words
 8373: @cindex locals words, implementation-defined options
 8374: 
 8375: @table @i
 8376: @item maximum number of locals in a definition:
 8377: @cindex maximum number of locals in a definition
 8378: @cindex locals, maximum number in a definition
 8379: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
 8380: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
 8381: characters. The number of locals in a definition is bounded by the size
 8382: of locals-buffer, which contains the names of the locals.
 8383: 
 8384: @end table
 8385: 
 8386: 
 8387: @c ---------------------------------------------------------------------
 8388: @node locals-ambcond,  , locals-idef, The optional Locals word set
 8389: @subsection Ambiguous conditions
 8390: @c ---------------------------------------------------------------------
 8391: @cindex locals words, ambiguous conditions
 8392: @cindex ambiguous conditions, locals words
 8393: 
 8394: @table @i
 8395: @item executing a named local in interpretation state:
 8396: @cindex local in interpretation state
 8397: @cindex Interpreting a compile-only word, for a local
 8398: Locals have no interpretation semantics. If you try to perform the
 8399: interpretation semantics, you will get a @code{-14 throw} somewhere
 8400: (Interpreting a compile-only word). If you perform the compilation
 8401: semantics, the locals access will be compiled (irrespective of state).
 8402: 
 8403: @item @var{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
 8404: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
 8405: @cindex @code{TO} on non-@code{VALUE}s and non-locals
 8406: @cindex Invalid name argument, @code{TO}
 8407: @code{-32 throw} (Invalid name argument)
 8408: 
 8409: @end table
 8410: 
 8411: 
 8412: @c =====================================================================
 8413: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
 8414: @section The optional Memory-Allocation word set
 8415: @c =====================================================================
 8416: @cindex system documentation, memory-allocation words
 8417: @cindex memory-allocation words, system documentation
 8418: 
 8419: @menu
 8420: * memory-idef::                 Implementation Defined Options                 
 8421: @end menu
 8422: 
 8423: 
 8424: @c ---------------------------------------------------------------------
 8425: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
 8426: @subsection Implementation Defined Options
 8427: @c ---------------------------------------------------------------------
 8428: @cindex implementation-defined options, memory-allocation words
 8429: @cindex memory-allocation words, implementation-defined options
 8430: 
 8431: @table @i
 8432: @item values and meaning of @var{ior}:
 8433: @cindex  @var{ior} values and meaning
 8434: The @var{ior}s returned by the file and memory allocation words are
 8435: intended as throw codes. They typically are in the range
 8436: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
 8437: @var{ior}s is -512@minus{}@var{errno}.
 8438: 
 8439: @end table
 8440: 
 8441: @c =====================================================================
 8442: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
 8443: @section The optional Programming-Tools word set
 8444: @c =====================================================================
 8445: @cindex system documentation, programming-tools words
 8446: @cindex programming-tools words, system documentation
 8447: 
 8448: @menu
 8449: * programming-idef::            Implementation Defined Options            
 8450: * programming-ambcond::         Ambiguous Conditions         
 8451: @end menu
 8452: 
 8453: 
 8454: @c ---------------------------------------------------------------------
 8455: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
 8456: @subsection Implementation Defined Options
 8457: @c ---------------------------------------------------------------------
 8458: @cindex implementation-defined options, programming-tools words
 8459: @cindex programming-tools words, implementation-defined options
 8460: 
 8461: @table @i
 8462: @item ending sequence for input following @code{;CODE} and @code{CODE}:
 8463: @cindex @code{;CODE} ending sequence
 8464: @cindex @code{CODE} ending sequence
 8465: @code{END-CODE}
 8466: 
 8467: @item manner of processing input following @code{;CODE} and @code{CODE}:
 8468: @cindex @code{;CODE}, processing input
 8469: @cindex @code{CODE}, processing input
 8470: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
 8471: the input is processed by the text interpreter, (starting) in interpret
 8472: state.
 8473: 
 8474: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
 8475: @cindex @code{ASSEMBLER}, search order capability
 8476: The ANS Forth search order word set.
 8477: 
 8478: @item source and format of display by @code{SEE}:
 8479: @cindex @code{SEE}, source and format of output
 8480: The source for @code{see} is the intermediate code used by the inner
 8481: interpreter.  The current @code{see} tries to output Forth source code
 8482: as well as possible.
 8483: 
 8484: @end table
 8485: 
 8486: @c ---------------------------------------------------------------------
 8487: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
 8488: @subsection Ambiguous conditions
 8489: @c ---------------------------------------------------------------------
 8490: @cindex programming-tools words, ambiguous conditions
 8491: @cindex ambiguous conditions, programming-tools words
 8492: 
 8493: @table @i
 8494: 
 8495: @item deleting the compilation word list (@code{FORGET}):
 8496: @cindex @code{FORGET}, deleting the compilation word list
 8497: Not implemented (yet).
 8498: 
 8499: @item fewer than @var{u}+1 items on the control flow stack (@code{CS-PICK}, @code{CS-ROLL}):
 8500: @cindex @code{CS-PICK}, fewer than @var{u}+1 items on the control flow stack
 8501: @cindex @code{CS-ROLL}, fewer than @var{u}+1 items on the control flow stack
 8502: @cindex control-flow stack underflow
 8503: This typically results in an @code{abort"} with a descriptive error
 8504: message (may change into a @code{-22 throw} (Control structure mismatch)
 8505: in the future). You may also get a memory access error. If you are
 8506: unlucky, this ambiguous condition is not caught.
 8507: 
 8508: @item @var{name} can't be found (@code{FORGET}):
 8509: @cindex @code{FORGET}, @var{name} can't be found
 8510: Not implemented (yet).
 8511: 
 8512: @item @var{name} not defined via @code{CREATE}:
 8513: @cindex @code{;CODE}, @var{name} not defined via @code{CREATE}
 8514: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
 8515: the execution semantics of the last defined word no matter how it was
 8516: defined.
 8517: 
 8518: @item @code{POSTPONE} applied to @code{[IF]}:
 8519: @cindex @code{POSTPONE} applied to @code{[IF]}
 8520: @cindex @code{[IF]} and @code{POSTPONE}
 8521: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
 8522: equivalent to @code{[IF]}.
 8523: 
 8524: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
 8525: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
 8526: Continue in the same state of conditional compilation in the next outer
 8527: input source. Currently there is no warning to the user about this.
 8528: 
 8529: @item removing a needed definition (@code{FORGET}):
 8530: @cindex @code{FORGET}, removing a needed definition
 8531: Not implemented (yet).
 8532: 
 8533: @end table
 8534: 
 8535: 
 8536: @c =====================================================================
 8537: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
 8538: @section The optional Search-Order word set
 8539: @c =====================================================================
 8540: @cindex system documentation, search-order words
 8541: @cindex search-order words, system documentation
 8542: 
 8543: @menu
 8544: * search-idef::                 Implementation Defined Options                 
 8545: * search-ambcond::              Ambiguous Conditions              
 8546: @end menu
 8547: 
 8548: 
 8549: @c ---------------------------------------------------------------------
 8550: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
 8551: @subsection Implementation Defined Options
 8552: @c ---------------------------------------------------------------------
 8553: @cindex implementation-defined options, search-order words
 8554: @cindex search-order words, implementation-defined options
 8555: 
 8556: @table @i
 8557: @item maximum number of word lists in search order:
 8558: @cindex maximum number of word lists in search order
 8559: @cindex search order, maximum depth
 8560: @code{s" wordlists" environment? drop .}. Currently 16.
 8561: 
 8562: @item minimum search order:
 8563: @cindex minimum search order
 8564: @cindex search order, minimum
 8565: @code{root root}.
 8566: 
 8567: @end table
 8568: 
 8569: @c ---------------------------------------------------------------------
 8570: @node search-ambcond,  , search-idef, The optional Search-Order word set
 8571: @subsection Ambiguous conditions
 8572: @c ---------------------------------------------------------------------
 8573: @cindex search-order words, ambiguous conditions
 8574: @cindex ambiguous conditions, search-order words
 8575: 
 8576: @table @i
 8577: @item changing the compilation word list (during compilation):
 8578: @cindex changing the compilation word list (during compilation)
 8579: @cindex compilation word list, change before definition ends
 8580: The word is entered into the word list that was the compilation word list
 8581: at the start of the definition. Any changes to the name field (e.g.,
 8582: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
 8583: are applied to the latest defined word (as reported by @code{last} or
 8584: @code{lastxt}), if possible, irrespective of the compilation word list.
 8585: 
 8586: @item search order empty (@code{previous}):
 8587: @cindex @code{previous}, search order empty
 8588: @cindex Vocstack empty, @code{previous}
 8589: @code{abort" Vocstack empty"}.
 8590: 
 8591: @item too many word lists in search order (@code{also}):
 8592: @cindex @code{also}, too many word lists in search order
 8593: @cindex Vocstack full, @code{also}
 8594: @code{abort" Vocstack full"}.
 8595: 
 8596: @end table
 8597: 
 8598: @c ***************************************************************
 8599: @node Model, Integrating Gforth, ANS conformance, Top
 8600: @chapter Model
 8601: 
 8602: This chapter has yet to be written. It will contain information, on
 8603: which internal structures you can rely.
 8604: 
 8605: @c ***************************************************************
 8606: @node Integrating Gforth, Emacs and Gforth, Model, Top
 8607: @chapter Integrating Gforth into C programs
 8608: 
 8609: This is not yet implemented.
 8610: 
 8611: Several people like to use Forth as scripting language for applications
 8612: that are otherwise written in C, C++, or some other language.
 8613: 
 8614: The Forth system ATLAST provides facilities for embedding it into
 8615: applications; unfortunately it has several disadvantages: most
 8616: importantly, it is not based on ANS Forth, and it is apparently dead
 8617: (i.e., not developed further and not supported). The facilities
 8618: provided by Gforth in this area are inspired by ATLAST's facilities, so
 8619: making the switch should not be hard.
 8620: 
 8621: We also tried to design the interface such that it can easily be
 8622: implemented by other Forth systems, so that we may one day arrive at a
 8623: standardized interface. Such a standard interface would allow you to
 8624: replace the Forth system without having to rewrite C code.
 8625: 
 8626: You embed the Gforth interpreter by linking with the library
 8627: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
 8628: global symbols in this library that belong to the interface, have the
 8629: prefix @code{forth_}. (Global symbols that are used internally have the
 8630: prefix @code{gforth_}).
 8631: 
 8632: You can include the declarations of Forth types and the functions and
 8633: variables of the interface with @code{#include <forth.h>}.
 8634: 
 8635: Types.
 8636: 
 8637: Variables.
 8638: 
 8639: Data and FP Stack pointer. Area sizes.
 8640: 
 8641: functions.
 8642: 
 8643: forth_init(imagefile)
 8644: forth_evaluate(string) exceptions?
 8645: forth_goto(address) (or forth_execute(xt)?)
 8646: forth_continue() (a corountining mechanism)
 8647: 
 8648: Adding primitives.
 8649: 
 8650: No checking.
 8651: 
 8652: Signals?
 8653: 
 8654: Accessing the Stacks
 8655: 
 8656: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
 8657: @chapter Emacs and Gforth
 8658: @cindex Emacs and Gforth
 8659: 
 8660: @cindex @file{gforth.el}
 8661: @cindex @file{forth.el}
 8662: @cindex Rydqvist, Goran
 8663: @cindex comment editing commands
 8664: @cindex @code{\}, editing with Emacs
 8665: @cindex debug tracer editing commands
 8666: @cindex @code{~~}, removal with Emacs
 8667: @cindex Forth mode in Emacs
 8668: Gforth comes with @file{gforth.el}, an improved version of
 8669: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
 8670: improvements are a better (but still not perfect) handling of
 8671: indentation. I have also added comment paragraph filling (@kbd{M-q}),
 8672: commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) regions and
 8673: removing debugging tracers (@kbd{C-x ~}, @pxref{Debugging}). I left the
 8674: stuff I do not use alone, even though some of it only makes sense for
 8675: TILE. To get a description of these features, enter Forth mode and type
 8676: @kbd{C-h m}.
 8677: 
 8678: @cindex source location of error or debugging output in Emacs
 8679: @cindex error output, finding the source location in Emacs
 8680: @cindex debugging output, finding the source location in Emacs
 8681: In addition, Gforth supports Emacs quite well: The source code locations
 8682: given in error messages, debugging output (from @code{~~}) and failed
 8683: assertion messages are in the right format for Emacs' compilation mode
 8684: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
 8685: Manual}) so the source location corresponding to an error or other
 8686: message is only a few keystrokes away (@kbd{C-x `} for the next error,
 8687: @kbd{C-c C-c} for the error under the cursor).
 8688: 
 8689: @cindex @file{TAGS} file
 8690: @cindex @file{etags.fs}
 8691: @cindex viewing the source of a word in Emacs
 8692: Also, if you @code{include} @file{etags.fs}, a new @file{TAGS} file
 8693: (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) will be produced that
 8694: contains the definitions of all words defined afterwards. You can then
 8695: find the source for a word using @kbd{M-.}. Note that emacs can use
 8696: several tags files at the same time (e.g., one for the Gforth sources
 8697: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
 8698: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
 8699: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
 8700: @file{/usr/local/share/gforth/0.2.0/TAGS}).
 8701: 
 8702: @cindex @file{.emacs}
 8703: To get all these benefits, add the following lines to your @file{.emacs}
 8704: file:
 8705: 
 8706: @example
 8707: (autoload 'forth-mode "gforth.el")
 8708: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
 8709: @end example
 8710: 
 8711: @node Image Files, Engine, Emacs and Gforth, Top
 8712: @chapter Image Files
 8713: @cindex image files
 8714: @cindex @code{.fi} files
 8715: @cindex precompiled Forth code
 8716: @cindex dictionary in persistent form
 8717: @cindex persistent form of dictionary
 8718: 
 8719: An image file is a file containing an image of the Forth dictionary,
 8720: i.e., compiled Forth code and data residing in the dictionary.  By
 8721: convention, we use the extension @code{.fi} for image files.
 8722: 
 8723: @menu
 8724: * Image Licensing Issues::      Distribution terms for images.
 8725: * Image File Background::       Why have image files?
 8726: * Non-Relocatable Image Files::  don't always work.
 8727: * Data-Relocatable Image Files::  are better.
 8728: * Fully Relocatable Image Files::  better yet.
 8729: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
 8730: * Running Image Files::         @code{gforth -i @var{file}} or @var{file}.
 8731: * Modifying the Startup Sequence::  and turnkey applications.
 8732: @end menu
 8733: 
 8734: @node Image Licensing Issues, Image File Background, Image Files, Image Files
 8735: @section Image Licensing Issues
 8736: @cindex license for images
 8737: @cindex image license
 8738: 
 8739: An image created with @code{gforthmi} (@pxref{gforthmi}) or
 8740: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
 8741: original image; i.e., according to copyright law it is a derived work of
 8742: the original image.
 8743: 
 8744: Since Gforth is distributed under the GNU GPL, the newly created image
 8745: falls under the GNU GPL, too. In particular, this means that if you
 8746: distribute the image, you have to make all of the sources for the image
 8747: available, including those you wrote.  For details see @ref{License, ,
 8748: GNU General Public License (Section 3)}.
 8749: 
 8750: If you create an image with @code{cross} (@pxref{cross.fs}), the image
 8751: contains only code compiled from the sources you gave it; if none of
 8752: these sources is under the GPL, the terms discussed above do not apply
 8753: to the image. However, if your image needs an engine (a gforth binary)
 8754: that is under the GPL, you should make sure that you distribute both in
 8755: a way that is at most a @emph{mere aggregation}, if you don't want the
 8756: terms of the GPL to apply to the image.
 8757: 
 8758: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
 8759: @section Image File Background
 8760: @cindex image file background
 8761: 
 8762: Our Forth system consists not only of primitives, but also of
 8763: definitions written in Forth. Since the Forth compiler itself belongs to
 8764: those definitions, it is not possible to start the system with the
 8765: primitives and the Forth source alone. Therefore we provide the Forth
 8766: code as an image file in nearly executable form. At the start of the
 8767: system a C routine loads the image file into memory, optionally
 8768: relocates the addresses, then sets up the memory (stacks etc.) according
 8769: to information in the image file, and starts executing Forth code.
 8770: 
 8771: The image file variants represent different compromises between the
 8772: goals of making it easy to generate image files and making them
 8773: portable.
 8774: 
 8775: @cindex relocation at run-time
 8776: Win32Forth 3.4 and Mitch Bradleys @code{cforth} use relocation at
 8777: run-time. This avoids many of the complications discussed below (image
 8778: files are data relocatable without further ado), but costs performance
 8779: (one addition per memory access).
 8780: 
 8781: @cindex relocation at load-time
 8782: By contrast, our loader performs relocation at image load time. The
 8783: loader also has to replace tokens standing for primitive calls with the
 8784: appropriate code-field addresses (or code addresses in the case of
 8785: direct threading).
 8786: 
 8787: There are three kinds of image files, with different degrees of
 8788: relocatability: non-relocatable, data-relocatable, and fully relocatable
 8789: image files.
 8790: 
 8791: @cindex image file loader
 8792: @cindex relocating loader
 8793: @cindex loader for image files
 8794: These image file variants have several restrictions in common; they are
 8795: caused by the design of the image file loader:
 8796: 
 8797: @itemize @bullet
 8798: @item
 8799: There is only one segment; in particular, this means, that an image file
 8800: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
 8801: them). And the contents of the stacks are not represented, either.
 8802: 
 8803: @item
 8804: The only kinds of relocation supported are: adding the same offset to
 8805: all cells that represent data addresses; and replacing special tokens
 8806: with code addresses or with pieces of machine code.
 8807: 
 8808: If any complex computations involving addresses are performed, the
 8809: results cannot be represented in the image file. Several applications that
 8810: use such computations come to mind:
 8811: @itemize @minus
 8812: @item
 8813: Hashing addresses (or data structures which contain addresses) for table
 8814: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
 8815: purpose, you will have no problem, because the hash tables are
 8816: recomputed automatically when the system is started. If you use your own
 8817: hash tables, you will have to do something similar.
 8818: 
 8819: @item
 8820: There's a cute implementation of doubly-linked lists that uses
 8821: @code{XOR}ed addresses. You could represent such lists as singly-linked
 8822: in the image file, and restore the doubly-linked representation on
 8823: startup.@footnote{In my opinion, though, you should think thrice before
 8824: using a doubly-linked list (whatever implementation).}
 8825: 
 8826: @item
 8827: The code addresses of run-time routines like @code{docol:} cannot be
 8828: represented in the image file (because their tokens would be replaced by
 8829: machine code in direct threaded implementations). As a workaround,
 8830: compute these addresses at run-time with @code{>code-address} from the
 8831: executions tokens of appropriate words (see the definitions of
 8832: @code{docol:} and friends in @file{kernel.fs}).
 8833: 
 8834: @item
 8835: On many architectures addresses are represented in machine code in some
 8836: shifted or mangled form. You cannot put @code{CODE} words that contain
 8837: absolute addresses in this form in a relocatable image file. Workarounds
 8838: are representing the address in some relative form (e.g., relative to
 8839: the CFA, which is present in some register), or loading the address from
 8840: a place where it is stored in a non-mangled form.
 8841: @end itemize
 8842: @end itemize
 8843: 
 8844: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
 8845: @section Non-Relocatable Image Files
 8846: @cindex non-relocatable image files
 8847: @cindex image files, non-relocatable
 8848: 
 8849: These files are simple memory dumps of the dictionary. They are specific
 8850: to the executable (i.e., @file{gforth} file) they were created
 8851: with. What's worse, they are specific to the place on which the
 8852: dictionary resided when the image was created. Now, there is no
 8853: guarantee that the dictionary will reside at the same place the next
 8854: time you start Gforth, so there's no guarantee that a non-relocatable
 8855: image will work the next time (Gforth will complain instead of crashing,
 8856: though).
 8857: 
 8858: You can create a non-relocatable image file with
 8859: 
 8860: doc-savesystem
 8861: 
 8862: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
 8863: @section Data-Relocatable Image Files
 8864: @cindex data-relocatable image files
 8865: @cindex image files, data-relocatable
 8866: 
 8867: These files contain relocatable data addresses, but fixed code addresses
 8868: (instead of tokens). They are specific to the executable (i.e.,
 8869: @file{gforth} file) they were created with. For direct threading on some
 8870: architectures (e.g., the i386), data-relocatable images do not work. You
 8871: get a data-relocatable image, if you use @file{gforthmi} with a
 8872: Gforth binary that is not doubly indirect threaded (@pxref{Fully
 8873: Relocatable Image Files}).
 8874: 
 8875: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
 8876: @section Fully Relocatable Image Files
 8877: @cindex fully relocatable image files
 8878: @cindex image files, fully relocatable
 8879: 
 8880: @cindex @file{kern*.fi}, relocatability
 8881: @cindex @file{gforth.fi}, relocatability
 8882: These image files have relocatable data addresses, and tokens for code
 8883: addresses. They can be used with different binaries (e.g., with and
 8884: without debugging) on the same machine, and even across machines with
 8885: the same data formats (byte order, cell size, floating point
 8886: format). However, they are usually specific to the version of Gforth
 8887: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
 8888: are fully relocatable.
 8889: 
 8890: There are two ways to create a fully relocatable image file:
 8891: 
 8892: @menu
 8893: * gforthmi::            The normal way
 8894: * cross.fs::                    The hard way
 8895: @end menu
 8896: 
 8897: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
 8898: @subsection @file{gforthmi}
 8899: @cindex @file{comp-i.fs}
 8900: @cindex @file{gforthmi}
 8901: 
 8902: You will usually use @file{gforthmi}. If you want to create an
 8903: image @var{file} that contains everything you would load by invoking
 8904: Gforth with @code{gforth @var{options}}, you simply say
 8905: @example
 8906: gforthmi @var{file} @var{options}
 8907: @end example
 8908: 
 8909: E.g., if you want to create an image @file{asm.fi} that has the file
 8910: @file{asm.fs} loaded in addition to the usual stuff, you could do it
 8911: like this:
 8912: 
 8913: @example
 8914: gforthmi asm.fi asm.fs
 8915: @end example
 8916: 
 8917: @file{gforthmi} works like this: It produces two non-relocatable
 8918: images for different addresses and then compares them. Its output
 8919: reflects this: first you see the output (if any) of the two Gforth
 8920: invocations that produce the nonrelocatable image files, then you see
 8921: the output of the comparing program: It displays the offset used for
 8922: data addresses and the offset used for code addresses;
 8923: moreover, for each cell that cannot be represented correctly in the
 8924: image files, it displays a line like the following one:
 8925: 
 8926: @example
 8927:      78DC         BFFFFA50         BFFFFA40
 8928: @end example
 8929: 
 8930: This means that at offset $78dc from @code{forthstart}, one input image
 8931: contains $bffffa50, and the other contains $bffffa40. Since these cells
 8932: cannot be represented correctly in the output image, you should examine
 8933: these places in the dictionary and verify that these cells are dead
 8934: (i.e., not read before they are written).
 8935: 
 8936: @cindex @code{savesystem} during @file{gforthmi}
 8937: @cindex @code{bye} during @file{gforthmi}
 8938: @cindex doubly indirect threaded code
 8939: @cindex environment variable @code{GFORTHD}
 8940: @cindex @code{GFORTHD} environment variable
 8941: @cindex @code{gforth-ditc}
 8942: There are a few wrinkles: After processing the passed @var{options}, the
 8943: words @code{savesystem} and @code{bye} must be visible. A special doubly
 8944: indirect threaded version of the @file{gforth} executable is used for
 8945: creating the nonrelocatable images; you can pass the exact filename of
 8946: this executable through the environment variable @code{GFORTHD}
 8947: (default: @file{gforth-ditc}); if you pass a version that is not doubly
 8948: indirect threaded, you will not get a fully relocatable image, but a
 8949: data-relocatable image (because there is no code address offset).
 8950: 
 8951: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
 8952: @subsection @file{cross.fs}
 8953: @cindex @file{cross.fs}
 8954: @cindex cross-compiler
 8955: @cindex metacompiler
 8956: 
 8957: You can also use @code{cross}, a batch compiler that accepts a Forth-like
 8958: programming language. This @code{cross} language has to be documented
 8959: yet.
 8960: 
 8961: @cindex target compiler
 8962: @code{cross} also allows you to create image files for machines with
 8963: different data sizes and data formats than the one used for generating
 8964: the image file. You can also use it to create an application image that
 8965: does not contain a Forth compiler. These features are bought with
 8966: restrictions and inconveniences in programming. E.g., addresses have to
 8967: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
 8968: order to make the code relocatable.
 8969: 
 8970: 
 8971: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
 8972: @section Stack and Dictionary Sizes
 8973: @cindex image file, stack and dictionary sizes
 8974: @cindex dictionary size default
 8975: @cindex stack size default
 8976: 
 8977: If you invoke Gforth with a command line flag for the size
 8978: (@pxref{Invoking Gforth}), the size you specify is stored in the
 8979: dictionary. If you save the dictionary with @code{savesystem} or create
 8980: an image with @file{gforthmi}, this size will become the default
 8981: for the resulting image file. E.g., the following will create a
 8982: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
 8983: 
 8984: @example
 8985: gforthmi gforth.fi -m 1M
 8986: @end example
 8987: 
 8988: In other words, if you want to set the default size for the dictionary
 8989: and the stacks of an image, just invoke @file{gforthmi} with the
 8990: appropriate options when creating the image.
 8991: 
 8992: @cindex stack size, cache-friendly
 8993: Note: For cache-friendly behaviour (i.e., good performance), you should
 8994: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
 8995: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
 8996: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
 8997: 
 8998: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
 8999: @section Running Image Files
 9000: @cindex running image files
 9001: @cindex invoking image files
 9002: @cindex image file invocation
 9003: 
 9004: @cindex -i, invoke image file
 9005: @cindex --image file, invoke image file
 9006: You can invoke Gforth with an image file @var{image} instead of the
 9007: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
 9008: @example
 9009: gforth -i @var{image}
 9010: @end example
 9011: 
 9012: @cindex executable image file
 9013: @cindex image files, executable
 9014: If your operating system supports starting scripts with a line of the
 9015: form @code{#! ...}, you just have to type the image file name to start
 9016: Gforth with this image file (note that the file extension @code{.fi} is
 9017: just a convention). I.e., to run Gforth with the image file @var{image},
 9018: you can just type @var{image} instead of @code{gforth -i @var{image}}.
 9019: 
 9020: doc-#!
 9021: 
 9022: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
 9023: @section Modifying the Startup Sequence
 9024: @cindex startup sequence for image file
 9025: @cindex image file initialization sequence
 9026: @cindex initialization sequence of image file
 9027: 
 9028: You can add your own initialization to the startup sequence through the
 9029: deferred word
 9030: 
 9031: doc-'cold
 9032: 
 9033: @code{'cold} is invoked just before the image-specific command line
 9034: processing (by default, loading files and evaluating (@code{-e}) strings)
 9035: starts.
 9036: 
 9037: A sequence for adding your initialization usually looks like this:
 9038: 
 9039: @example
 9040: :noname
 9041:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
 9042:     ... \ your stuff
 9043: ; IS 'cold
 9044: @end example
 9045: 
 9046: @cindex turnkey image files
 9047: @cindex image files, turnkey applications
 9048: You can make a turnkey image by letting @code{'cold} execute a word
 9049: (your turnkey application) that never returns; instead, it exits Gforth
 9050: via @code{bye} or @code{throw}.
 9051: 
 9052: @cindex command-line arguments, access
 9053: @cindex arguments on the command line, access
 9054: You can access the (image-specific) command-line arguments through the
 9055: variables @code{argc} and @code{argv}. @code{arg} provides conventient
 9056: access to @code{argv}.
 9057: 
 9058: doc-argc
 9059: doc-argv
 9060: doc-arg
 9061: 
 9062: If @code{'cold} exits normally, Gforth processes the command-line
 9063: arguments as files to be loaded and strings to be evaluated.  Therefore,
 9064: @code{'cold} should remove the arguments it has used in this case.
 9065: 
 9066: @c ******************************************************************
 9067: @node Engine, Binding to System Library, Image Files, Top
 9068: @chapter Engine
 9069: @cindex engine
 9070: @cindex virtual machine
 9071: 
 9072: Reading this section is not necessary for programming with Gforth. It
 9073: may be helpful for finding your way in the Gforth sources.
 9074: 
 9075: The ideas in this section have also been published in the papers
 9076: @cite{ANS fig/GNU/??? Forth} (in German) by Bernd Paysan, presented at
 9077: the Forth-Tagung '93 and @cite{A Portable Forth Engine} by M. Anton
 9078: Ertl, presented at EuroForth '93; the latter is available at
 9079: @*@url{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z}.
 9080: 
 9081: @menu
 9082: * Portability::                 
 9083: * Threading::                   
 9084: * Primitives::                  
 9085: * Performance::                 
 9086: @end menu
 9087: 
 9088: @node Portability, Threading, Engine, Engine
 9089: @section Portability
 9090: @cindex engine portability
 9091: 
 9092: One of the main goals of the effort is availability across a wide range
 9093: of personal machines. fig-Forth, and, to a lesser extent, F83, achieved
 9094: this goal by manually coding the engine in assembly language for several
 9095: then-popular processors. This approach is very labor-intensive and the
 9096: results are short-lived due to progress in computer architecture.
 9097: 
 9098: @cindex C, using C for the engine
 9099: Others have avoided this problem by coding in C, e.g., Mitch Bradley
 9100: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
 9101: particularly popular for UNIX-based Forths due to the large variety of
 9102: architectures of UNIX machines. Unfortunately an implementation in C
 9103: does not mix well with the goals of efficiency and with using
 9104: traditional techniques: Indirect or direct threading cannot be expressed
 9105: in C, and switch threading, the fastest technique available in C, is
 9106: significantly slower. Another problem with C is that it is very
 9107: cumbersome to express double integer arithmetic.
 9108: 
 9109: @cindex GNU C for the engine
 9110: @cindex long long
 9111: Fortunately, there is a portable language that does not have these
 9112: limitations: GNU C, the version of C processed by the GNU C compiler
 9113: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
 9114: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
 9115: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
 9116: threading possible, its @code{long long} type (@pxref{Long Long, ,
 9117: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
 9118: double numbers@footnote{Unfortunately, long longs are not implemented
 9119: properly on all machines (e.g., on alpha-osf1, long longs are only 64
 9120: bits, the same size as longs (and pointers), but they should be twice as
 9121: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
 9122: C Manual}). So, we had to implement doubles in C after all. Still, on
 9123: most machines we can use long longs and achieve better performance than
 9124: with the emulation package.}. GNU C is available for free on all
 9125: important (and many unimportant) UNIX machines, VMS, 80386s running
 9126: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
 9127: on all these machines.
 9128: 
 9129: Writing in a portable language has the reputation of producing code that
 9130: is slower than assembly. For our Forth engine we repeatedly looked at
 9131: the code produced by the compiler and eliminated most compiler-induced
 9132: inefficiencies by appropriate changes in the source code.
 9133: 
 9134: @cindex explicit register declarations
 9135: @cindex --enable-force-reg, configuration flag
 9136: @cindex -DFORCE_REG
 9137: However, register allocation cannot be portably influenced by the
 9138: programmer, leading to some inefficiencies on register-starved
 9139: machines. We use explicit register declarations (@pxref{Explicit Reg
 9140: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
 9141: improve the speed on some machines. They are turned on by using the
 9142: configuration flag @code{--enable-force-reg} (@code{gcc} switch
 9143: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
 9144: machine, but also on the compiler version: On some machines some
 9145: compiler versions produce incorrect code when certain explicit register
 9146: declarations are used. So by default @code{-DFORCE_REG} is not used.
 9147: 
 9148: @node Threading, Primitives, Portability, Engine
 9149: @section Threading
 9150: @cindex inner interpreter implementation
 9151: @cindex threaded code implementation
 9152: 
 9153: @cindex labels as values
 9154: GNU C's labels as values extension (available since @code{gcc-2.0},
 9155: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
 9156: makes it possible to take the address of @var{label} by writing
 9157: @code{&&@var{label}}.  This address can then be used in a statement like
 9158: @code{goto *@var{address}}. I.e., @code{goto *&&x} is the same as
 9159: @code{goto x}.
 9160: 
 9161: @cindex NEXT, indirect threaded
 9162: @cindex indirect threaded inner interpreter
 9163: @cindex inner interpreter, indirect threaded
 9164: With this feature an indirect threaded NEXT looks like:
 9165: @example
 9166: cfa = *ip++;
 9167: ca = *cfa;
 9168: goto *ca;
 9169: @end example
 9170: @cindex instruction pointer
 9171: For those unfamiliar with the names: @code{ip} is the Forth instruction
 9172: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
 9173: execution token and points to the code field of the next word to be
 9174: executed; The @code{ca} (code address) fetched from there points to some
 9175: executable code, e.g., a primitive or the colon definition handler
 9176: @code{docol}.
 9177: 
 9178: @cindex NEXT, direct threaded
 9179: @cindex direct threaded inner interpreter
 9180: @cindex inner interpreter, direct threaded
 9181: Direct threading is even simpler:
 9182: @example
 9183: ca = *ip++;
 9184: goto *ca;
 9185: @end example
 9186: 
 9187: Of course we have packaged the whole thing neatly in macros called
 9188: @code{NEXT} and @code{NEXT1} (the part of NEXT after fetching the cfa).
 9189: 
 9190: @menu
 9191: * Scheduling::                  
 9192: * Direct or Indirect Threaded?::  
 9193: * DOES>::                       
 9194: @end menu
 9195: 
 9196: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
 9197: @subsection Scheduling
 9198: @cindex inner interpreter optimization
 9199: 
 9200: There is a little complication: Pipelined and superscalar processors,
 9201: i.e., RISC and some modern CISC machines can process independent
 9202: instructions while waiting for the results of an instruction. The
 9203: compiler usually reorders (schedules) the instructions in a way that
 9204: achieves good usage of these delay slots. However, on our first tries
 9205: the compiler did not do well on scheduling primitives. E.g., for
 9206: @code{+} implemented as
 9207: @example
 9208: n=sp[0]+sp[1];
 9209: sp++;
 9210: sp[0]=n;
 9211: NEXT;
 9212: @end example
 9213: the NEXT comes strictly after the other code, i.e., there is nearly no
 9214: scheduling. After a little thought the problem becomes clear: The
 9215: compiler cannot know that @code{sp} and @code{ip} point to different
 9216: addresses (and the version of @code{gcc} we used would not know it even
 9217: if it was possible), so it could not move the load of the cfa above the
 9218: store to the TOS. Indeed the pointers could be the same, if code on or
 9219: very near the top of stack were executed. In the interest of speed we
 9220: chose to forbid this probably unused ``feature'' and helped the compiler
 9221: in scheduling: NEXT is divided into the loading part (@code{NEXT_P1})
 9222: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
 9223: @example
 9224: n=sp[0]+sp[1];
 9225: sp++;
 9226: NEXT_P1;
 9227: sp[0]=n;
 9228: NEXT_P2;
 9229: @end example
 9230: This can be scheduled optimally by the compiler.
 9231: 
 9232: This division can be turned off with the switch @code{-DCISC_NEXT}. This
 9233: switch is on by default on machines that do not profit from scheduling
 9234: (e.g., the 80386), in order to preserve registers.
 9235: 
 9236: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
 9237: @subsection Direct or Indirect Threaded?
 9238: @cindex threading, direct or indirect?
 9239: 
 9240: @cindex -DDIRECT_THREADED
 9241: Both! After packaging the nasty details in macro definitions we
 9242: realized that we could switch between direct and indirect threading by
 9243: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
 9244: defining a few machine-specific macros for the direct-threading case.
 9245: On the Forth level we also offer access words that hide the
 9246: differences between the threading methods (@pxref{Threading Words}).
 9247: 
 9248: Indirect threading is implemented completely machine-independently.
 9249: Direct threading needs routines for creating jumps to the executable
 9250: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
 9251: machine-dependent, but they do not amount to many source lines. Therefore,
 9252: even porting direct threading to a new machine requires little effort.
 9253: 
 9254: @cindex --enable-indirect-threaded, configuration flag
 9255: @cindex --enable-direct-threaded, configuration flag
 9256: The default threading method is machine-dependent. You can enforce a
 9257: specific threading method when building Gforth with the configuration
 9258: flag @code{--enable-direct-threaded} or
 9259: @code{--enable-indirect-threaded}. Note that direct threading is not
 9260: supported on all machines.
 9261: 
 9262: @node DOES>,  , Direct or Indirect Threaded?, Threading
 9263: @subsection DOES>
 9264: @cindex @code{DOES>} implementation
 9265: 
 9266: @cindex dodoes routine
 9267: @cindex DOES-code
 9268: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
 9269: the chunk of code executed by every word defined by a
 9270: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
 9271: the Forth code to be executed, i.e. the code after the
 9272: @code{DOES>} (the DOES-code)? There are two solutions:
 9273: 
 9274: In fig-Forth the code field points directly to the @code{dodoes} and the
 9275: DOES-code address is stored in the cell after the code address (i.e. at
 9276: @code{@var{cfa} cell+}). It may seem that this solution is illegal in
 9277: the Forth-79 and all later standards, because in fig-Forth this address
 9278: lies in the body (which is illegal in these standards). However, by
 9279: making the code field larger for all words this solution becomes legal
 9280: again. We use this approach for the indirect threaded version and for
 9281: direct threading on some machines. Leaving a cell unused in most words
 9282: is a bit wasteful, but on the machines we are targeting this is hardly a
 9283: problem. The other reason for having a code field size of two cells is
 9284: to avoid having different image files for direct and indirect threaded
 9285: systems (direct threaded systems require two-cell code fields on many
 9286: machines).
 9287: 
 9288: @cindex DOES-handler
 9289: The other approach is that the code field points or jumps to the cell
 9290: after @code{DOES}. In this variant there is a jump to @code{dodoes} at
 9291: this address (the DOES-handler). @code{dodoes} can then get the
 9292: DOES-code address by computing the code address, i.e., the address of
 9293: the jump to dodoes, and add the length of that jump field. A variant of
 9294: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
 9295: return address (which can be found in the return register on RISCs) is
 9296: the DOES-code address. Since the two cells available in the code field
 9297: are used up by the jump to the code address in direct threading on many
 9298: architectures, we use this approach for direct threading on these
 9299: architectures. We did not want to add another cell to the code field.
 9300: 
 9301: @node Primitives, Performance, Threading, Engine
 9302: @section Primitives
 9303: @cindex primitives, implementation
 9304: @cindex virtual machine instructions, implementation
 9305: 
 9306: @menu
 9307: * Automatic Generation::        
 9308: * TOS Optimization::            
 9309: * Produced code::               
 9310: @end menu
 9311: 
 9312: @node Automatic Generation, TOS Optimization, Primitives, Primitives
 9313: @subsection Automatic Generation
 9314: @cindex primitives, automatic generation
 9315: 
 9316: @cindex @file{prims2x.fs}
 9317: Since the primitives are implemented in a portable language, there is no
 9318: longer any need to minimize the number of primitives. On the contrary,
 9319: having many primitives has an advantage: speed. In order to reduce the
 9320: number of errors in primitives and to make programming them easier, we
 9321: provide a tool, the primitive generator (@file{prims2x.fs}), that
 9322: automatically generates most (and sometimes all) of the C code for a
 9323: primitive from the stack effect notation.  The source for a primitive
 9324: has the following form:
 9325: 
 9326: @cindex primitive source format
 9327: @format
 9328: @var{Forth-name}	@var{stack-effect}	@var{category}	[@var{pronounc.}]
 9329: [@code{""}@var{glossary entry}@code{""}]
 9330: @var{C code}
 9331: [@code{:}
 9332: @var{Forth code}]
 9333: @end format
 9334: 
 9335: The items in brackets are optional. The category and glossary fields
 9336: are there for generating the documentation, the Forth code is there
 9337: for manual implementations on machines without GNU C. E.g., the source
 9338: for the primitive @code{+} is:
 9339: @example
 9340: +    n1 n2 -- n    core    plus
 9341: n = n1+n2;
 9342: @end example
 9343: 
 9344: This looks like a specification, but in fact @code{n = n1+n2} is C
 9345: code. Our primitive generation tool extracts a lot of information from
 9346: the stack effect notations@footnote{We use a one-stack notation, even
 9347: though we have separate data and floating-point stacks; The separate
 9348: notation can be generated easily from the unified notation.}: The number
 9349: of items popped from and pushed on the stack, their type, and by what
 9350: name they are referred to in the C code. It then generates a C code
 9351: prelude and postlude for each primitive. The final C code for @code{+}
 9352: looks like this:
 9353: 
 9354: @example
 9355: I_plus:	/* + ( n1 n2 -- n ) */  /* label, stack effect */
 9356: /*  */                          /* documentation */
 9357: @{
 9358: DEF_CA                          /* definition of variable ca (indirect threading) */
 9359: Cell n1;                        /* definitions of variables */
 9360: Cell n2;
 9361: Cell n;
 9362: n1 = (Cell) sp[1];              /* input */
 9363: n2 = (Cell) TOS;
 9364: sp += 1;                        /* stack adjustment */
 9365: NAME("+")                       /* debugging output (with -DDEBUG) */
 9366: @{
 9367: n = n1+n2;                      /* C code taken from the source */
 9368: @}
 9369: NEXT_P1;                        /* NEXT part 1 */
 9370: TOS = (Cell)n;                  /* output */
 9371: NEXT_P2;                        /* NEXT part 2 */
 9372: @}
 9373: @end example
 9374: 
 9375: This looks long and inefficient, but the GNU C compiler optimizes quite
 9376: well and produces optimal code for @code{+} on, e.g., the R3000 and the
 9377: HP RISC machines: Defining the @code{n}s does not produce any code, and
 9378: using them as intermediate storage also adds no cost.
 9379: 
 9380: There are also other optimizations, that are not illustrated by this
 9381: example: Assignments between simple variables are usually for free (copy
 9382: propagation). If one of the stack items is not used by the primitive
 9383: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
 9384: (dead code elimination). On the other hand, there are some things that
 9385: the compiler does not do, therefore they are performed by
 9386: @file{prims2x.fs}: The compiler does not optimize code away that stores
 9387: a stack item to the place where it just came from (e.g., @code{over}).
 9388: 
 9389: While programming a primitive is usually easy, there are a few cases
 9390: where the programmer has to take the actions of the generator into
 9391: account, most notably @code{?dup}, but also words that do not (always)
 9392: fall through to NEXT.
 9393: 
 9394: @node TOS Optimization, Produced code, Automatic Generation, Primitives
 9395: @subsection TOS Optimization
 9396: @cindex TOS optimization for primitives
 9397: @cindex primitives, keeping the TOS in a register
 9398: 
 9399: An important optimization for stack machine emulators, e.g., Forth
 9400: engines, is keeping  one or more of the top stack items in
 9401: registers.  If a word has the stack effect @var{in1}...@var{inx} @code{--}
 9402: @var{out1}...@var{outy}, keeping the top @var{n} items in registers
 9403: @itemize @bullet
 9404: @item
 9405: is better than keeping @var{n-1} items, if @var{x>=n} and @var{y>=n},
 9406: due to fewer loads from and stores to the stack.
 9407: @item is slower than keeping @var{n-1} items, if @var{x<>y} and @var{x<n} and
 9408: @var{y<n}, due to additional moves between registers.
 9409: @end itemize
 9410: 
 9411: @cindex -DUSE_TOS
 9412: @cindex -DUSE_NO_TOS
 9413: In particular, keeping one item in a register is never a disadvantage,
 9414: if there are enough registers. Keeping two items in registers is a
 9415: disadvantage for frequent words like @code{?branch}, constants,
 9416: variables, literals and @code{i}. Therefore our generator only produces
 9417: code that keeps zero or one items in registers. The generated C code
 9418: covers both cases; the selection between these alternatives is made at
 9419: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
 9420: code for @code{+} is just a simple variable name in the one-item case,
 9421: otherwise it is a macro that expands into @code{sp[0]}. Note that the
 9422: GNU C compiler tries to keep simple variables like @code{TOS} in
 9423: registers, and it usually succeeds, if there are enough registers.
 9424: 
 9425: @cindex -DUSE_FTOS
 9426: @cindex -DUSE_NO_FTOS
 9427: The primitive generator performs the TOS optimization for the
 9428: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
 9429: operations the benefit of this optimization is even larger:
 9430: floating-point operations take quite long on most processors, but can be
 9431: performed in parallel with other operations as long as their results are
 9432: not used. If the FP-TOS is kept in a register, this works. If
 9433: it is kept on the stack, i.e., in memory, the store into memory has to
 9434: wait for the result of the floating-point operation, lengthening the
 9435: execution time of the primitive considerably.
 9436: 
 9437: The TOS optimization makes the automatic generation of primitives a
 9438: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
 9439: @code{TOS} is not sufficient. There are some special cases to
 9440: consider:
 9441: @itemize @bullet
 9442: @item In the case of @code{dup ( w -- w w )} the generator must not
 9443: eliminate the store to the original location of the item on the stack,
 9444: if the TOS optimization is turned on.
 9445: @item Primitives with stack effects of the form @code{--}
 9446: @var{out1}...@var{outy} must store the TOS to the stack at the start.
 9447: Likewise, primitives with the stack effect @var{in1}...@var{inx} @code{--}
 9448: must load the TOS from the stack at the end. But for the null stack
 9449: effect @code{--} no stores or loads should be generated.
 9450: @end itemize
 9451: 
 9452: @node Produced code,  , TOS Optimization, Primitives
 9453: @subsection Produced code
 9454: @cindex primitives, assembly code listing
 9455: 
 9456: @cindex @file{engine.s}
 9457: To see what assembly code is produced for the primitives on your machine
 9458: with your compiler and your flag settings, type @code{make engine.s} and
 9459: look at the resulting file @file{engine.s}.
 9460: 
 9461: @node  Performance,  , Primitives, Engine
 9462: @section Performance
 9463: @cindex performance of some Forth interpreters
 9464: @cindex engine performance
 9465: @cindex benchmarking Forth systems
 9466: @cindex Gforth performance
 9467: 
 9468: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
 9469: impossible to write a significantly faster engine.
 9470: 
 9471: On register-starved machines like the 386 architecture processors
 9472: improvements are possible, because @code{gcc} does not utilize the
 9473: registers as well as a human, even with explicit register declarations;
 9474: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
 9475: and hand-tuned it for the 486; this system is 1.19 times faster on the
 9476: Sieve benchmark on a 486DX2/66 than Gforth compiled with
 9477: @code{gcc-2.6.3} with @code{-DFORCE_REG}.
 9478: 
 9479: @cindex Win32Forth performance
 9480: @cindex NT Forth performance
 9481: @cindex eforth performance
 9482: @cindex ThisForth performance
 9483: @cindex PFE performance
 9484: @cindex TILE performance
 9485: However, this potential advantage of assembly language implementations
 9486: is not necessarily realized in complete Forth systems: We compared
 9487: Gforth (direct threaded, compiled with @code{gcc-2.6.3} and
 9488: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
 9489: 1994) and Eforth (with and without peephole (aka pinhole) optimization
 9490: of the threaded code); all these systems were written in assembly
 9491: language. We also compared Gforth with three systems written in C:
 9492: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
 9493: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
 9494: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
 9495: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
 9496: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
 9497: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
 9498: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
 9499: 486DX2/66 with similar memory performance under Windows NT. Marcel
 9500: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
 9501: added the peephole optimizer, ran the benchmarks and reported the
 9502: results.
 9503:  
 9504: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
 9505: matrix multiplication come from the Stanford integer benchmarks and have
 9506: been translated into Forth by Martin Fraeman; we used the versions
 9507: included in the TILE Forth package, but with bigger data set sizes; and
 9508: a recursive Fibonacci number computation for benchmarking calling
 9509: performance. The following table shows the time taken for the benchmarks
 9510: scaled by the time taken by Gforth (in other words, it shows the speedup
 9511: factor that Gforth achieved over the other systems).
 9512: 
 9513: @example
 9514: relative      Win32-    NT       eforth       This-
 9515:   time  Gforth Forth Forth eforth  +opt   PFE Forth  TILE
 9516: sieve     1.00  1.39  1.14   1.39  0.85  1.58  3.18  8.58
 9517: bubble    1.00  1.31  1.41   1.48  0.88  1.50        3.88
 9518: matmul    1.00  1.47  1.35   1.46  0.74  1.58        4.09
 9519: fib       1.00  1.52  1.34   1.22  0.86  1.74  2.99  4.30
 9520: @end example
 9521: 
 9522: You may find the good performance of Gforth compared with the systems
 9523: written in assembly language quite surprising. One important reason for
 9524: the disappointing performance of these systems is probably that they are
 9525: not written optimally for the 486 (e.g., they use the @code{lods}
 9526: instruction). In addition, Win32Forth uses a comfortable, but costly
 9527: method for relocating the Forth image: like @code{cforth}, it computes
 9528: the actual addresses at run time, resulting in two address computations
 9529: per NEXT (@pxref{Image File Background}).
 9530: 
 9531: Only Eforth with the peephole optimizer performs comparable to
 9532: Gforth. The speedups achieved with peephole optimization of threaded
 9533: code are quite remarkable. Adding a peephole optimizer to Gforth should
 9534: cause similar speedups.
 9535: 
 9536: The speedup of Gforth over PFE, ThisForth and TILE can be easily
 9537: explained with the self-imposed restriction of the latter systems to
 9538: standard C, which makes efficient threading impossible (however, the
 9539: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
 9540: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
 9541: Moreover, current C compilers have a hard time optimizing other aspects
 9542: of the ThisForth and the TILE source.
 9543: 
 9544: Note that the performance of Gforth on 386 architecture processors
 9545: varies widely with the version of @code{gcc} used. E.g., @code{gcc-2.5.8}
 9546: failed to allocate any of the virtual machine registers into real
 9547: machine registers by itself and would not work correctly with explicit
 9548: register declarations, giving a 1.3 times slower engine (on a 486DX2/66
 9549: running the Sieve) than the one measured above.
 9550: 
 9551: Note also that there have been several releases of Win32Forth since the
 9552: release presented here, so the results presented here may have little
 9553: predictive value for the performance of Win32Forth today.
 9554: 
 9555: @cindex @file{Benchres}
 9556: In @cite{Translating Forth to Efficient C} by M. Anton Ertl and Martin
 9557: Maierhofer (presented at EuroForth '95), an indirect threaded version of
 9558: Gforth is compared with Win32Forth, NT Forth, PFE, and ThisForth; that
 9559: version of Gforth is 2%@minus{}8% slower on a 486 than the direct
 9560: threaded version used here. The paper available at
 9561: @*@url{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz};
 9562: it also contains numbers for some native code systems. You can find a
 9563: newer version of these measurements at
 9564: @url{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
 9565: find numbers for Gforth on various machines in @file{Benchres}.
 9566: 
 9567: @node Binding to System Library, Cross Compiler, Engine, Top
 9568: @chapter Binding to System Library
 9569: 
 9570: @node Cross Compiler, Bugs, Binding to System Library, Top
 9571: @chapter Cross Compiler
 9572: 
 9573: Cross Compiler
 9574: 
 9575: @menu
 9576: * Using the Cross Compiler::
 9577: * How the Cross Compiler Works::
 9578: @end menu
 9579: 
 9580: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
 9581: @section Using the Cross Compiler
 9582: 
 9583: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
 9584: @section How the Cross Compiler Works
 9585: 
 9586: @node Bugs, Origin, Cross Compiler, Top
 9587: @appendix Bugs
 9588: @cindex bug reporting
 9589: 
 9590: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
 9591: 
 9592: If you find a bug, please send a bug report to
 9593: @email{bug-gforth@@gnu.ai.mit.edu}. A bug report should include this
 9594: information:
 9595: 
 9596: @itemize @bullet
 9597: @item
 9598: The Gforth version used (it is announced at the start of an
 9599: interactive Gforth session).
 9600: @item
 9601: The machine and operating system (on Unix
 9602: systems @code{uname -a} will report this information).
 9603: @item
 9604: The installation options (send the file @file{config.status}).
 9605: @item
 9606: A complete list of changes (if any) you (or your installer) have made to the
 9607: Gforth sources.
 9608: @item
 9609: A program (or a sequence of keyboard commands) that reproduces the bug.
 9610: @item
 9611: A description of what you think constitutes the buggy behaviour.
 9612: @end itemize
 9613: 
 9614: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
 9615: to Report Bugs, gcc.info, GNU C Manual}.
 9616: 
 9617: 
 9618: @node Origin, Forth-related information, Bugs, Top
 9619: @appendix Authors and Ancestors of Gforth
 9620: 
 9621: @section Authors and Contributors
 9622: @cindex authors of Gforth
 9623: @cindex contributors to Gforth
 9624: 
 9625: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
 9626: Ertl. The third major author was Jens Wilke.  Lennart Benschop (who was
 9627: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
 9628: with their continuous feedback. Lennart Benshop contributed
 9629: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
 9630: support for calling C libraries. Helpful comments also came from Paul
 9631: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
 9632: Wavrik, Barrie Stott, Marc de Groot, and Jorge Acerada. Since the
 9633: release of Gforth-0.2.1 there were also helpful comments from many
 9634: others; thank you all, sorry for not listing you here (but digging
 9635: through my mailbox to extract your names is on my to-do list).
 9636: 
 9637: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
 9638: and autoconf, among others), and to the creators of the Internet: Gforth
 9639: was developed across the Internet, and its authors did not meet
 9640: physically for the first 4 years of development.
 9641: 
 9642: @section Pedigree
 9643: @cindex Pedigree of Gforth
 9644: 
 9645: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
 9646: Dirk Zoller) will cross-fertilize each other. Of course, a significant
 9647: part of the design of Gforth was prescribed by ANS Forth.
 9648: 
 9649: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
 9650: 32 bit native code version of VolksForth for the Atari ST, written
 9651: mostly by Dietrich Weineck.
 9652: 
 9653: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
 9654: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
 9655: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
 9656: 
 9657: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
 9658: Forth-83 standard. !! Pedigree? When?
 9659: 
 9660: A team led by Bill Ragsdale implemented fig-Forth on many processors in
 9661: 1979. Robert Selzer and Bill Ragsdale developed the original
 9662: implementation of fig-Forth for the 6502 based on microForth.
 9663: 
 9664: The principal architect of microForth was Dean Sanderson. microForth was
 9665: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
 9666: the 1802, and subsequently implemented on the 8080, the 6800 and the
 9667: Z80.
 9668: 
 9669: All earlier Forth systems were custom-made, usually by Charles Moore,
 9670: who discovered (as he puts it) Forth during the late 60s. The first full
 9671: Forth existed in 1971.
 9672: 
 9673: A part of the information in this section comes from @cite{The Evolution
 9674: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
 9675: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
 9676: Notices 28(3), 1993.  You can find more historical and genealogical
 9677: information about Forth there.
 9678: 
 9679: @node Forth-related information, Word Index, Origin, Top
 9680: @appendix Other Forth-related information
 9681: @cindex Forth-related information
 9682: 
 9683: @menu
 9684: * Internet resources::
 9685: * Books::
 9686: * The Forth Interest Group::
 9687: * Conferences::
 9688: @end menu
 9689: 
 9690: 
 9691: @node Internet resources, Books, Forth-related information, Forth-related information
 9692: @section Internet resources
 9693: @cindex Internet resources
 9694: 
 9695: @cindex comp.lang.forth
 9696: @cindex frequently asked questions
 9697: There is an active newsgroup (comp.lang.forth) discussing Forth and
 9698: Forth-related issues. A frequently-asked-questions (FAQ) list
 9699: is posted to the newsgroup regulary, and archived at these sites:
 9700: 
 9701: @itemize @bullet
 9702: @item
 9703: @url{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
 9704: @item
 9705: @url{ftp://ftp.forth.org/pub/Forth/FAQ/}
 9706: @end itemize
 9707: 
 9708: The FAQ list should be considered mandatory reading before posting to
 9709: the newsgroup.
 9710: 
 9711: Here are some other web sites holding Forth-related material:
 9712: 
 9713: @itemize @bullet
 9714: @item
 9715: @url{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
 9716: @item
 9717: @url{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
 9718: @item
 9719: @url{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
 9720: @item
 9721: @url{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
 9722: Research page, including links to the Journal of Forth Application and
 9723: Research (JFAR) and a searchable Forth bibliography.
 9724: @end itemize
 9725: 
 9726: 
 9727: @node Books, The Forth Interest Group, Internet resources, Forth-related information
 9728: @section Books
 9729: @cindex Books
 9730: 
 9731: As the Standard is relatively new, there are not many books out yet. It
 9732: is not recommended to learn Forth by using Gforth and a book that is not
 9733: written for ANS Forth, as you will not know your mistakes from the
 9734: deviations of the book. However, books based on the Forth-83 standard
 9735: should be ok, because ANS Forth is primarily an extension of Forth-83.
 9736: 
 9737: @cindex standard document for ANS Forth
 9738: @cindex ANS Forth document
 9739: The definite reference if you want to write ANS Forth programs is, of
 9740: course, the ANS Forth Standard. It is available in printed form from the
 9741: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
 9742: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
 9743: $200. You can also get it from Global Engineering Documents (Tel.: USA
 9744: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
 9745: 
 9746: @cite{dpANS6}, the last draft of the standard, which was then submitted
 9747: to ANSI for publication is available electronically and for free in some
 9748: MS Word format, and it has been converted to HTML
 9749: (@url{http://www.taygeta.com/forth/dpans.html}; this is my favourite
 9750: format); this HTML version also includes the answers to Requests for
 9751: Interpretation (RFIs). Some pointers to these versions can be found
 9752: through @*@url{http://www.complang.tuwien.ac.at/projects/forth.html}.
 9753: 
 9754: @cindex introductory book
 9755: @cindex book, introductory
 9756: @cindex Woehr, Jack: @cite{Forth: The New Model}
 9757: @cindex @cite{Forth: The new model} (book)
 9758: @cite{Forth: The New Model} by Jack Woehr (Prentice-Hall, 1993) is an
 9759: introductory book based on a draft version of the standard. It does not
 9760: cover the whole standard. It also contains interesting background
 9761: information (Jack Woehr was in the ANS Forth Technical Committee). It is
 9762: not appropriate for complete newbies, but programmers experienced in
 9763: other languages should find it ok.
 9764: 
 9765: @cindex Conklin, Edward K., and Elizabeth Rather: @cite{Forth Programmer's Handbook}
 9766: @cindex Rather, Elizabeth and Edward K. Conklin: @cite{Forth Programmer's Handbook}
 9767: @cindex @cite{Forth Programmer's Handbook} (book)
 9768: @cite{Forth Programmer's Handbook} by Edward K. Conklin, Elizabeth
 9769: D. Rather and the technical staff of Forth, Inc. (Forth, Inc., 1997;
 9770: ISBN 0-9662156-0-5) contains little introductory material. The majority
 9771: of the book is similar to @ref{Words}, but the book covers most of the
 9772: standard words and some non-standard words (whereas this manual is
 9773: quite incomplete). In addition, the book contains a chapter on
 9774: programming style. The major drawback of this book is that it usually
 9775: does not identify what is standard and what is specific to the Forth
 9776: system described in the book (probably one of Forth, Inc.'s systems).
 9777: Fortunately, many of the non-standard programming practices described in
 9778: the book work in Gforth, too.  Still, this drawback makes the book
 9779: hardly more useful than a pre-ANS book.
 9780: 
 9781: @node The Forth Interest Group, Conferences, Books, Forth-related information
 9782: @section The Forth Interest Group
 9783: @cindex Forth interest group (FIG)
 9784: 
 9785: The Forth Interest Group (FIG) is a world-wide, non-profit,
 9786: member-supported organisation. It publishes a regular magazine and
 9787: offers other benefits of membership. You can contact the FIG through
 9788: their office email address: @email{office@@forth.org} or by visiting
 9789: their web site at @url{http://www.forth.org/}. This web site also
 9790: includes links to FIG chapters in other countries and American cities
 9791: (@url{http://www.forth.org/chapters.html}).
 9792: 
 9793: @node Conferences, , The Forth Interest Group, Forth-related information
 9794: @section Conferences
 9795: @cindex Conferences
 9796: 
 9797: There are several regular conferences related to Forth. They are all
 9798: well-publicised in FIG magazine and on the comp.lang.forth news group:
 9799: 
 9800: @itemize @bullet
 9801: @item
 9802: FORML -- the Forth modification laboratory convenes every year near
 9803: Monterey, California.
 9804: @item
 9805: The Rochester Forth Conference -- an annual conference traditionally
 9806: held in Rochester, New York.
 9807: @item
 9808: EuroForth -- this European conference takes place annually.
 9809: @end itemize
 9810: 
 9811: 
 9812: @node Word Index, Concept Index, Forth-related information, Top
 9813: @unnumbered Word Index
 9814: 
 9815: This index is as incomplete as the manual. Each word is listed with
 9816: stack effect and wordset.
 9817: 
 9818: @printindex fn
 9819: 
 9820: @node Concept Index,  , Word Index, Top
 9821: @unnumbered Concept and Word Index
 9822: 
 9823: This index is as incomplete as the manual. Not all entries listed are
 9824: present verbatim in the text. Only the names are listed for the words
 9825: here.
 9826: 
 9827: @printindex cp
 9828: 
 9829: @contents
 9830: @bye
 9831: 

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