File:  [gforth] / gforth / doc / gforth.ds
Revision 1.40: download - view: text, annotated - select for diffs
Sun Aug 29 15:45:21 1999 UTC (24 years, 8 months ago) by anton
Branches: MAIN
CVS tags: HEAD
added ekey etc.
updated performance in docs

    1: \input texinfo   @c -*-texinfo-*-
    2: @comment The source is gforth.ds, from which gforth.texi is generated
    3: 
    4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
    5: @comment 1. x-ref all ambiguous or implementation-defined features?
    6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
    7: @comment 3. words in miscellaneous section need a home.
    8: @comment 4. search for TODO for other minor and major works required.
    9: @comment 5. [rats] change all @var to @i in Forth source so that info
   10: @comment    file looks decent.
   11: @c          Not an improvement IMO - anton
   12: @c          and anyway, this should be taken up
   13: @c          with Karl Berry (the texinfo guy) - anton
   14: @comment .. would be useful to have a word that identified all deferred words
   15: @comment should semantics stuff in intro be moved to another section
   16: 
   17: 
   18: @comment %**start of header (This is for running Texinfo on a region.)
   19: @setfilename gforth.info
   20: @settitle Gforth Manual
   21: @dircategory GNU programming tools
   22: @direntry
   23: * Gforth: (gforth).             A fast interpreter for the Forth language.
   24: @end direntry
   25: @comment @setchapternewpage odd
   26: @comment TODO this gets left in by HTML converter
   27: @macro progstyle {}
   28: Programming style note:
   29: @end macro
   30: @comment %**end of header (This is for running Texinfo on a region.)
   31: 
   32: 
   33: @comment ----------------------------------------------------------
   34: @comment macros for beautifying glossary entries
   35: @comment if these are used, need to strip them out for HTML converter
   36: @comment else they get repeated verbatim in HTML output.
   37: @comment .. not working yet.
   38: 
   39: @macro GLOSS-START {}
   40: @iftex
   41: @ninerm
   42: @end iftex
   43: @end macro
   44: 
   45: @macro GLOSS-END {}
   46: @iftex
   47: @rm
   48: @end iftex
   49: @end macro
   50: 
   51: @comment ----------------------------------------------------------
   52: 
   53: 
   54: @include version.texi
   55: 
   56: @ifinfo
   57: This file documents Gforth @value{VERSION}
   58: 
   59: Copyright @copyright{} 1995-1999 Free Software Foundation, Inc.
   60: 
   61:      Permission is granted to make and distribute verbatim copies of
   62:      this manual provided the copyright notice and this permission notice
   63:      are preserved on all copies.
   64:      
   65: @ignore
   66:      Permission is granted to process this file through TeX and print the
   67:      results, provided the printed document carries a copying permission
   68:      notice identical to this one except for the removal of this paragraph
   69:      (this paragraph not being relevant to the printed manual).
   70:      
   71: @end ignore
   72:      Permission is granted to copy and distribute modified versions of this
   73:      manual under the conditions for verbatim copying, provided also that the
   74:      sections entitled "Distribution" and "General Public License" are
   75:      included exactly as in the original, and provided that the entire
   76:      resulting derived work is distributed under the terms of a permission
   77:      notice identical to this one.
   78:      
   79:      Permission is granted to copy and distribute translations of this manual
   80:      into another language, under the above conditions for modified versions,
   81:      except that the sections entitled "Distribution" and "General Public
   82:      License" may be included in a translation approved by the author instead
   83:      of in the original English.
   84: @end ifinfo
   85: 
   86: @finalout
   87: @titlepage
   88: @sp 10
   89: @center @titlefont{Gforth Manual}
   90: @sp 2
   91: @center for version @value{VERSION}
   92: @sp 2
   93: @center Neal Crook
   94: @center Anton Ertl
   95: @center Bernd Paysan
   96: @center Jens Wilke
   97: @sp 3
   98: @center This manual is permanently under construction and was last updated on 04-May-1999
   99: 
  100: @comment  The following two commands start the copyright page.
  101: @page
  102: @vskip 0pt plus 1filll
  103: Copyright @copyright{} 1995--1999 Free Software Foundation, Inc.
  104: 
  105: @comment !! Published by ... or You can get a copy of this manual ...
  106: 
  107:      Permission is granted to make and distribute verbatim copies of
  108:      this manual provided the copyright notice and this permission notice
  109:      are preserved on all copies.
  110:      
  111:      Permission is granted to copy and distribute modified versions of this
  112:      manual under the conditions for verbatim copying, provided also that the
  113:      sections entitled "Distribution" and "General Public License" are
  114:      included exactly as in the original, and provided that the entire
  115:      resulting derived work is distributed under the terms of a permission
  116:      notice identical to this one.
  117:      
  118:      Permission is granted to copy and distribute translations of this manual
  119:      into another language, under the above conditions for modified versions,
  120:      except that the sections entitled "Distribution" and "General Public
  121:      License" may be included in a translation approved by the author instead
  122:      of in the original English.
  123: @end titlepage
  124: 
  125: 
  126: @node Top, License, (dir), (dir)
  127: @ifinfo
  128: Gforth is a free implementation of ANS Forth available on many
  129: personal machines. This manual corresponds to version @value{VERSION}.
  130: @end ifinfo
  131: 
  132: @menu
  133: * License::                     The GPL
  134: * Goals::                       About the Gforth Project
  135: * Gforth Environment::          Starting (and exiting) Gforth
  136: * Introduction::                An introduction to ANS Forth
  137: * Words::                       Forth words available in Gforth
  138: * Error messages::              How to interpret them
  139: * Tools::                       Programming tools
  140: * ANS conformance::             Implementation-defined options etc.
  141: * Model::                       The abstract machine of Gforth
  142: * Integrating Gforth::          Forth as scripting language for applications
  143: * Emacs and Gforth::            The Gforth Mode
  144: * Image Files::                 @code{.fi} files contain compiled code
  145: * Engine::                      The inner interpreter and the primitives
  146: * Binding to System Library::   
  147: * Cross Compiler::              The Cross Compiler
  148: * Bugs::                        How to report them
  149: * Origin::                      Authors and ancestors of Gforth
  150: * Forth-related information::   Books and places to look on the WWW
  151: * Word Index::                  An item for each Forth word
  152: * Concept Index::               A menu covering many topics
  153: 
  154: @detailmenu --- The Detailed Node Listing ---
  155: 
  156: Goals of Gforth
  157: 
  158: * Gforth Extensions Sinful?::
  159: 
  160: Gforth Environment
  161: 
  162: * Invoking Gforth::             Getting in
  163: * Leaving Gforth::              Getting out
  164: * Command-line editing::        
  165: * Upper and lower case::
  166: * Environment variables::       ..that affect how Gforth starts up
  167: * Gforth Files::                What gets installed and where
  168: 
  169: An Introduction to ANS Forth
  170: 
  171: * Introducing the Text Interpreter::
  172: * Stacks and Postfix notation::
  173: * Your first definition::
  174: * How does that work?::
  175: * Forth is written in Forth::
  176: * Review - elements of a Forth system::
  177: * Where to go next::
  178: * Exercises::
  179: 
  180: Forth Words
  181: 
  182: * Notation::                    
  183: * Comments::
  184: * Boolean Flags::
  185: * Arithmetic::                  
  186: * Stack Manipulation::          
  187: * Memory::                      
  188: * Control Structures::          
  189: * Defining Words::              
  190: * The Text Interpreter::
  191: * Tokens for Words::            
  192: * Word Lists::                   
  193: * Environmental Queries::
  194: * Files::                       
  195: * Blocks::                      
  196: * Other I/O::                   
  197: * Programming Tools::           
  198: * Assembler and Code Words::    
  199: * Threading Words::             
  200: * Locals::                      
  201: * Structures::                  
  202: * Object-oriented Forth::       
  203: * Passing Commands to the OS::
  204: * Miscellaneous Words::
  205: 
  206: Arithmetic
  207: 
  208: * Single precision::            
  209: * Bitwise operations::          
  210: * Double precision::            Double-cell integer arithmetic
  211: * Numeric comparison::
  212: * Mixed precision::             Operations with single and double-cell integers
  213: * Floating Point::              
  214: 
  215: Stack Manipulation
  216: 
  217: * Data stack::                  
  218: * Floating point stack::        
  219: * Return stack::                
  220: * Locals stack::                
  221: * Stack pointer manipulation::  
  222: 
  223: Memory
  224: 
  225: * Memory model::                
  226: * Dictionary allocation::       
  227: * Heap Allocation::             
  228: * Memory Access::               
  229: * Address arithmetic::          
  230: * Memory Blocks::               
  231: 
  232: Control Structures
  233: 
  234: * Selection::                   IF.. ELSE.. ENDIF
  235: * Simple Loops::                BEGIN..
  236: * Counted Loops::               DO
  237: * Arbitrary control structures::
  238: * Calls and returns::
  239: * Exception Handling::          
  240: 
  241: Defining Words
  242: 
  243: * Simple Defining Words::       Variables, values and constants
  244: * Colon Definitions::
  245: * User-defined Defining Words::
  246: * Supplying names::
  247: * Interpretation and Compilation Semantics::
  248: 
  249: The Text Interpreter
  250: 
  251: * Input Sources::
  252: * Number Conversion::
  253: * Interpret/Compile states::
  254: * Literals::
  255: * Interpreter Directives::
  256: 
  257: Word Lists
  258: 
  259: * Why use word lists?::
  260: * Word list examples::
  261: 
  262: Files
  263: 
  264: * Forth source files::
  265: * General files::         
  266: * Search Paths::                 
  267: * Forth Search Paths::    
  268: * General Search Paths::        
  269: 
  270: Other I/O
  271: 
  272: * Simple numeric output::       Predefined formats
  273: * Formatted numeric output::    Formatted (pictured) output
  274: * String Formats::              How Forth stores strings in memory
  275: * Displaying characters and strings:: Other stuff
  276: * Input::                       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: Locals
  285: 
  286: * Gforth locals::               
  287: * ANS Forth locals::            
  288: 
  289: Gforth locals
  290: 
  291: * Where are locals visible by name?::  
  292: * How long do locals live?::    
  293: * Programming Style::           
  294: * Implementation::              
  295: 
  296: Structures
  297: 
  298: * Why explicit structure support?::  
  299: * Structure Usage::             
  300: * Structure Naming Convention::  
  301: * Structure Implementation::    
  302: * Structure Glossary::          
  303: 
  304: Object-oriented Forth
  305: 
  306: * Why object-oriented programming?::
  307: * Object-Oriented Terminology::
  308: * Objects::
  309: * OOF::
  310: * Mini-OOF::
  311: * Comparison with other object models::  
  312: 
  313: The @file{objects.fs} model
  314: 
  315: * Properties of the Objects model::  
  316: * Basic Objects Usage::         
  317: * The Objects base class::            
  318: * Creating objects::            
  319: * Object-Oriented Programming Style::  
  320: * Class Binding::               
  321: * Method conveniences::         
  322: * Classes and Scoping::         
  323: * Object Interfaces::           
  324: * Objects Implementation::      
  325: * Objects Glossary::            
  326: 
  327: The @file{oof.fs} model
  328: 
  329: * Properties of the OOF model::
  330: * Basic OOF Usage::
  331: * The OOF base class::
  332: * Class Declaration::
  333: * Class Implementation::
  334: 
  335: The @file{mini-oof.fs} model
  336: 
  337: * Basic Mini-OOF Usage::
  338: * Mini-OOF Example::
  339: * Mini-OOF Implementation::
  340: 
  341: Tools
  342: 
  343: * ANS Report::                  Report the words used, sorted by wordset.
  344: 
  345: ANS conformance
  346: 
  347: * The Core Words::              
  348: * The optional Block word set::  
  349: * The optional Double Number word set::  
  350: * The optional Exception word set::  
  351: * The optional Facility word set::  
  352: * The optional File-Access word set::  
  353: * The optional Floating-Point word set::  
  354: * The optional Locals word set::  
  355: * The optional Memory-Allocation word set::  
  356: * The optional Programming-Tools word set::  
  357: * The optional Search-Order word set::  
  358: 
  359: The Core Words
  360: 
  361: * core-idef::                   Implementation Defined Options                   
  362: * core-ambcond::                Ambiguous Conditions                
  363: * core-other::                  Other System Documentation                  
  364: 
  365: The optional Block word set
  366: 
  367: * block-idef::                  Implementation Defined Options
  368: * block-ambcond::               Ambiguous Conditions               
  369: * block-other::                 Other System Documentation                 
  370: 
  371: The optional Double Number word set
  372: 
  373: * double-ambcond::              Ambiguous Conditions              
  374: 
  375: The optional Exception word set
  376: 
  377: * exception-idef::              Implementation Defined Options              
  378: 
  379: The optional Facility word set
  380: 
  381: * facility-idef::               Implementation Defined Options               
  382: * facility-ambcond::            Ambiguous Conditions            
  383: 
  384: The optional File-Access word set
  385: 
  386: * file-idef::                   Implementation Defined Options
  387: * file-ambcond::                Ambiguous Conditions                
  388: 
  389: The optional Floating-Point word set
  390: 
  391: * floating-idef::               Implementation Defined Options
  392: * floating-ambcond::            Ambiguous Conditions            
  393: 
  394: The optional Locals word set
  395: 
  396: * locals-idef::                 Implementation Defined Options                 
  397: * locals-ambcond::              Ambiguous Conditions              
  398: 
  399: The optional Memory-Allocation word set
  400: 
  401: * memory-idef::                 Implementation Defined Options                 
  402: 
  403: The optional Programming-Tools word set
  404: 
  405: * programming-idef::            Implementation Defined Options            
  406: * programming-ambcond::         Ambiguous Conditions         
  407: 
  408: The optional Search-Order word set
  409: 
  410: * search-idef::                 Implementation Defined Options                 
  411: * search-ambcond::              Ambiguous Conditions              
  412: 
  413: Image Files
  414: 
  415: * Image Licensing Issues::      Distribution terms for images.
  416: * Image File Background::       Why have image files?
  417: * Non-Relocatable Image Files::   don't always work.
  418: * Data-Relocatable Image Files::  are better.
  419: * Fully Relocatable Image Files:: better yet.
  420: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
  421: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
  422: * Modifying the Startup Sequence::  and turnkey applications.
  423: 
  424: Fully Relocatable Image Files
  425: 
  426: * gforthmi::                    The normal way
  427: * cross.fs::                    The hard way
  428: 
  429: Engine
  430: 
  431: * Portability::                 
  432: * Threading::                   
  433: * Primitives::                  
  434: * Performance::                 
  435: 
  436: Threading
  437: 
  438: * Scheduling::                  
  439: * Direct or Indirect Threaded?::  
  440: * DOES>::                       
  441: 
  442: Primitives
  443: 
  444: * Automatic Generation::        
  445: * TOS Optimization::            
  446: * Produced code::               
  447: 
  448: Cross Compiler
  449: 
  450: * Using the Cross Compiler::
  451: * How the Cross Compiler Works::
  452: 
  453: Other Forth-related information
  454: 
  455: * Internet resources::
  456: * Books::
  457: * The Forth Interest Group::
  458: * Conferences::
  459: 
  460: @end detailmenu
  461: @end menu
  462: 
  463: @node License, Goals, Top, Top
  464: @unnumbered GNU GENERAL PUBLIC LICENSE
  465: @center Version 2, June 1991
  466: 
  467: @display
  468: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
  469: 675 Mass Ave, Cambridge, MA 02139, USA
  470: 
  471: Everyone is permitted to copy and distribute verbatim copies
  472: of this license document, but changing it is not allowed.
  473: @end display
  474: 
  475: @unnumberedsec Preamble
  476: 
  477:   The licenses for most software are designed to take away your
  478: freedom to share and change it.  By contrast, the GNU General Public
  479: License is intended to guarantee your freedom to share and change free
  480: software---to make sure the software is free for all its users.  This
  481: General Public License applies to most of the Free Software
  482: Foundation's software and to any other program whose authors commit to
  483: using it.  (Some other Free Software Foundation software is covered by
  484: the GNU Library General Public License instead.)  You can apply it to
  485: your programs, too.
  486: 
  487:   When we speak of free software, we are referring to freedom, not
  488: price.  Our General Public Licenses are designed to make sure that you
  489: have the freedom to distribute copies of free software (and charge for
  490: this service if you wish), that you receive source code or can get it
  491: if you want it, that you can change the software or use pieces of it
  492: in new free programs; and that you know you can do these things.
  493: 
  494:   To protect your rights, we need to make restrictions that forbid
  495: anyone to deny you these rights or to ask you to surrender the rights.
  496: These restrictions translate to certain responsibilities for you if you
  497: distribute copies of the software, or if you modify it.
  498: 
  499:   For example, if you distribute copies of such a program, whether
  500: gratis or for a fee, you must give the recipients all the rights that
  501: you have.  You must make sure that they, too, receive or can get the
  502: source code.  And you must show them these terms so they know their
  503: rights.
  504: 
  505:   We protect your rights with two steps: (1) copyright the software, and
  506: (2) offer you this license which gives you legal permission to copy,
  507: distribute and/or modify the software.
  508: 
  509:   Also, for each author's protection and ours, we want to make certain
  510: that everyone understands that there is no warranty for this free
  511: software.  If the software is modified by someone else and passed on, we
  512: want its recipients to know that what they have is not the original, so
  513: that any problems introduced by others will not reflect on the original
  514: authors' reputations.
  515: 
  516:   Finally, any free program is threatened constantly by software
  517: patents.  We wish to avoid the danger that redistributors of a free
  518: program will individually obtain patent licenses, in effect making the
  519: program proprietary.  To prevent this, we have made it clear that any
  520: patent must be licensed for everyone's free use or not licensed at all.
  521: 
  522:   The precise terms and conditions for copying, distribution and
  523: modification follow.
  524: 
  525: @iftex
  526: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  527: @end iftex
  528: @ifinfo
  529: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  530: @end ifinfo
  531: 
  532: @enumerate 0
  533: @item
  534: This License applies to any program or other work which contains
  535: a notice placed by the copyright holder saying it may be distributed
  536: under the terms of this General Public License.  The ``Program'', below,
  537: refers to any such program or work, and a ``work based on the Program''
  538: means either the Program or any derivative work under copyright law:
  539: that is to say, a work containing the Program or a portion of it,
  540: either verbatim or with modifications and/or translated into another
  541: language.  (Hereinafter, translation is included without limitation in
  542: the term ``modification''.)  Each licensee is addressed as ``you''.
  543: 
  544: Activities other than copying, distribution and modification are not
  545: covered by this License; they are outside its scope.  The act of
  546: running the Program is not restricted, and the output from the Program
  547: is covered only if its contents constitute a work based on the
  548: Program (independent of having been made by running the Program).
  549: Whether that is true depends on what the Program does.
  550: 
  551: @item
  552: You may copy and distribute verbatim copies of the Program's
  553: source code as you receive it, in any medium, provided that you
  554: conspicuously and appropriately publish on each copy an appropriate
  555: copyright notice and disclaimer of warranty; keep intact all the
  556: notices that refer to this License and to the absence of any warranty;
  557: and give any other recipients of the Program a copy of this License
  558: along with the Program.
  559: 
  560: You may charge a fee for the physical act of transferring a copy, and
  561: you may at your option offer warranty protection in exchange for a fee.
  562: 
  563: @item
  564: You may modify your copy or copies of the Program or any portion
  565: of it, thus forming a work based on the Program, and copy and
  566: distribute such modifications or work under the terms of Section 1
  567: above, provided that you also meet all of these conditions:
  568: 
  569: @enumerate a
  570: @item
  571: You must cause the modified files to carry prominent notices
  572: stating that you changed the files and the date of any change.
  573: 
  574: @item
  575: You must cause any work that you distribute or publish, that in
  576: whole or in part contains or is derived from the Program or any
  577: part thereof, to be licensed as a whole at no charge to all third
  578: parties under the terms of this License.
  579: 
  580: @item
  581: If the modified program normally reads commands interactively
  582: when run, you must cause it, when started running for such
  583: interactive use in the most ordinary way, to print or display an
  584: announcement including an appropriate copyright notice and a
  585: notice that there is no warranty (or else, saying that you provide
  586: a warranty) and that users may redistribute the program under
  587: these conditions, and telling the user how to view a copy of this
  588: License.  (Exception: if the Program itself is interactive but
  589: does not normally print such an announcement, your work based on
  590: the Program is not required to print an announcement.)
  591: @end enumerate
  592: 
  593: These requirements apply to the modified work as a whole.  If
  594: identifiable sections of that work are not derived from the Program,
  595: and can be reasonably considered independent and separate works in
  596: themselves, then this License, and its terms, do not apply to those
  597: sections when you distribute them as separate works.  But when you
  598: distribute the same sections as part of a whole which is a work based
  599: on the Program, the distribution of the whole must be on the terms of
  600: this License, whose permissions for other licensees extend to the
  601: entire whole, and thus to each and every part regardless of who wrote it.
  602: 
  603: Thus, it is not the intent of this section to claim rights or contest
  604: your rights to work written entirely by you; rather, the intent is to
  605: exercise the right to control the distribution of derivative or
  606: collective works based on the Program.
  607: 
  608: In addition, mere aggregation of another work not based on the Program
  609: with the Program (or with a work based on the Program) on a volume of
  610: a storage or distribution medium does not bring the other work under
  611: the scope of this License.
  612: 
  613: @item
  614: You may copy and distribute the Program (or a work based on it,
  615: under Section 2) in object code or executable form under the terms of
  616: Sections 1 and 2 above provided that you also do one of the following:
  617: 
  618: @enumerate a
  619: @item
  620: Accompany it with the complete corresponding machine-readable
  621: source code, which must be distributed under the terms of Sections
  622: 1 and 2 above on a medium customarily used for software interchange; or,
  623: 
  624: @item
  625: Accompany it with a written offer, valid for at least three
  626: years, to give any third party, for a charge no more than your
  627: cost of physically performing source distribution, a complete
  628: machine-readable copy of the corresponding source code, to be
  629: distributed under the terms of Sections 1 and 2 above on a medium
  630: customarily used for software interchange; or,
  631: 
  632: @item
  633: Accompany it with the information you received as to the offer
  634: to distribute corresponding source code.  (This alternative is
  635: allowed only for noncommercial distribution and only if you
  636: received the program in object code or executable form with such
  637: an offer, in accord with Subsection b above.)
  638: @end enumerate
  639: 
  640: The source code for a work means the preferred form of the work for
  641: making modifications to it.  For an executable work, complete source
  642: code means all the source code for all modules it contains, plus any
  643: associated interface definition files, plus the scripts used to
  644: control compilation and installation of the executable.  However, as a
  645: special exception, the source code distributed need not include
  646: anything that is normally distributed (in either source or binary
  647: form) with the major components (compiler, kernel, and so on) of the
  648: operating system on which the executable runs, unless that component
  649: itself accompanies the executable.
  650: 
  651: If distribution of executable or object code is made by offering
  652: access to copy from a designated place, then offering equivalent
  653: access to copy the source code from the same place counts as
  654: distribution of the source code, even though third parties are not
  655: compelled to copy the source along with the object code.
  656: 
  657: @item
  658: You may not copy, modify, sublicense, or distribute the Program
  659: except as expressly provided under this License.  Any attempt
  660: otherwise to copy, modify, sublicense or distribute the Program is
  661: void, and will automatically terminate your rights under this License.
  662: However, parties who have received copies, or rights, from you under
  663: this License will not have their licenses terminated so long as such
  664: parties remain in full compliance.
  665: 
  666: @item
  667: You are not required to accept this License, since you have not
  668: signed it.  However, nothing else grants you permission to modify or
  669: distribute the Program or its derivative works.  These actions are
  670: prohibited by law if you do not accept this License.  Therefore, by
  671: modifying or distributing the Program (or any work based on the
  672: Program), you indicate your acceptance of this License to do so, and
  673: all its terms and conditions for copying, distributing or modifying
  674: the Program or works based on it.
  675: 
  676: @item
  677: Each time you redistribute the Program (or any work based on the
  678: Program), the recipient automatically receives a license from the
  679: original licensor to copy, distribute or modify the Program subject to
  680: these terms and conditions.  You may not impose any further
  681: restrictions on the recipients' exercise of the rights granted herein.
  682: You are not responsible for enforcing compliance by third parties to
  683: this License.
  684: 
  685: @item
  686: If, as a consequence of a court judgment or allegation of patent
  687: infringement or for any other reason (not limited to patent issues),
  688: conditions are imposed on you (whether by court order, agreement or
  689: otherwise) that contradict the conditions of this License, they do not
  690: excuse you from the conditions of this License.  If you cannot
  691: distribute so as to satisfy simultaneously your obligations under this
  692: License and any other pertinent obligations, then as a consequence you
  693: may not distribute the Program at all.  For example, if a patent
  694: license would not permit royalty-free redistribution of the Program by
  695: all those who receive copies directly or indirectly through you, then
  696: the only way you could satisfy both it and this License would be to
  697: refrain entirely from distribution of the Program.
  698: 
  699: If any portion of this section is held invalid or unenforceable under
  700: any particular circumstance, the balance of the section is intended to
  701: apply and the section as a whole is intended to apply in other
  702: circumstances.
  703: 
  704: It is not the purpose of this section to induce you to infringe any
  705: patents or other property right claims or to contest validity of any
  706: such claims; this section has the sole purpose of protecting the
  707: integrity of the free software distribution system, which is
  708: implemented by public license practices.  Many people have made
  709: generous contributions to the wide range of software distributed
  710: through that system in reliance on consistent application of that
  711: system; it is up to the author/donor to decide if he or she is willing
  712: to distribute software through any other system and a licensee cannot
  713: impose that choice.
  714: 
  715: This section is intended to make thoroughly clear what is believed to
  716: be a consequence of the rest of this License.
  717: 
  718: @item
  719: If the distribution and/or use of the Program is restricted in
  720: certain countries either by patents or by copyrighted interfaces, the
  721: original copyright holder who places the Program under this License
  722: may add an explicit geographical distribution limitation excluding
  723: those countries, so that distribution is permitted only in or among
  724: countries not thus excluded.  In such case, this License incorporates
  725: the limitation as if written in the body of this License.
  726: 
  727: @item
  728: The Free Software Foundation may publish revised and/or new versions
  729: of the General Public License from time to time.  Such new versions will
  730: be similar in spirit to the present version, but may differ in detail to
  731: address new problems or concerns.
  732: 
  733: Each version is given a distinguishing version number.  If the Program
  734: specifies a version number of this License which applies to it and ``any
  735: later version'', you have the option of following the terms and conditions
  736: either of that version or of any later version published by the Free
  737: Software Foundation.  If the Program does not specify a version number of
  738: this License, you may choose any version ever published by the Free Software
  739: Foundation.
  740: 
  741: @item
  742: If you wish to incorporate parts of the Program into other free
  743: programs whose distribution conditions are different, write to the author
  744: to ask for permission.  For software which is copyrighted by the Free
  745: Software Foundation, write to the Free Software Foundation; we sometimes
  746: make exceptions for this.  Our decision will be guided by the two goals
  747: of preserving the free status of all derivatives of our free software and
  748: of promoting the sharing and reuse of software generally.
  749: 
  750: @iftex
  751: @heading NO WARRANTY
  752: @end iftex
  753: @ifinfo
  754: @center NO WARRANTY
  755: @end ifinfo
  756: 
  757: @item
  758: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
  759: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
  760: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
  761: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
  762: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  763: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
  764: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
  765: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
  766: REPAIR OR CORRECTION.
  767: 
  768: @item
  769: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
  770: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
  771: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
  772: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
  773: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
  774: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
  775: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
  776: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
  777: POSSIBILITY OF SUCH DAMAGES.
  778: @end enumerate
  779: 
  780: @iftex
  781: @heading END OF TERMS AND CONDITIONS
  782: @end iftex
  783: @ifinfo
  784: @center END OF TERMS AND CONDITIONS
  785: @end ifinfo
  786: 
  787: @page
  788: @unnumberedsec How to Apply These Terms to Your New Programs
  789: 
  790:   If you develop a new program, and you want it to be of the greatest
  791: possible use to the public, the best way to achieve this is to make it
  792: free software which everyone can redistribute and change under these terms.
  793: 
  794:   To do so, attach the following notices to the program.  It is safest
  795: to attach them to the start of each source file to most effectively
  796: convey the exclusion of warranty; and each file should have at least
  797: the ``copyright'' line and a pointer to where the full notice is found.
  798: 
  799: @smallexample
  800: @var{one line to give the program's name and a brief idea of what it does.}
  801: Copyright (C) 19@var{yy}  @var{name of author}
  802: 
  803: This program is free software; you can redistribute it and/or modify 
  804: it under the terms of the GNU General Public License as published by 
  805: the Free Software Foundation; either version 2 of the License, or 
  806: (at your option) any later version.
  807: 
  808: This program is distributed in the hope that it will be useful,
  809: but WITHOUT ANY WARRANTY; without even the implied warranty of
  810: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  811: GNU General Public License for more details.
  812: 
  813: You should have received a copy of the GNU General Public License
  814: along with this program; if not, write to the Free Software
  815: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  816: @end smallexample
  817: 
  818: Also add information on how to contact you by electronic and paper mail.
  819: 
  820: If the program is interactive, make it output a short notice like this
  821: when it starts in an interactive mode:
  822: 
  823: @smallexample
  824: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
  825: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
  826: type `show w'.  
  827: This is free software, and you are welcome to redistribute it 
  828: under certain conditions; type `show c' for details.
  829: @end smallexample
  830: 
  831: The hypothetical commands @samp{show w} and @samp{show c} should show
  832: the appropriate parts of the General Public License.  Of course, the
  833: commands you use may be called something other than @samp{show w} and
  834: @samp{show c}; they could even be mouse-clicks or menu items---whatever
  835: suits your program.
  836: 
  837: You should also get your employer (if you work as a programmer) or your
  838: school, if any, to sign a ``copyright disclaimer'' for the program, if
  839: necessary.  Here is a sample; alter the names:
  840: 
  841: @smallexample
  842: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  843: `Gnomovision' (which makes passes at compilers) written by James Hacker.
  844: 
  845: @var{signature of Ty Coon}, 1 April 1989
  846: Ty Coon, President of Vice
  847: @end smallexample
  848: 
  849: This General Public License does not permit incorporating your program into
  850: proprietary programs.  If your program is a subroutine library, you may
  851: consider it more useful to permit linking proprietary applications with the
  852: library.  If this is what you want to do, use the GNU Library General
  853: Public License instead of this License.
  854: 
  855: @iftex
  856: @unnumbered Preface
  857: @cindex Preface
  858: This manual documents Gforth. Some introductory material is provided for
  859: readers who are unfamiliar with Forth or who are migrating to Gforth
  860: from other Forth compilers. However, this manual is primarily a
  861: reference manual.
  862: @end iftex
  863: 
  864: @comment TODO much more blurb here.
  865: 
  866: @c ******************************************************************
  867: @node Goals, Gforth Environment, License, Top
  868: @comment node-name,     next,           previous, up
  869: @chapter Goals of Gforth
  870: @cindex goals of the Gforth project
  871: The goal of the Gforth Project is to develop a standard model for
  872: ANS Forth. This can be split into several subgoals:
  873: 
  874: @itemize @bullet
  875: @item
  876: Gforth should conform to the ANS Forth Standard.
  877: @item
  878: It should be a model, i.e. it should define all the
  879: implementation-dependent things.
  880: @item
  881: It should become standard, i.e. widely accepted and used. This goal
  882: is the most difficult one.
  883: @end itemize
  884: 
  885: To achieve these goals Gforth should be
  886: @itemize @bullet
  887: @item
  888: Similar to previous models (fig-Forth, F83)
  889: @item
  890: Powerful. It should provide for all the things that are considered
  891: necessary today and even some that are not yet considered necessary.
  892: @item
  893: Efficient. It should not get the reputation of being exceptionally
  894: slow.
  895: @item
  896: Free.
  897: @item
  898: Available on many machines/easy to port.
  899: @end itemize
  900: 
  901: Have we achieved these goals? Gforth conforms to the ANS Forth
  902: standard. It may be considered a model, but we have not yet documented
  903: which parts of the model are stable and which parts we are likely to
  904: change. It certainly has not yet become a de facto standard, but it
  905: appears to be quite popular. It has some similarities to and some
  906: differences from previous models. It has some powerful features, but not
  907: yet everything that we envisioned. We certainly have achieved our
  908: execution speed goals (@pxref{Performance}).  It is free and available
  909: on many machines.
  910: 
  911: @menu
  912: * Gforth Extensions Sinful?::
  913: @end menu
  914: 
  915: @node Gforth Extensions Sinful?, , Goals, Goals
  916: @comment node-name,     next,           previous, up
  917: @section Is it a Sin to use Gforth Extensions?
  918: @cindex Gforth extensions
  919: 
  920: If you've been paying attention, you will have realised that there is an
  921: ANS (American National Standard) for Forth. As you read through the rest
  922: of this manual, you will see documentation for @i{Standard} words, and
  923: documentation for some appealing Gforth @i{extensions}. You might ask
  924: yourself the question: @i{``Given that there is a standard, would I be
  925: committing a sin to use (non-Standard) Gforth extensions?''}
  926: 
  927: The answer to that question is somewhat pragmatic and somewhat
  928: philosophical. Consider these points:
  929: 
  930: @itemize @bullet
  931: @item
  932: A number of the Gforth extensions can be implemented in ANS Forth using
  933: files provided in the @file{compat/} directory. These are mentioned in
  934: the text in passing.
  935: @item
  936: Forth has a rich historical precedent for programmers taking advantage
  937: of implementation-dependent features of their tools (for example,
  938: relying on a knowledge of the dictionary structure). Sometimes these
  939: techniques are necessary to extract every last bit of performance from
  940: the hardware, sometimes they are just a programming shorthand.
  941: @item
  942: The best way to break the rules is to know what the rules are. To learn
  943: the rules, there is no substitute for studying the text of the Standard
  944: itself. In particular, Appendix A of the Standard (@var{Rationale})
  945: provides a valuable insight into the thought processes of the technical
  946: committee.
  947: @item
  948: The best reason to break a rule is because you have to; because it's
  949: more productive to do that, because it makes your code run fast enough
  950: or because you can see no Standard way to achieve what you want to
  951: achieve.
  952: @end itemize
  953: 
  954: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
  955: analyse your program and determine what non-Standard definitions it
  956: relies upon.
  957: 
  958: 
  959: @c ******************************************************************
  960: @node Gforth Environment, Introduction, Goals, Top
  961: @chapter Gforth Environment
  962: @cindex Gforth environment
  963: 
  964: Note: ultimately, the gforth man page will be auto-generated from the
  965: material in this chapter.
  966: 
  967: @menu
  968: * Invoking Gforth::             Getting in
  969: * Leaving Gforth::              Getting out
  970: * Command-line editing::        
  971: * Upper and lower case::
  972: * Environment variables::       ..that affect how Gforth starts up
  973: * Gforth Files::                What gets installed and where
  974: @end menu
  975: 
  976: @xref{Image Files} for related information about the creation of images.
  977: 
  978: @comment ----------------------------------------------
  979: @node Invoking Gforth, Leaving Gforth, ,Gforth Environment
  980: @section Invoking Gforth
  981: @cindex invoking Gforth
  982: @cindex running Gforth
  983: @cindex command-line options
  984: @cindex options on the command line
  985: @cindex flags on the command line
  986: 
  987: Gforth is made up of two parts; an executable ``engine'' (named
  988: @file{gforth} or @file{gforth-fast}) and an image file. To start it, you
  989: will usually just say @code{gforth} -- this automatically loads the
  990: default image file @file{gforth.fi}. In many other cases the default
  991: Gforth image will be invoked like this:
  992: @example
  993: gforth [file | -e forth-code] ...
  994: @end example
  995: @noindent
  996: This interprets the contents of the files and the Forth code in the order they
  997: are given.
  998: 
  999: In addition to the @file{gforth} engine, there is also an engine called
 1000: @file{gforth-fast}, which is faster, but gives less informative error
 1001: messages (@pxref{Error messages}).
 1002: 
 1003: In general, the command line looks like this:
 1004: 
 1005: @example
 1006: gforth[-fast] [engine options] [image options]
 1007: @end example
 1008: 
 1009: The engine options must come before the rest of the command
 1010: line. They are:
 1011: 
 1012: @table @code
 1013: @cindex -i, command-line option
 1014: @cindex --image-file, command-line option
 1015: @item --image-file @i{file}
 1016: @itemx -i @i{file}
 1017: Loads the Forth image @i{file} instead of the default
 1018: @file{gforth.fi} (@pxref{Image Files}).
 1019: 
 1020: @cindex --appl-image, command-line option
 1021: @item --appl-image @i{file}
 1022: Loads the image @i{file} and leaves all further command-line arguments
 1023: to the image (instead of processing them as options).  This is useful
 1024: for building executable application images on Unix, built with
 1025: @code{gforthmi --application ...}.
 1026: 
 1027: @cindex --path, command-line option
 1028: @cindex -p, command-line option
 1029: @item --path @i{path}
 1030: @itemx -p @i{path}
 1031: Uses @i{path} for searching the image file and Forth source code files
 1032: instead of the default in the environment variable @code{GFORTHPATH} or
 1033: the path specified at installation time (e.g.,
 1034: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
 1035: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
 1036: 
 1037: @cindex --dictionary-size, command-line option
 1038: @cindex -m, command-line option
 1039: @cindex @i{size} parameters for command-line options
 1040: @cindex size of the dictionary and the stacks
 1041: @item --dictionary-size @i{size}
 1042: @itemx -m @i{size}
 1043: Allocate @i{size} space for the Forth dictionary space instead of
 1044: using the default specified in the image (typically 256K). The
 1045: @i{size} specification for this and subsequent options consists of
 1046: an integer and a unit (e.g.,
 1047: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
 1048: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
 1049: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
 1050: @code{e} is used.
 1051: 
 1052: @cindex --data-stack-size, command-line option
 1053: @cindex -d, command-line option
 1054: @item --data-stack-size @i{size}
 1055: @itemx -d @i{size}
 1056: Allocate @i{size} space for the data stack instead of using the
 1057: default specified in the image (typically 16K).
 1058: 
 1059: @cindex --return-stack-size, command-line option
 1060: @cindex -r, command-line option
 1061: @item --return-stack-size @i{size}
 1062: @itemx -r @i{size}
 1063: Allocate @i{size} space for the return stack instead of using the
 1064: default specified in the image (typically 15K).
 1065: 
 1066: @cindex --fp-stack-size, command-line option
 1067: @cindex -f, command-line option
 1068: @item --fp-stack-size @i{size}
 1069: @itemx -f @i{size}
 1070: Allocate @i{size} space for the floating point stack instead of
 1071: using the default specified in the image (typically 15.5K). In this case
 1072: the unit specifier @code{e} refers to floating point numbers.
 1073: 
 1074: @cindex --locals-stack-size, command-line option
 1075: @cindex -l, command-line option
 1076: @item --locals-stack-size @i{size}
 1077: @itemx -l @i{size}
 1078: Allocate @i{size} space for the locals stack instead of using the
 1079: default specified in the image (typically 14.5K).
 1080: 
 1081: @cindex -h, command-line option
 1082: @cindex --help, command-line option
 1083: @item --help
 1084: @itemx -h
 1085: Print a message about the command-line options
 1086: 
 1087: @cindex -v, command-line option
 1088: @cindex --version, command-line option
 1089: @item --version
 1090: @itemx -v
 1091: Print version and exit
 1092: 
 1093: @cindex --debug, command-line option
 1094: @item --debug
 1095: Print some information useful for debugging on startup.
 1096: 
 1097: @cindex --offset-image, command-line option
 1098: @item --offset-image
 1099: Start the dictionary at a slightly different position than would be used
 1100: otherwise (useful for creating data-relocatable images,
 1101: @pxref{Data-Relocatable Image Files}).
 1102: 
 1103: @cindex --no-offset-im, command-line option
 1104: @item --no-offset-im
 1105: Start the dictionary at the normal position.
 1106: 
 1107: @cindex --clear-dictionary, command-line option
 1108: @item --clear-dictionary
 1109: Initialize all bytes in the dictionary to 0 before loading the image
 1110: (@pxref{Data-Relocatable Image Files}).
 1111: 
 1112: @cindex --die-on-signal, command-line-option
 1113: @item --die-on-signal
 1114: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
 1115: or the segmentation violation SIGSEGV) by translating it into a Forth
 1116: @code{THROW}. With this option, Gforth exits if it receives such a
 1117: signal. This option is useful when the engine and/or the image might be
 1118: severely broken (such that it causes another signal before recovering
 1119: from the first); this option avoids endless loops in such cases.
 1120: @end table
 1121: 
 1122: @cindex loading files at startup
 1123: @cindex executing code on startup
 1124: @cindex batch processing with Gforth
 1125: As explained above, the image-specific command-line arguments for the
 1126: default image @file{gforth.fi} consist of a sequence of filenames and
 1127: @code{-e @var{forth-code}} options that are interpreted in the sequence
 1128: in which they are given. The @code{-e @var{forth-code}} or
 1129: @code{--evaluate @var{forth-code}} option evaluates the Forth
 1130: code. This option takes only one argument; if you want to evaluate more
 1131: Forth words, you have to quote them or use @code{-e} several times. To exit
 1132: after processing the command line (instead of entering interactive mode)
 1133: append @code{-e bye} to the command line.
 1134: 
 1135: @cindex versions, invoking other versions of Gforth
 1136: If you have several versions of Gforth installed, @code{gforth} will
 1137: invoke the version that was installed last. @code{gforth-@i{version}}
 1138: invokes a specific version. You may want to use the option
 1139: @code{--path}, if your environment contains the variable
 1140: @code{GFORTHPATH}.
 1141: 
 1142: Not yet implemented:
 1143: On startup the system first executes the system initialization file
 1144: (unless the option @code{--no-init-file} is given; note that the system
 1145: resulting from using this option may not be ANS Forth conformant). Then
 1146: the user initialization file @file{.gforth.fs} is executed, unless the
 1147: option @code{--no-rc} is given; this file is first searched in @file{.},
 1148: then in @file{~}, then in the normal path (see above).
 1149: 
 1150: 
 1151: 
 1152: @comment ----------------------------------------------
 1153: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
 1154: @section Leaving Gforth
 1155: @cindex Gforth - leaving
 1156: @cindex leaving Gforth
 1157: 
 1158: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
 1159: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
 1160: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
 1161: data are discarded. @xref{Image Files} for ways of saving the state of
 1162: the system before leaving Gforth.
 1163: 
 1164: doc-bye
 1165: 
 1166: @comment ----------------------------------------------
 1167: @node Command-line editing, Upper and lower case,Leaving Gforth,Gforth Environment
 1168: @section Command-line editing
 1169: @cindex command-line editing
 1170: 
 1171: Gforth maintains a history file that records every line that you type to
 1172: the text interpreter. This file is preserved between sessions, and is
 1173: used to provide a command-line recall facility; if you type ctrl-P
 1174: repeatedly you can recall successively older commands from this (or
 1175: previous) session(s). The full list of command-line editing facilities is:
 1176: 
 1177: @comment use @table? - anton
 1178: @itemize @bullet
 1179: @item
 1180: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
 1181: commands from the history buffer.
 1182: @item
 1183: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
 1184: from the history buffer.
 1185: @item
 1186: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
 1187: @item
 1188: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
 1189: @item
 1190: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
 1191: closing up the line.
 1192: @item
 1193: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
 1194: @item
 1195: @kbd{Ctrl-a} to move the cursor to the start of the line.
 1196: @item
 1197: @kbd{Ctrl-e} to move the cursor to the end of the line.
 1198: @item
 1199: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
 1200: line.
 1201: @item
 1202: @key{TAB} to step through all possible full-word completions of the word
 1203: currently being typed.
 1204: @item
 1205: @kbd{Ctrl-d} at the start of the line to terminate Gforth (gracefully,
 1206: using @code{bye}).
 1207: @end itemize
 1208: 
 1209: When editing, displayable characters are inserted to the left of the
 1210: cursor position; the line is always in ``insert'' (as opposed to
 1211: ``overstrike'') mode.
 1212: 
 1213: @cindex history file
 1214: @cindex @file{.gforth-history}
 1215: On Unix systems, the history file is @file{~/.gforth-history} by
 1216: default@footnote{i.e. it is stored in the user's home directory.}. You
 1217: can find out the name and location of your history file using:
 1218: 
 1219: @example 
 1220: history-file type \ Unix-class systems
 1221: 
 1222: history-file type \ Other systems
 1223: history-dir  type
 1224: @end example
 1225: 
 1226: If you enter long definitions by hand, you can use a text editor to
 1227: paste them out of the history file into a Forth source file for reuse at
 1228: a later time.
 1229: 
 1230: Gforth never trims the size of the history file, so you should do this
 1231: periodically, if necessary.
 1232: 
 1233: @comment this is all defined in history.fs
 1234: 
 1235: 
 1236: 
 1237: @comment ----------------------------------------------
 1238: @node Upper and lower case, Environment variables,Command-line editing,Gforth Environment
 1239: @section Upper and lower case
 1240: @cindex case-sensitivity
 1241: @cindex upper and lower case
 1242: 
 1243: Gforth is case-insensitive, so you can enter definitions and invoke
 1244: Standard words using upper, lower or mixed case (however,
 1245: @pxref{core-idef, Implementation-defined options, Implementation-defined
 1246: options}).
 1247: 
 1248: ANS Forth only @i{requires} implementations to recognise Standard words
 1249: when they are typed entirely in upper case. Therefore, a Standard
 1250: program must use upper case for all Standard words. You can use whatever
 1251: case you like for words that you define, but in a standard program you
 1252: have to use the words in the same case that you defined them.
 1253: 
 1254: Gforth supports case sensitivity through @code{table}s (case-sensitive
 1255: wordlists, @pxref{Word Lists}).
 1256: 
 1257: Two people have asked how to convert Gforth to case sensitivity; while
 1258: we think this is a bad idea, you can change all wordlists into tables
 1259: like this:
 1260: 
 1261: @example
 1262: ' table-find forth-wordlist wordlist-map @ !
 1263: @end example
 1264: 
 1265: Note that you now have to type the predefined words in the same case
 1266: that we defined them, which are varying.  You may want to convert them
 1267: to your favourite case before doing this operation (I won't explain how,
 1268: because if you are even contemplating to do this, you'd better have
 1269: enough knowledge of Forth systems to know this already).
 1270: 
 1271: @comment ----------------------------------------------
 1272: @node Environment variables, Gforth Files, Upper and lower case,Gforth Environment
 1273: @section Environment variables
 1274: @cindex environment variables
 1275: 
 1276: Gforth uses these environment variables:
 1277: 
 1278: @itemize @bullet
 1279: @item
 1280: @cindex GFORTHHIST - environment variable
 1281: GFORTHHIST - (Unix systems only) specifies the directory in which to
 1282: open/create the history file, @file{.gforth-history}. Default:
 1283: @code{$HOME}.
 1284: 
 1285: @item
 1286: @cindex GFORTHPATH - environment variable
 1287: GFORTHPATH - specifies the path used when searching for the gforth image file and
 1288: for Forth source-code files.
 1289: 
 1290: @item
 1291: @cindex GFORTH - environment variable
 1292: GFORTH - used by @file{gforthmi} @xref{gforthmi}.
 1293: 
 1294: @item
 1295: @cindex GFORTHD - environment variable
 1296: GFORTHD - used by @file{gforthmi} @xref{gforthmi}.
 1297: 
 1298: @item
 1299: @cindex TMP, TEMP - environment variable
 1300: TMP, TEMP - (non-Unix systems only) used as a potential location for the
 1301: history file.
 1302: @end itemize
 1303: 
 1304: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
 1305: @comment mentioning these.
 1306: 
 1307: All the Gforth environment variables default to sensible values if they
 1308: are not set.
 1309: 
 1310: 
 1311: @comment ----------------------------------------------
 1312: @node Gforth Files, ,Environment variables,Gforth Environment
 1313: @section Gforth files
 1314: @cindex Gforth files
 1315: 
 1316: When you Gforth on a Unix system in the default places, it installs
 1317: files in these locations:
 1318: 
 1319: @itemize @bullet
 1320: @item
 1321: @file{/usr/local/bin/gforth}
 1322: @item
 1323: @file{/usr/local/bin/gforthmi}
 1324: @item
 1325: @file{/usr/local/man/man1/gforth.1} - man page.
 1326: @item
 1327: @file{/usr/local/info} - the Info version of this manual.
 1328: @item
 1329: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
 1330: @item
 1331: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
 1332: @item
 1333: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
 1334: @item
 1335: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
 1336: @end itemize
 1337: 
 1338: You can select different places for installation by using
 1339: @code{configure} options (listed with @code{configure --help}).
 1340: 
 1341: @c ******************************************************************
 1342: @node Introduction, Words, Gforth Environment, Top
 1343: @comment node-name,     next,           previous, up
 1344: @chapter An Introduction to ANS Forth
 1345: @cindex Forth - an introduction
 1346: 
 1347: The primary purpose of this manual is to document Gforth. However, since
 1348: Forth is not a widely-known language and there is a lack of up-to-date
 1349: teaching material, it seems worthwhile to provide some introductory
 1350: material. @xref{Forth-related information} for other sources of Forth-related
 1351: information.
 1352: 
 1353: The examples in this section should work on any ANS Forth; the
 1354: output shown was produced using Gforth. Each example attempts to
 1355: reproduce the exact output that Gforth produces. If you try out the
 1356: examples (and you should), what you should type is shown @kbd{like this}
 1357: and Gforth's response is shown @code{like this}. The single exception is
 1358: that, where the example shows @key{RET} it means that you should
 1359: press the ``carriage return'' key. Unfortunately, some output formats for
 1360: this manual cannot show the difference between @kbd{this} and
 1361: @code{this} which will make trying out the examples harder (but not
 1362: impossible).
 1363: 
 1364: Forth is an unusual language. It provides an interactive development
 1365: environment which includes both an interpreter and compiler. Forth
 1366: programming style encourages you to break a problem down into many
 1367: @cindex factoring
 1368: small fragments (@dfn{factoring}), and then to develop and test each
 1369: fragment interactively. Forth advocates assert that breaking the
 1370: edit-compile-test cycle used by conventional programming languages can
 1371: lead to great productivity improvements.
 1372: 
 1373: @menu
 1374: * Introducing the Text Interpreter::
 1375: * Stacks and Postfix notation::
 1376: * Your first definition::
 1377: * How does that work?::
 1378: * Forth is written in Forth::
 1379: * Review - elements of a Forth system::
 1380: * Where to go next::
 1381: * Exercises::
 1382: @end menu
 1383: 
 1384: @comment ----------------------------------------------
 1385: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
 1386: @section Introducing the Text Interpreter
 1387: @cindex text interpreter
 1388: @cindex outer interpreter
 1389: 
 1390: @c IMO this is too detailed and the pace is too slow for
 1391: @c an introduction.  If you know German, take a look at
 1392: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
 1393: @c to see how I do it - anton 
 1394: 
 1395: When you invoke the Forth image, you will see a startup banner printed
 1396: and nothing else (if you have Gforth installed on your system, try
 1397: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
 1398: its command line interpreter, which is called the @dfn{Text Interpreter}
 1399: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
 1400: about the text interpreter as you read through this chapter, but
 1401: @pxref{The Text Interpreter} for more detail).
 1402: 
 1403: Although it's not obvious, Forth is actually waiting for your
 1404: input. Type a number and press the @key{RET} key:
 1405: 
 1406: @example
 1407: @kbd{45@key{RET}}  ok
 1408: @end example
 1409: 
 1410: Rather than give you a prompt to invite you to input something, the text
 1411: interpreter prints a status message @i{after} it has processed a line
 1412: of input. The status message in this case (``@code{ ok}'' followed by
 1413: carriage-return) indicates that the text interpreter was able to process
 1414: all of your input successfully. Now type something illegal:
 1415: 
 1416: @example
 1417: @kbd{qwer341@key{RET}}
 1418: :1: Undefined word
 1419: qwer341
 1420: ^^^^^^^
 1421: $400D2BA8 Bounce
 1422: $400DBDA8 no.extensions
 1423: @end example
 1424: 
 1425: The exact text, other than the ``Undefined word'' may differ slightly on
 1426: your system, but the effect is the same; when the text interpreter
 1427: detects an error, it discards any remaining text on a line, resets
 1428: certain internal state and prints an error message. @xref{Error
 1429: messages} for a detailed description of error messages.
 1430: 
 1431: The text interpreter waits for you to press carriage-return, and then
 1432: processes your input line. Starting at the beginning of the line, it
 1433: breaks the line into groups of characters separated by spaces. For each
 1434: group of characters in turn, it makes two attempts to do something:
 1435: 
 1436: @itemize @bullet
 1437: @item
 1438: It tries to treat it as a command. It does this by searching a @dfn{name
 1439: dictionary}. If the group of characters matches an entry in the name
 1440: dictionary, the name dictionary provides the text interpreter with
 1441: information that allows the text interpreter perform some actions. In
 1442: Forth jargon, we say that the group
 1443: @cindex word
 1444: @cindex definition
 1445: @cindex execution token
 1446: @cindex xt
 1447: of characters names a @dfn{word}, that the dictionary search returns an
 1448: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
 1449: word, and that the text interpreter executes the xt. Often, the terms
 1450: @dfn{word} and @dfn{definition} are used interchangeably.
 1451: @item
 1452: If the text interpreter fails to find a match in the name dictionary, it
 1453: tries to treat the group of characters as a number in the current number
 1454: base (when you start up Forth, the current number base is base 10). If
 1455: the group of characters legitimately represents a number, the text
 1456: interpreter pushes the number onto a stack (we'll learn more about that
 1457: in the next section).
 1458: @end itemize
 1459: 
 1460: If the text interpreter is unable to do either of these things with any
 1461: group of characters, it discards the group of characters and the rest of
 1462: the line, then prints an error message. If the text interpreter reaches
 1463: the end of the line without error, it prints the status message ``@code{ ok}''
 1464: followed by carriage-return.
 1465: 
 1466: This is the simplest command we can give to the text interpreter:
 1467: 
 1468: @example
 1469: @key{RET}  ok
 1470: @end example
 1471: 
 1472: The text interpreter did everything we asked it to do (nothing) without
 1473: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
 1474: command:
 1475: 
 1476: @example
 1477: @kbd{12 dup fred dup@key{RET}}
 1478: :1: Undefined word
 1479: 12 dup fred dup
 1480:        ^^^^
 1481: $400D2BA8 Bounce
 1482: $400DBDA8 no.extensions
 1483: @end example
 1484: 
 1485: When you press the carriage-return key, the text interpreter starts to
 1486: work its way along the line:
 1487: 
 1488: @itemize @bullet
 1489: @item
 1490: When it gets to the space after the @code{2}, it takes the group of
 1491: characters @code{12} and looks them up in the name
 1492: dictionary@footnote{We can't tell if it found them or not, but assume
 1493: for now that it did not}. There is no match for this group of characters
 1494: in the name dictionary, so it tries to treat them as a number. It is
 1495: able to do this successfully, so it puts the number, 12, ``on the stack''
 1496: (whatever that means).
 1497: @item
 1498: The text interpreter resumes scanning the line and gets the next group
 1499: of characters, @code{dup}. It looks it up in the name dictionary and
 1500: (you'll have to take my word for this) finds it, and executes the word
 1501: @code{dup} (whatever that means).
 1502: @item
 1503: Once again, the text interpreter resumes scanning the line and gets the
 1504: group of characters @code{fred}. It looks them up in the name
 1505: dictionary, but can't find them. It tries to treat them as a number, but
 1506: they don't represent any legal number.
 1507: @end itemize
 1508: 
 1509: At this point, the text interpreter gives up and prints an error
 1510: message. The error message shows exactly how far the text interpreter
 1511: got in processing the line. In particular, it shows that the text
 1512: interpreter made no attempt to do anything with the final character
 1513: group, @code{dup}, even though we have good reason to believe that the
 1514: text interpreter would have no problem looking that word up and
 1515: executing it a second time.
 1516: 
 1517: 
 1518: @comment ----------------------------------------------
 1519: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
 1520: @section Stacks, postfix notation and parameter passing
 1521: @cindex text interpreter
 1522: @cindex outer interpreter
 1523: 
 1524: In procedural programming languages (like C and Pascal), the
 1525: building-block of programs is the @dfn{function} or @dfn{procedure}. These
 1526: functions or procedures are called with @dfn{explicit parameters}. For
 1527: example, in C we might write:
 1528: 
 1529: @example
 1530: total = total + new_volume(length,height,depth);
 1531: @end example
 1532: 
 1533: @noindent
 1534: where new_volume is a function-call to another piece of code, and total,
 1535: length, height and depth are all variables. length, height and depth are
 1536: parameters to the function-call.
 1537: 
 1538: In Forth, the equivalent of the function or procedure is the
 1539: @dfn{definition} and parameters are implicitly passed between
 1540: definitions using a shared stack that is visible to the
 1541: programmer. Although Forth does support variables, the existence of the
 1542: stack means that they are used far less often than in most other
 1543: programming languages. When the text interpreter encounters a number, it
 1544: will place (@dfn{push}) it on the stack. There are several stacks (the
 1545: actual number is implementation-dependent ...) and the particular stack
 1546: used for any operation is implied unambiguously by the operation being
 1547: performed. The stack used for all integer operations is called the @dfn{data
 1548: stack} and, since this is the stack used most commonly, references to
 1549: ``the data stack'' are often abbreviated to ``the stack''.
 1550: 
 1551: The stacks have a last-in, first-out (LIFO) organisation. If you type:
 1552: 
 1553: @example
 1554: @kbd{1 2 3@key{RET}}  ok
 1555: @end example
 1556: 
 1557: Then this instructs the text interpreter to placed three numbers on the
 1558: (data) stack. An analogy for the behaviour of the stack is to take a
 1559: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
 1560: the table. The 3 was the last card onto the pile (``last-in'') and if
 1561: you take a card off the pile then, unless you're prepared to fiddle a
 1562: bit, the card that you take off will be the 3 (``first-out''). The
 1563: number that will be first-out of the stack is called the @dfn{top of
 1564: stack}, which
 1565: @cindex TOS definition
 1566: is often abbreviated to @dfn{TOS}.
 1567: 
 1568: To understand how parameters are passed in Forth, consider the
 1569: behaviour of the definition @code{+} (pronounced ``plus''). You will not
 1570: be surprised to learn that this definition performs addition. More
 1571: precisely, it adds two number together and produces a result. Where does
 1572: it get the two numbers from? It takes the top two numbers off the
 1573: stack. Where does it place the result? On the stack. You can act-out the
 1574: behaviour of @code{+} with your playing cards like this:
 1575: 
 1576: @itemize @bullet
 1577: @item
 1578: Pick up two cards from the stack on the table
 1579: @item
 1580: Stare at them intently and ask yourself ``what @i{is} the sum of these two
 1581: numbers''
 1582: @item
 1583: Decide that the answer is 5
 1584: @item
 1585: Shuffle the two cards back into the pack and find a 5
 1586: @item
 1587: Put a 5 on the remaining ace that's on the table.
 1588: @end itemize
 1589: 
 1590: If you don't have a pack of cards handy but you do have Forth running,
 1591: you can use the definition @code{.s} to show the current state of the stack,
 1592: without affecting the stack. Type:
 1593: 
 1594: @example
 1595: @kbd{clearstack 1 2 3@key{RET}} ok
 1596: @kbd{.s@key{RET}} <3> 1 2 3  ok
 1597: @end example
 1598: 
 1599: The text interpreter looks up the word @code{clearstack} and executes
 1600: it; it tidies up the stack and removes any entries that may have been
 1601: left on it by earlier examples. The text interpreter pushes each of the
 1602: three numbers in turn onto the stack. Finally, the text interpreter
 1603: looks up the word @code{.s} and executes it. The effect of executing
 1604: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
 1605: followed by a list of all the items on the stack; the item on the far
 1606: right-hand side is the TOS.
 1607: 
 1608: You can now type:
 1609: 
 1610: @example
 1611: @kbd{+ .s@key{RET}} <2> 1 5  ok
 1612: @end example
 1613: 
 1614: @noindent
 1615: which is correct; there are now 2 items on the stack and the result of
 1616: the addition is 5.
 1617: 
 1618: If you're playing with cards, try doing a second addition: pick up the
 1619: two cards, work out that their sum is 6, shuffle them into the pack,
 1620: look for a 6 and place that on the table. You now have just one item on
 1621: the stack. What happens if you try to do a third addition? Pick up the
 1622: first card, pick up the second card -- ah! There is no second card. This
 1623: is called a @dfn{stack underflow} and consitutes an error. If you try to
 1624: do the same thing with Forth it will report an error (probably a Stack
 1625: Underflow or an Invalid Memory Address error).
 1626: 
 1627: The opposite situation to a stack underflow is a @dfn{stack overflow},
 1628: which simply accepts that there is a finite amount of storage space
 1629: reserved for the stack. To stretch the playing card analogy, if you had
 1630: enough packs of cards and you piled the cards up on the table, you would
 1631: eventually be unable to add another card; you'd hit the ceiling. Gforth
 1632: allows you to set the maximum size of the stacks. In general, the only
 1633: time that you will get a stack overflow is because a definition has a
 1634: bug in it and is generating data on the stack uncontrollably.
 1635: 
 1636: There's one final use for the playing card analogy. If you model your
 1637: stack using a pack of playing cards, the maximum number of items on
 1638: your stack will be 52 (I assume you didn't use the Joker). The maximum
 1639: @i{value} of any item on the stack is 13 (the King). In fact, the only
 1640: possible numbers are positive integer numbers 1 through 13; you can't
 1641: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
 1642: think about some of the cards, you can accommodate different
 1643: numbers. For example, you could think of the Jack as representing 0,
 1644: the Queen as representing -1 and the King as representing -2. Your
 1645: *range* remains unchanged (you can still only represent a total of 13
 1646: numbers) but the numbers that you can represent are -2 through 10.
 1647: 
 1648: In that analogy, the limit was the amount of information that a single
 1649: stack entry could hold, and Forth has a similar limit. In Forth, the
 1650: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
 1651: implementation dependent and affects the maximum value that a stack
 1652: entry can hold. A Standard Forth provides a cell size of at least
 1653: 16-bits, and most desktop systems use a cell size of 32-bits.
 1654: 
 1655: Forth does not do any type checking for you, so you are free to
 1656: manipulate and combine stack items in any way you wish. A convenient way
 1657: of treating stack items is as 2's complement signed integers, and that
 1658: is what Standard words like @code{+} do. Therefore you can type:
 1659: 
 1660: @example
 1661: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
 1662: @end example
 1663: 
 1664: If you use numbers and definitions like @code{+} in order to turn Forth
 1665: into a great big pocket calculator, you will realise that it's rather
 1666: different from a normal calculator. Rather than typing 2 + 3 = you had
 1667: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
 1668: result). The terminology used to describe this difference is to say that
 1669: your calculator uses @dfn{Infix Notation} (parameters and operators are
 1670: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
 1671: operators are separate), also called @dfn{Reverse Polish Notation}.
 1672: 
 1673: Whilst postfix notation might look confusing to begin with, it has
 1674: several important advantages:
 1675: 
 1676: @itemize @bullet
 1677: @item
 1678: it is unambiguous
 1679: @item
 1680: it is more concise
 1681: @item
 1682: it fits naturally with a stack-based system
 1683: @end itemize
 1684: 
 1685: To examine these claims in more detail, consider these sums:
 1686: 
 1687: @example
 1688: 6 + 5 * 4 =
 1689: 4 * 5 + 6 =
 1690: @end example
 1691: 
 1692: If you're just learning maths or your maths is very rusty, you will
 1693: probably come up with the answer 44 for the first and 26 for the
 1694: second. If you are a bit of a whizz at maths you will remember the
 1695: @i{convention} that multiplication takes precendence over addition, and
 1696: you'd come up with the answer 26 both times. To explain the answer 26
 1697: to someone who got the answer 44, you'd probably rewrite the first sum
 1698: like this:
 1699: 
 1700: @example
 1701: 6 + (5 * 4) =
 1702: @end example
 1703: 
 1704: If what you really wanted was to perform the addition before the
 1705: multiplication, you would have to use parentheses to force it.
 1706: 
 1707: If you did the first two sums on a pocket calculator you would probably
 1708: get the right answers, unless you were very cautious and entered them using
 1709: these keystroke sequences:
 1710: 
 1711: 6 + 5 = * 4 =
 1712: 4 * 5 = + 6 =
 1713: 
 1714: Postfix notation is unambiguous because the order that the operators
 1715: are applied is always explicit; that also means that parentheses are
 1716: never required. The operators are @i{active} (the act of quoting the
 1717: operator makes the operation occur) which removes the need for ``=''.
 1718: 
 1719: The sum 6 + 5 * 4 can be written (in postfix notation) in two
 1720: equivalent ways:
 1721: 
 1722: @example
 1723: 6 5 4 * +      or:
 1724: 5 4 * 6 +
 1725: @end example
 1726: 
 1727: An important thing that you should notice about this notation is that
 1728: the @i{order} of the numbers does not change; if you want to subtract
 1729: 2 from 10 you type @code{10 2 -}.
 1730: 
 1731: The reason that Forth uses postfix notation is very simple to explain: it
 1732: makes the implementation extremely simple, and it follows naturally from
 1733: using the stack as a mechanism for passing parameters. Another way of
 1734: thinking about this is to realise that all Forth definitions are
 1735: @i{active}; they execute as they are encountered by the text
 1736: interpreter. The result of this is that the syntax of Forth is trivially
 1737: simple.
 1738: 
 1739: 
 1740: 
 1741: @comment ----------------------------------------------
 1742: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
 1743: @section Your first Forth definition
 1744: @cindex first definition
 1745: 
 1746: Until now, the examples we've seen have been trivial; we've just been
 1747: using Forth as a bigger-than-pocket calculator. Also, each calculation
 1748: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
 1749: again@footnote{That's not quite true. If you press the up-arrow key on
 1750: your keyboard you should be able to scroll back to any earlier command,
 1751: edit it and re-enter it.} In this section we'll see how to add new
 1752: words to Forth's vocabulary.
 1753: 
 1754: The easiest way to create a new word is to use a @dfn{colon
 1755: definition}. We'll define a few and try them out before worrying too
 1756: much about how they work. Try typing in these examples; be careful to
 1757: copy the spaces accurately:
 1758: 
 1759: @example
 1760: : add-two 2 + . ;
 1761: : greet ." Hello and welcome" ;
 1762: : demo 5 add-two ;
 1763: @end example
 1764: 
 1765: @noindent
 1766: Now try them out:
 1767: 
 1768: @example
 1769: @kbd{greet@key{RET}} Hello and welcome  ok
 1770: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
 1771: @kbd{4 add-two@key{RET}} 6  ok
 1772: @kbd{demo@key{RET}} 7  ok
 1773: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
 1774: @end example
 1775: 
 1776: The first new thing that we've introduced here is the pair of words
 1777: @code{:} and @code{;}. These are used to start and terminate a new
 1778: definition, respectively. The first word after the @code{:} is the name
 1779: for the new definition.
 1780: 
 1781: As you can see from the examples, a definition is built up of words that
 1782: have already been defined; Forth makes no distinction between
 1783: definitions that existed when you started the system up, and those that
 1784: you define yourself.
 1785: 
 1786: The examples also introduce the words @code{.} (dot), @code{."}
 1787: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
 1788: the stack and displays it. It's like @code{.s} except that it only
 1789: displays the top item of the stack and it is destructive; after it has
 1790: executed, the number is no longer on the stack. There is always one
 1791: space printed after the number, and no spaces before it. Dot-quote
 1792: defines a string (a sequence of characters) that will be printed when
 1793: the word is executed. The string can contain any printable characters
 1794: except @code{"}. A @code{"} has a special function; it is not a Forth
 1795: word but it acts as a delimiter (the way that delimiters work is
 1796: described in the next section). Finally, @code{dup} duplicates the value
 1797: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
 1798: 
 1799: We already know that the text interpreter searches through the
 1800: dictionary to locate names. If you've followed the examples earlier, you
 1801: will already have a definition called @code{add-two}. Lets try modifying
 1802: it by typing in a new definition:
 1803: 
 1804: @example
 1805: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
 1806: @end example
 1807: 
 1808: Forth recognised that we were defining a word that already exists, and
 1809: printed a message to warn us of that fact. Let's try out the new
 1810: definition:
 1811: 
 1812: @example
 1813: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
 1814: @end example
 1815: 
 1816: @noindent
 1817: All that we've actually done here, though, is to create a new
 1818: definition, with a particular name. The fact that there was already a
 1819: definition with the same name did not make any difference to the way
 1820: that the new definition was created (except that Forth printed a warning
 1821: message). The old definition of add-two still exists (try @code{demo}
 1822: again to see that this is true). Any new definition will use the new
 1823: definition of @code{add-two}, but old definitions continue to use the
 1824: version that already existed at the time that they were @code{compiled}.
 1825: 
 1826: Before you go on to the next section, try defining and redefining some
 1827: words of your own.
 1828: 
 1829: @comment ----------------------------------------------
 1830: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
 1831: @section How does that work?
 1832: @cindex parsing words
 1833: 
 1834: @c That's pretty deep (IMO way too deep) for an introduction. - anton
 1835: 
 1836: @c Is it a good idea to talk about the interpretation semantics of a
 1837: @c number? We don't have an xt to go along with it. - anton
 1838: 
 1839: @c Now that I have eliminated execution semantics, I wonder if it would not
 1840: @c be better to keep them (or add run-time semantics), to make it easier to
 1841: @c explain what compilation semantics usually does. - anton
 1842: 
 1843: Now we're going to take another look at the definition of @code{add-two}
 1844: from the previous section. From our knowledge of the way that the text
 1845: interpreter works, we would have expected this result when we tried to
 1846: define @code{add-two}:
 1847: 
 1848: @example
 1849: @kbd{: add-two 2 + . " ;@key{RET}}
 1850:   ^^^^^^^
 1851: Error: Undefined word
 1852: @end example
 1853: 
 1854: The reason that this didn't happen is bound up in the way that @code{:}
 1855: works. The word @code{:} does two special things. The first special
 1856: thing that it does prevents the text interpreter from ever seeing the
 1857: characters @code{add-two}. The text interpreter uses a variable called
 1858: @cindex modifying >IN
 1859: @code{>IN} (pronounced ''to-in'') to keep track of where it is in the
 1860: input line. When it encounters the word @code{:} it behaves in exactly
 1861: the same way as it does for any other word; it looks it up in the name
 1862: dictionary, finds its xt and executes it. When @code{:} executes, it
 1863: looks at the input buffer, finds the word @code{add-two} and advances the
 1864: value of @code{>IN} to point past it. It then does some other stuff
 1865: associated with creating the new definition (including creating an entry
 1866: for @code{add-two} in the name dictionary). When the execution of @code{:}
 1867: completes, control returns to the text interpreter, which is oblivious
 1868: to the fact that it has been tricked into ignoring part of the input
 1869: line.
 1870: 
 1871: @cindex parsing words
 1872: Words like @code{:} -- words that advance the value of @code{>IN} and so
 1873: prevent the text interpreter from acting on the whole of the input line
 1874: -- are called @dfn{parsing words}.
 1875: 
 1876: @cindex @code{state} - effect on the text interpreter
 1877: @cindex text interpreter - effect of state
 1878: The second special thing that @code{:} does is change the value of a
 1879: variable called @code{state}, which affects the way that the text
 1880: interpreter behaves. When Gforth starts up, @code{state} has the value
 1881: 0, and the text interpreter is said to be @dfn{interpreting}. During a
 1882: colon definition (started with @code{:}), @code{state} is set to -1 and
 1883: the text interpreter is said to be @dfn{compiling}. The word @code{;}
 1884: ends the definition -- one of the things that it does is to change the
 1885: value of @code{state} back to 0.
 1886: 
 1887: We have already seen how the text interpreter behaves when it is
 1888: interpreting; it looks for each character sequence in the dictionary,
 1889: finds its xt and executes it, or it converts it to a number and pushes
 1890: it onto the stack, or it fails to do either and generates an error.
 1891: 
 1892: When the text interpreter is compiling, its behaviour is slightly
 1893: different; it still looks for each character sequence in the dictionary
 1894: and finds it, or converts it to a number, or fails to do either and
 1895: generates an error.  But instead of the execution token of a word it
 1896: finds and executes the compilation token.  For most words executing the
 1897: compilation token results in laying down (@dfn{compiling}) the execution
 1898: token, i.e., some magic to make that xt or number get executed or pushed
 1899: at a later time; at the time that @code{add-two} is
 1900: @dfn{executed}. Therefore, when you execute @code{add-two} its
 1901: @dfn{run-time effect} is exactly the same as if you had typed @code{2 +
 1902: .} outside of a definition, and pressed carriage-return.
 1903: 
 1904: In Forth, every word or number can be described in terms of two
 1905: properties:
 1906: 
 1907: @itemize @bullet
 1908: @item
 1909: Its @dfn{interpretation semantics}, represented by the execution token.
 1910: @item
 1911: Its @dfn{compilation semantics}, represented by the compilation token.
 1912: @end itemize
 1913: 
 1914: The value of @code{state} determines whether the text interpreter will
 1915: use the compilation or interpretation semantics of a word or number that
 1916: it encounters.
 1917: 
 1918: @itemize @bullet
 1919: @item
 1920: @cindex interpretation semantics
 1921: When the text interpreter encounters a word or number in @dfn{interpret}
 1922: state, it performs the @dfn{interpretation semantics} of the word or
 1923: number.
 1924: @item
 1925: @cindex compilation semantics
 1926: When the text interpreter encounters a word or number in @dfn{compile}
 1927: state, it performs the @dfn{compilation semantics} of the word or
 1928: number.
 1929: @end itemize
 1930: 
 1931: @noindent
 1932: Numbers are always treated in a fixed way:
 1933: 
 1934: @itemize @bullet
 1935: @item
 1936: When the number is @dfn{interpreted}, its behaviour is to push the number onto the stack.
 1937: @item
 1938: When the number is @dfn{compiled}, a piece of code is appended to the
 1939: current definition that pushes the number when it runs. (In other words,
 1940: the compilation semantics of a number are to postpone its interpretation
 1941: semantics until the run-time of the definition that it is being compiled
 1942: into.)
 1943: @end itemize
 1944: 
 1945: The behaviour of a word is not so regular, but most have @i{default
 1946: compilation semantics} which means that they behave like this:
 1947: 
 1948: @itemize @bullet
 1949: @item
 1950: The @dfn{interpretation semantics} of the word are to do something useful.
 1951: @item
 1952: The @dfn{compilation semantics} of the word are to append its
 1953: @dfn{interpretation semantics} to the current definition (so that its
 1954: run-time behaviour is to do something useful).
 1955: @end itemize
 1956: 
 1957: @cindex immediate words
 1958: The actual behaviour of any particular word depends upon the way in
 1959: which it was defined. When the text interpreter finds the word in the
 1960: name dictionary, it not only retrieves the xt for the word, it also
 1961: retrieves some flags: the @dfn{compile-only} flag and the @dfn{immediate
 1962: flag}. The compile-only flag indicates that the word has no
 1963: interpretation semantics (the run-time behaviour for the default
 1964: compilation semantics is not affected by this flag, however); any
 1965: attempt to interpret a word that has the compile-only flag set will
 1966: generate an error (for example, @code{IF} has no interpretation
 1967: semantics). The immediate flag changes the compilation semantics of the
 1968: word; if it is set, the compilation semantics are equal to the
 1969: interpretation semantics (again ignoring the compile-only flag).  it. In
 1970: other words, these so-called @dfn{immediate} words behave like this:
 1971: 
 1972: @itemize @bullet
 1973: @item
 1974: The @dfn{interpretation semantics} of the word are to do something useful.
 1975: @item
 1976: The @dfn{compilation semantics} of the word are to do something useful
 1977: (and actually the same thing); i.e., it is executed during compilation.
 1978: @end itemize
 1979: 
 1980: This example shows the difference between an immediate and a
 1981: non-immediate word:
 1982: 
 1983: @example
 1984: : show-state state @@ . ;
 1985: : show-state-now show-state ; immediate
 1986: : word1 show-state ;
 1987: : word2 show-state-now ;
 1988: @end example
 1989: 
 1990: The word @code{immediate} after the definition of @code{show-state-now}
 1991: makes that word an immediate word. These definitions introduce a new
 1992: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
 1993: variable, and leaves it on the stack. Therefore, the behaviour of
 1994: @code{show-state} is to print a number that represents the current value
 1995: of @code{state}.
 1996: 
 1997: When you execute @code{word1}, it prints the number 0, indicating that
 1998: the system is interpreting. When the text interpreter compiled the
 1999: definition of @code{word1}, it encountered @code{show-state} whose
 2000: compilation semantics are to append its interpretation semantics to the
 2001: current definition. When you execute @code{word1}, it performs the
 2002: interpretation semantics of @code{show-state}.  At the time that @code{word1}
 2003: (and therefore @code{show-state}) are executed, the system is
 2004: interpreting.
 2005: 
 2006: When you pressed @key{RET} after entering the definition of @code{word2},
 2007: you should have seen the number -1 printed, followed by ``@code{
 2008: ok}''. When the text interpreter compiled the definition of
 2009: @code{word2}, it encountered @code{show-state-now}, an immediate word,
 2010: whose compilation semantics are therefore to perform its interpretation
 2011: semantics. It is executed straight away (even before the text
 2012: interpreter has moved on to process another group of characters; the
 2013: @code{;} in this example). The effect of executing it are to display the
 2014: value of @code{state} @i{at the time that the definition of}
 2015: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
 2016: system is compiling at this time. If you execute @code{word2} it does
 2017: nothing at all.
 2018: 
 2019: @cindex @code{."}, how it works
 2020: Before leaving the subject of immediate words, consider the behaviour of
 2021: @code{."} in the definition of @code{greet}, in the previous
 2022: section. This word is both a parsing word and an immediate word. Notice
 2023: that there is a space between @code{."} and the start of the text
 2024: @code{Hello and welcome}, but that there is no space between the last
 2025: letter of @code{welcome} and the @code{"} character. The reason for this
 2026: is that @code{."} is a Forth word; it must have a space after it so that
 2027: the text interpreter can identify it. The @code{"} is not a Forth word;
 2028: it is a @dfn{delimiter}. The examples earlier show that, when the string
 2029: is displayed, there is neither a space before the @code{H} nor after the
 2030: @code{e}. Since @code{."} is an immediate word, it executes at the time
 2031: that @code{greet} is defined. When it executes, its behaviour is to
 2032: search forward in the input line looking for the delimiter. When it
 2033: finds the delimiter, it updates @code{>IN} to point past the
 2034: delimiter. It also compiles some magic code into the definition of
 2035: @code{greet}; the xt of a run-time routine that prints a text string. It
 2036: compiles the string @code{Hello and welcome} into memory so that it is
 2037: available to be printed later. When the text interpreter gains control,
 2038: the next word it finds in the input stream is @code{;} and so it
 2039: terminates the definition of @code{greet}.
 2040: 
 2041: 
 2042: @comment ----------------------------------------------
 2043: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
 2044: @section Forth is written in Forth
 2045: @cindex structure of Forth programs
 2046: 
 2047: When you start up a Forth compiler, a large number of definitions
 2048: already exist. In Forth, you develop a new application using bottom-up
 2049: programming techniques to create new definitions that are defined in
 2050: terms of existing definitions. As you create each definition you can
 2051: test and debug it interactively.
 2052: 
 2053: If you have tried out the examples in this section, you will probably
 2054: have typed them in by hand; when you leave Gforth, your definitions will
 2055: be lost. You can avoid this by using a text editor to enter Forth source
 2056: code into a file, and then loading code from the file using
 2057: @code{include} (@xref{Forth source files}). A Forth source file is
 2058: processed by the text interpreter, just as though you had typed it in by
 2059: hand@footnote{Actually, there are some subtle differences -- see
 2060: @ref{The Text Interpreter}.}.
 2061: 
 2062: Gforth also supports the traditional Forth alternative to using text
 2063: files for program entry (@xref{Blocks}).
 2064: 
 2065: In common with many, if not most, Forth compilers, most of Gforth is
 2066: actually written in Forth. All of the @file{.fs} files in the
 2067: installation directory@footnote{For example,
 2068: @file{/usr/local/share/gforth...}} are Forth source files, which you can
 2069: study to see examples of Forth programming.
 2070: 
 2071: Gforth maintains a history file that records every line that you type to
 2072: the text interpreter. This file is preserved between sessions, and is
 2073: used to provide a command-line recall facility. If you enter long
 2074: definitions by hand, you can use a text editor to paste them out of the
 2075: history file into a Forth source file for reuse at a later time
 2076: (@pxref{Command-line editing} for more information).
 2077: 
 2078: 
 2079: @comment ----------------------------------------------
 2080: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
 2081: @section Review - elements of a Forth system
 2082: @cindex elements of a Forth system
 2083: 
 2084: To summarise this chapter:
 2085: 
 2086: @itemize @bullet
 2087: @item
 2088: Forth programs use @dfn{factoring} to break a problem down into small
 2089: fragments called @dfn{words} or @dfn{definitions}.
 2090: @item
 2091: Forth program development is an interactive process.
 2092: @item
 2093: The main command loop that accepts input, and controls both
 2094: interpretation and compilation, is called the @dfn{text interpreter}
 2095: (also known as the @dfn{outer interpreter}).
 2096: @item
 2097: Forth has a very simple syntax, consisting of words and numbers
 2098: separated by spaces or carriage-return characters. Any additional syntax
 2099: is imposed by @dfn{parsing words}.
 2100: @item
 2101: Forth uses a stack to pass parameters between words. As a result, it
 2102: uses postfix notation.
 2103: @item
 2104: To use a word that has previously been defined, the text interpreter
 2105: searches for the word in the @dfn{name dictionary}.
 2106: @item
 2107: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
 2108: @item
 2109: The text interpreter uses the value of @code{state} to select between
 2110: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
 2111: semantics} of a word that it encounters.
 2112: @item
 2113: The relationship between the @dfn{interpretation semantics} and
 2114: @dfn{compilation semantics} for a word
 2115: depend upon the way in which the word was defined (for example, whether
 2116: it is an @dfn{immediate} word).
 2117: @item
 2118: Forth definitions can be implemented in Forth (called @dfn{high-level
 2119: definitions}) or in some other way (usually a lower-level language and
 2120: as a result often called @dfn{low-level definitions}, @dfn{code
 2121: definitions} or @dfn{primitives}).
 2122: @item
 2123: Many Forth systems are implemented mainly in Forth.
 2124: @end itemize
 2125: 
 2126: 
 2127: @comment ----------------------------------------------
 2128: @node Where to go next,Exercises,Review - elements of a Forth system, Introduction
 2129: @section Where To Go Next
 2130: @cindex where to go next
 2131: 
 2132: Amazing as it may seem, if you have read (and understood) this far, you
 2133: know almost all the fundamentals about the inner workings of a Forth
 2134: system. You certainly know enough to be able to read and understand the
 2135: rest of this manual and the ANS Forth document, to learn more about the
 2136: facilities that Forth in general and Gforth in particular provide. Even
 2137: scarier, you know almost enough to implement your own Forth system.
 2138: However, that's not a good idea just yet... better to try writing some
 2139: programs in Gforth.
 2140: 
 2141: Forth has such a rich vocabulary that it can be hard to know where to
 2142: start in learning it. This section suggests a few sets of words that are
 2143: enough to write small but useful programs. Use the word index in this
 2144: document to learn more about each word, then try it out and try to write
 2145: small definitions using it. Start by experimenting with these words:
 2146: 
 2147: @itemize @bullet
 2148: @item
 2149: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
 2150: @item
 2151: Comparison: @code{MIN MAX =}
 2152: @item
 2153: Logic: @code{AND OR XOR NOT}
 2154: @item
 2155: Stack manipulation: @code{DUP DROP SWAP OVER}
 2156: @item
 2157: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
 2158: @item
 2159: Input/Output: @code{. ." EMIT CR KEY}
 2160: @item
 2161: Defining words: @code{: ; CREATE}
 2162: @item
 2163: Memory allocation words: @code{ALLOT ,}
 2164: @item
 2165: Tools: @code{SEE WORDS .S MARKER}
 2166: @end itemize
 2167: 
 2168: When you have mastered those, go on to:
 2169: 
 2170: @itemize @bullet
 2171: @item
 2172: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
 2173: @item
 2174: Memory access: @code{@@ !}
 2175: @end itemize
 2176: 
 2177: When you have mastered these, there's nothing for it but to read through
 2178: the whole of this manual and find out what you've missed.
 2179: 
 2180: @comment ----------------------------------------------
 2181: @node Exercises, ,Where to go next, Introduction
 2182: @section Exercises
 2183: @cindex exercises
 2184: 
 2185: TODO: provide a set of programming excercises linked into the stuff done
 2186: already and into other sections of the manual. Provide solutions to all
 2187: the exercises in a .fs file in the distribution.
 2188: 
 2189: @c Get some inspiration from Starting Forth and Kelly&Spies.
 2190: 
 2191: @c excercises:
 2192: @c 1. take inches and convert to feet and inches.
 2193: @c 2. take temperature and convert from fahrenheight to celcius;
 2194: @c    may need to care about symmetric vs floored??
 2195: @c 3. take input line and do character substitution
 2196: @c    to encipher or decipher
 2197: @c 4. as above but work on a file for in and out
 2198: @c 5. take input line and convert to pig-latin 
 2199: @c
 2200: @c thing of sets of things to exercise then come up with
 2201: @c problems that need those things.
 2202: 
 2203: 
 2204: @c ******************************************************************
 2205: @node Words, Error messages, Introduction, Top
 2206: @chapter Forth Words
 2207: @cindex words
 2208: 
 2209: @menu
 2210: * Notation::                    
 2211: * Comments::
 2212: * Boolean Flags::
 2213: * Arithmetic::                  
 2214: * Stack Manipulation::          
 2215: * Memory::                      
 2216: * Control Structures::          
 2217: * Defining Words::              
 2218: * The Text Interpreter::
 2219: * Tokens for Words::            
 2220: * Word Lists::                   
 2221: * Environmental Queries::
 2222: * Files::                       
 2223: * Blocks::                      
 2224: * Other I/O::                   
 2225: * Programming Tools::           
 2226: * Assembler and Code Words::    
 2227: * Threading Words::             
 2228: * Locals::                      
 2229: * Structures::                  
 2230: * Object-oriented Forth::       
 2231: * Passing Commands to the OS::
 2232: * Miscellaneous Words::
 2233: @end menu
 2234: 
 2235: @node Notation, Comments, Words, Words
 2236: @section Notation
 2237: @cindex notation of glossary entries
 2238: @cindex format of glossary entries
 2239: @cindex glossary notation format
 2240: @cindex word glossary entry format
 2241: 
 2242: The Forth words are described in this section in the glossary notation
 2243: that has become a de-facto standard for Forth texts, i.e.,
 2244: 
 2245: @format
 2246: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
 2247: @end format
 2248: @i{Description}
 2249: 
 2250: @table @var
 2251: @item word
 2252: The name of the word.
 2253: 
 2254: @item Stack effect
 2255: @cindex stack effect
 2256: The stack effect is written in the notation @code{@i{before} --
 2257: @i{after}}, where @i{before} and @i{after} describe the top of
 2258: stack entries before and after the execution of the word. The rest of
 2259: the stack is not touched by the word. The top of stack is rightmost,
 2260: i.e., a stack sequence is written as it is typed in. Note that Gforth
 2261: uses a separate floating point stack, but a unified stack
 2262: notation. Also, return stack effects are not shown in @i{stack
 2263: effect}, but in @i{Description}. The name of a stack item describes
 2264: the type and/or the function of the item. See below for a discussion of
 2265: the types.
 2266: 
 2267: All words have two stack effects: A compile-time stack effect and a
 2268: run-time stack effect. The compile-time stack-effect of most words is
 2269: @i{ -- }. If the compile-time stack-effect of a word deviates from
 2270: this standard behaviour, or the word does other unusual things at
 2271: compile time, both stack effects are shown; otherwise only the run-time
 2272: stack effect is shown.
 2273: 
 2274: @cindex pronounciation of words
 2275: @item pronunciation
 2276: How the word is pronounced.
 2277: 
 2278: @cindex wordset
 2279: @item wordset
 2280: The ANS Forth standard is divided into several word sets. A standard
 2281: system need not support all of them. Therefore, in theory, the fewer
 2282: word sets your program uses the more portable it will be. However, we
 2283: suspect that most ANS Forth systems on personal machines will feature
 2284: all word sets. Words that are not defined in ANS Forth have
 2285: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
 2286: describes words that will work in future releases of Gforth;
 2287: @code{gforth-internal} words are more volatile. Environmental query
 2288: strings are also displayed like words; you can recognize them by the
 2289: @code{environment} in the word set field.
 2290: 
 2291: @item Description
 2292: A description of the behaviour of the word.
 2293: @end table
 2294: 
 2295: @cindex types of stack items
 2296: @cindex stack item types
 2297: The type of a stack item is specified by the character(s) the name
 2298: starts with:
 2299: 
 2300: @table @code
 2301: @item f
 2302: @cindex @code{f}, stack item type
 2303: Boolean flags, i.e. @code{false} or @code{true}.
 2304: @item c
 2305: @cindex @code{c}, stack item type
 2306: Char
 2307: @item w
 2308: @cindex @code{w}, stack item type
 2309: Cell, can contain an integer or an address
 2310: @item n
 2311: @cindex @code{n}, stack item type
 2312: signed integer
 2313: @item u
 2314: @cindex @code{u}, stack item type
 2315: unsigned integer
 2316: @item d
 2317: @cindex @code{d}, stack item type
 2318: double sized signed integer
 2319: @item ud
 2320: @cindex @code{ud}, stack item type
 2321: double sized unsigned integer
 2322: @item r
 2323: @cindex @code{r}, stack item type
 2324: Float (on the FP stack)
 2325: @item a-
 2326: @cindex @code{a_}, stack item type
 2327: Cell-aligned address
 2328: @item c-
 2329: @cindex @code{c_}, stack item type
 2330: Char-aligned address (note that a Char may have two bytes in Windows NT)
 2331: @item f-
 2332: @cindex @code{f_}, stack item type
 2333: Float-aligned address
 2334: @item df-
 2335: @cindex @code{df_}, stack item type
 2336: Address aligned for IEEE double precision float
 2337: @item sf-
 2338: @cindex @code{sf_}, stack item type
 2339: Address aligned for IEEE single precision float
 2340: @item xt
 2341: @cindex @code{xt}, stack item type
 2342: Execution token, same size as Cell
 2343: @item wid
 2344: @cindex @code{wid}, stack item type
 2345: Word list ID, same size as Cell
 2346: @item f83name
 2347: @cindex @code{f83name}, stack item type
 2348: Pointer to a name structure
 2349: @item "
 2350: @cindex @code{"}, stack item type
 2351: string in the input stream (not on the stack). The terminating character
 2352: is a blank by default. If it is not a blank, it is shown in @code{<>}
 2353: quotes.
 2354: @end table
 2355: 
 2356: @node Comments, Boolean Flags, Notation, Words
 2357: @section Comments
 2358: @cindex comments
 2359: 
 2360: Forth supports two styles of comment; the traditional @i{in-line} comment,
 2361: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
 2362: 
 2363: doc-(
 2364: doc-\
 2365: doc-\G
 2366: 
 2367: @node Boolean Flags, Arithmetic, Comments, Words
 2368: @section Boolean Flags
 2369: @cindex Boolean flags
 2370: 
 2371: A Boolean flag is cell-sized. A cell with all bits clear represents the
 2372: flag @code{false} and a flag with all bits set represents the flag
 2373: @code{true}. Words that check a flag (for example, @code{IF}) will treat
 2374: a cell that has @i{any} bit set as @code{true}.
 2375: 
 2376: doc-true
 2377: doc-false
 2378: doc-on
 2379: doc-off
 2380: 
 2381: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
 2382: @section Arithmetic
 2383: @cindex arithmetic words
 2384: 
 2385: @cindex division with potentially negative operands
 2386: Forth arithmetic is not checked, i.e., you will not hear about integer
 2387: overflow on addition or multiplication, you may hear about division by
 2388: zero if you are lucky. The operator is written after the operands, but
 2389: the operands are still in the original order. I.e., the infix @code{2-1}
 2390: corresponds to @code{2 1 -}. Forth offers a variety of division
 2391: operators. If you perform division with potentially negative operands,
 2392: you do not want to use @code{/} or @code{/mod} with its undefined
 2393: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
 2394: former, @pxref{Mixed precision}).
 2395: @comment TODO discuss the different division forms and the std approach
 2396: 
 2397: @menu
 2398: * Single precision::            
 2399: * Bitwise operations::          
 2400: * Double precision::            Double-cell integer arithmetic
 2401: * Numeric comparison::
 2402: * Mixed precision::             Operations with single and double-cell integers
 2403: * Floating Point::              
 2404: @end menu
 2405: 
 2406: @node Single precision, Bitwise operations, Arithmetic, Arithmetic
 2407: @subsection Single precision
 2408: @cindex single precision arithmetic words
 2409: 
 2410: By default, numbers in Forth are single-precision integers that are 1
 2411: cell in size. They can be signed or unsigned, depending upon how you
 2412: treat them. @xref{Number Conversion} for the rules used by the text
 2413: interpreter for recognising single-precision integers.
 2414: 
 2415: doc-+
 2416: doc-1+
 2417: doc--
 2418: doc-1-
 2419: doc-*
 2420: doc-/
 2421: doc-mod
 2422: doc-/mod
 2423: doc-negate
 2424: doc-abs
 2425: doc-min
 2426: doc-max
 2427: doc-d>s
 2428: doc-floored
 2429: 
 2430: @node Bitwise operations, Double precision, Single precision, Arithmetic
 2431: @subsection Bitwise operations
 2432: @cindex bitwise operation words
 2433: 
 2434: doc-and
 2435: doc-or
 2436: doc-xor
 2437: doc-invert
 2438: doc-lshift
 2439: doc-rshift
 2440: doc-2*
 2441: doc-d2*
 2442: doc-2/
 2443: doc-d2/
 2444: 
 2445: @node Double precision, Numeric comparison, Bitwise operations, Arithmetic
 2446: @subsection Double precision
 2447: @cindex double precision arithmetic words
 2448: 
 2449: @xref{Number Conversion} for the rules used by the text interpreter for
 2450: recognising double-precision integers.
 2451: 
 2452: A double precision number is represented by a cell pair, with the most
 2453: significant cell at the TOS. It is trivial to convert an unsigned
 2454: single to an (unsigned) double; simply push a @code{0} onto the
 2455: TOS. Since numbers are represented by Gforth using 2's complement
 2456: arithmetic, converting a signed single to a (signed) double requires
 2457: sign-extension across the most significant cell. This can be achieved
 2458: using @code{s>d}. The moral of the story is that you cannot convert a
 2459: number without knowing whether it represents an unsigned or a
 2460: signed number.
 2461: 
 2462: doc-s>d
 2463: doc-d+
 2464: doc-d-
 2465: doc-dnegate
 2466: doc-dabs
 2467: doc-dmin
 2468: doc-dmax
 2469: 
 2470: @node Numeric comparison, Mixed precision, Double precision, Arithmetic
 2471: @subsection Numeric comparison
 2472: @cindex numeric comparison words
 2473: 
 2474: doc-<
 2475: doc-<=
 2476: doc-<>
 2477: doc-=
 2478: doc->
 2479: doc->=
 2480: 
 2481: doc-0<
 2482: doc-0<=
 2483: doc-0<>
 2484: doc-0=
 2485: doc-0>
 2486: doc-0>=
 2487: 
 2488: doc-u<
 2489: doc-u<=
 2490: @c TODO why u<> and u= ... they are the same as <> and =
 2491: @c commented them out because they are unnecessary
 2492: @c doc-u<>
 2493: @c doc-u=
 2494: doc-u>
 2495: doc-u>=
 2496: 
 2497: doc-within
 2498: 
 2499: doc-d<
 2500: doc-d<=
 2501: doc-d<>
 2502: doc-d=
 2503: doc-d>
 2504: doc-d>=
 2505: 
 2506: doc-d0<
 2507: doc-d0<=
 2508: doc-d0<>
 2509: doc-d0=
 2510: doc-d0>
 2511: doc-d0>=
 2512: 
 2513: doc-du<
 2514: doc-du<=
 2515: @c doc-du<>
 2516: @c doc-du=
 2517: doc-du>
 2518: doc-du>=
 2519: 
 2520: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
 2521: @subsection Mixed precision
 2522: @cindex mixed precision arithmetic words
 2523: 
 2524: doc-m+
 2525: doc-*/
 2526: doc-*/mod
 2527: doc-m*
 2528: doc-um*
 2529: doc-m*/
 2530: doc-um/mod
 2531: doc-fm/mod
 2532: doc-sm/rem
 2533: 
 2534: @node Floating Point,  , Mixed precision, Arithmetic
 2535: @subsection Floating Point
 2536: @cindex floating point arithmetic words
 2537: 
 2538: @xref{Number Conversion} for the rules used by the text interpreter for
 2539: recognising floating-point numbers.
 2540: 
 2541: Gforth has a separate floating point
 2542: stack, but the documentation uses the unified notation.
 2543: 
 2544: @cindex floating-point arithmetic, pitfalls
 2545: Floating point numbers have a number of unpleasant surprises for the
 2546: unwary (e.g., floating point addition is not associative) and even a few
 2547: for the wary. You should not use them unless you know what you are doing
 2548: or you don't care that the results you get are totally bogus. If you
 2549: want to learn about the problems of floating point numbers (and how to
 2550: avoid them), you might start with @cite{David Goldberg, What Every
 2551: Computer Scientist Should Know About Floating-Point Arithmetic, ACM
 2552: Computing Surveys 23(1):5@minus{}48, March 1991}
 2553: (@url{http://www.validgh.com/goldberg/paper.ps}).
 2554: 
 2555: doc-d>f
 2556: doc-f>d
 2557: doc-f+
 2558: doc-f-
 2559: doc-f*
 2560: doc-f/
 2561: doc-fnegate
 2562: doc-fabs
 2563: doc-fmax
 2564: doc-fmin
 2565: doc-floor
 2566: doc-fround
 2567: doc-f**
 2568: doc-fsqrt
 2569: doc-fexp
 2570: doc-fexpm1
 2571: doc-fln
 2572: doc-flnp1
 2573: doc-flog
 2574: doc-falog
 2575: doc-f2*
 2576: doc-f2/
 2577: doc-1/f
 2578: doc-precision
 2579: doc-set-precision
 2580: 
 2581: @cindex angles in trigonometric operations
 2582: @cindex trigonometric operations
 2583: Angles in floating point operations are given in radians (a full circle
 2584: has 2 pi radians).
 2585: 
 2586: doc-fsin
 2587: doc-fcos
 2588: doc-fsincos
 2589: doc-ftan
 2590: doc-fasin
 2591: doc-facos
 2592: doc-fatan
 2593: doc-fatan2
 2594: doc-fsinh
 2595: doc-fcosh
 2596: doc-ftanh
 2597: doc-fasinh
 2598: doc-facosh
 2599: doc-fatanh
 2600: doc-pi
 2601: 
 2602: @cindex equality of floats
 2603: @cindex floating-point comparisons
 2604: One particular problem with floating-point arithmetic is that comparison
 2605: for equality often fails when you would expect it to succeed.  For this
 2606: reason approximate equality is often preferred (but you still have to
 2607: know what you are doing).  The comparison words are:
 2608: 
 2609: doc-f~rel
 2610: doc-f~abs
 2611: doc-f=
 2612: doc-f~
 2613: doc-f<>
 2614: 
 2615: doc-f<
 2616: doc-f<=
 2617: doc-f>
 2618: doc-f>=
 2619: 
 2620: doc-f0<
 2621: doc-f0<=
 2622: doc-f0<>
 2623: doc-f0=
 2624: doc-f0>
 2625: doc-f0>=
 2626: 
 2627: 
 2628: @node Stack Manipulation, Memory, Arithmetic, Words
 2629: @section Stack Manipulation
 2630: @cindex stack manipulation words
 2631: 
 2632: @cindex floating-point stack in the standard
 2633: Gforth maintains a number of separate stacks:
 2634: 
 2635: @cindex data stack
 2636: @cindex parameter stack
 2637: @itemize @bullet
 2638: @item
 2639: A data stack (also known as the @dfn{parameter stack}) -- for
 2640: characters, cells, addresses, and double cells.
 2641: 
 2642: @cindex floating-point stack
 2643: @item
 2644: A floating point stack -- for floating point numbers.
 2645: 
 2646: @cindex return stack
 2647: @item
 2648: A return stack -- for storing the return addresses of colon
 2649: definitions and other (non-FP) data.
 2650: 
 2651: @cindex locals stack
 2652: @item
 2653: A locals stack for storing local variables.
 2654: @end itemize
 2655: 
 2656: @menu
 2657: * Data stack::                  
 2658: * Floating point stack::        
 2659: * Return stack::                
 2660: * Locals stack::                
 2661: * Stack pointer manipulation::  
 2662: @end menu
 2663: 
 2664: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
 2665: @subsection Data stack
 2666: @cindex data stack manipulation words
 2667: @cindex stack manipulations words, data stack
 2668: 
 2669: doc-drop
 2670: doc-nip
 2671: doc-dup
 2672: doc-over
 2673: doc-tuck
 2674: doc-swap
 2675: doc-pick
 2676: doc-rot
 2677: doc--rot
 2678: doc-?dup
 2679: doc-roll
 2680: doc-2drop
 2681: doc-2nip
 2682: doc-2dup
 2683: doc-2over
 2684: doc-2tuck
 2685: doc-2swap
 2686: doc-2rot
 2687: 
 2688: @node Floating point stack, Return stack, Data stack, Stack Manipulation
 2689: @subsection Floating point stack
 2690: @cindex floating-point stack manipulation words
 2691: @cindex stack manipulation words, floating-point stack
 2692: 
 2693: Whilst every sane Forth has a separate floating-point stack, it is not
 2694: strictly required; an ANS Forth system could theoretically keep
 2695: floating-point numbers on the data stack. As an additional difficulty,
 2696: you don't know how many cells a floating-point number takes. It is
 2697: reportedly possible to write words in a way that they work also for a
 2698: unified stack model, but we do not recommend trying it. Instead, just
 2699: say that your program has an environmental dependency on a separate
 2700: floating-point stack.
 2701: 
 2702: doc-floating-stack
 2703: 
 2704: doc-fdrop
 2705: doc-fnip
 2706: doc-fdup
 2707: doc-fover
 2708: doc-ftuck
 2709: doc-fswap
 2710: doc-fpick
 2711: doc-frot
 2712: 
 2713: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
 2714: @subsection Return stack
 2715: @cindex return stack manipulation words
 2716: @cindex stack manipulation words, return stack
 2717: 
 2718: @cindex return stack and locals
 2719: @cindex locals and return stack
 2720: A Forth system is allowed to keep local variables on the
 2721: return stack. This is reasonable, as local variables usually eliminate
 2722: the need to use the return stack explicitly. So, if you want to produce
 2723: a standard compliant program and you are using local variables in a
 2724: word, forget about return stack manipulations in that word (refer to the
 2725: standard document for the exact rules).
 2726: 
 2727: doc->r
 2728: doc-r>
 2729: doc-r@
 2730: doc-rdrop
 2731: doc-2>r
 2732: doc-2r>
 2733: doc-2r@
 2734: doc-2rdrop
 2735: 
 2736: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
 2737: @subsection Locals stack
 2738: 
 2739: @comment TODO
 2740: 
 2741: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
 2742: @subsection Stack pointer manipulation
 2743: @cindex stack pointer manipulation words
 2744: 
 2745: doc-sp0
 2746: doc-sp@
 2747: doc-sp!
 2748: doc-fp0
 2749: doc-fp@
 2750: doc-fp!
 2751: doc-rp0
 2752: doc-rp@
 2753: doc-rp!
 2754: doc-lp0
 2755: doc-lp@
 2756: doc-lp!
 2757: 
 2758: @node Memory, Control Structures, Stack Manipulation, Words
 2759: @section Memory
 2760: @cindex memory words
 2761: 
 2762: @menu
 2763: * Memory model::                
 2764: * Dictionary allocation::       
 2765: * Heap Allocation::             
 2766: * Memory Access::               
 2767: * Address arithmetic::          
 2768: * Memory Blocks::               
 2769: @end menu
 2770: 
 2771: @node Memory model, Dictionary allocation, Memory, Memory
 2772: @subsection ANS Forth and Gforth memory models
 2773: 
 2774: @c The ANS Forth description is a mess (e.g., is the heap part of
 2775: @c the dictionary?), so let's not stick to closely with it.
 2776: 
 2777: ANS Forth considers a Forth system as consisting of several memories, of
 2778: which only @dfn{data space} is managed and accessible with the memory
 2779: words.  Memory not necessarily in data space includes the stacks, the
 2780: code (called code space) and the headers (called name space). In Gforth
 2781: everything is in data space, but the code for the primitives is usually
 2782: read-only.
 2783: 
 2784: Data space is divided into a number of areas: The (data space portion of
 2785: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
 2786: refer to the search data structure embodied in word lists and headers,
 2787: because it is used for looking up names, just as you would in a
 2788: conventional dictionary.}, the heap, and a number of system-allocated
 2789: buffers.
 2790: 
 2791: In ANS Forth data space is also divided into contiguous regions.  You
 2792: can only use address arithmetic within a contiguous region, not between
 2793: them.  Usually each allocation gives you one contiguous region, but the
 2794: dictionary allocation words have additional rules (@pxref{Dictionary
 2795: allocation}).
 2796: 
 2797: Gforth provides one big address space, and address arithmetic can be
 2798: performed between any addresses. However, in the dictionary headers or
 2799: code are interleaved with data, so almost the only contiguous data space
 2800: regions there are those described by ANS Forth as contiguous; but you
 2801: can be sure that the dictionary is allocated towards increasing
 2802: addresses even between contiguous regions.  The memory order of
 2803: allocations in the heap is platform-dependent (and possibly different
 2804: from one run to the next).
 2805: 
 2806: @subsubsection ANS Forth dictionary details
 2807: 
 2808: @c !! I have deleted some of the stuff this section refers to - anton
 2809: 
 2810: This section is just informative, you can skip it if you are in a hurry.
 2811: 
 2812: When you create a colon definition, the text interpreter compiles the
 2813: code for the definition into the code space and compiles the name
 2814: of the definition into the header space, together with other
 2815: information about the definition (such as its execution token).
 2816: 
 2817: When you create a variable, the execution of @code{variable} will
 2818: compile some code, assign one cell in data space, and compile the name
 2819: of the variable into the header space.
 2820: 
 2821: @cindex memory regions - relationship between them
 2822: ANS Forth does not specify the relationship between the three memory
 2823: regions, and specifies that a Standard program must not access code or
 2824: data space directly -- it may only access data space directly. In
 2825: addition, the Standard defines what relationships you may and may not
 2826: rely on when allocating regions in data space. These constraints are
 2827: simply a reflection of the many diverse techniques that are used to
 2828: implement Forth systems; understanding and following the requirements of
 2829: the Standard allows you to write portable programs -- programs that run
 2830: in the same way on any of these diverse systems. Another way of looking
 2831: at this is to say that ANS Forth was designed to permit compliant Forth
 2832: systems to be implemented in many diverse ways.
 2833: 
 2834: @cindex memory regions - how they are assigned
 2835: Here are some examples of ways in which name, code and data spaces
 2836: might be assigned in different Forth implementations:
 2837: 
 2838: @itemize @bullet
 2839: @item
 2840: For a Forth system that runs from RAM under a general-purpose operating
 2841: system, it can be convenient to interleave name, code and data spaces in
 2842: a single contiguous memory region. This organisation can be
 2843: memory-efficient (for example, because the relationship between the name
 2844: dictionary entry and the associated code space entry can be
 2845: implicit, rather than requiring an explicit memory pointer to reference
 2846: from the header space and the code space). This is the
 2847: organisation used by Gforth, as this example@footnote{The addresses
 2848: in the example have been truncated to fit it onto the page, and the
 2849: addresses and data shown will not match the output from your system} shows:
 2850: @example
 2851: hex
 2852: variable fred 123456 fred !
 2853: variable jim abcd jim !
 2854: : foo + / - ;
 2855: ' fred 10 - 50 dump 
 2856: ..80: 5C 46 0E 40  84 66 72 65 - 64 20 20 20  20 20 20 20  \F.@.fred       
 2857: ..90: D0 9B 04 08  00 00 00 00 - 56 34 12 00  80 46 0E 40  ........V4...F.@
 2858: ..A0: 83 6A 69 6D  20 20 20 20 - D0 9B 04 08  00 00 00 00  .jim    ........
 2859: ..B0: CD AB 00 00  9C 46 0E 40 - 83 66 6F 6F  20 20 20 20  .....F.@.foo    
 2860: ..C0: 80 9B 04 08  00 00 00 00 - E4 2E 05 08  0C 2F 05 08  ............./..
 2861: @end example
 2862: 
 2863: @item
 2864: For a high-performance system running on a modern RISC processor with a
 2865: modified Harvard architecture (one that has a unified main memory but
 2866: separate instruction and data caches), it is desirable to separate
 2867: processor instructions from processor data. This encourages a high cache
 2868: density and therefore a high cache hit rate. The Forth code space
 2869: is not necessarily made up entirely of processor instructions; its
 2870: nature is dependent upon the Forth implementation. 
 2871: 
 2872: @item
 2873: A Forth compiler that runs on a segmented 8086 processor could be
 2874: designed to interleave the name, code and data spaces within a single
 2875: 64Kbyte segment. A more common implementation choice is to use a
 2876: separate 64Kbyte segment for each region, which provides more memory
 2877: overall but provides an address map in which only the data space is
 2878: accessible.
 2879: 
 2880: @item
 2881: Microprocessors exist that run Forth (or many of the primitives required
 2882: to implement the Forth virtual machine efficiently) directly. On these
 2883: processors, the relationship between name, code and data spaces may be
 2884: imposed as a side-effect of the architecture of the processor.
 2885: 
 2886: @item
 2887: A Forth compiler that executes from ROM on an embedded system needs its
 2888: data space separated from the name and code spaces so that the data
 2889: space can be mapped to a RAM area.
 2890: 
 2891: @item 
 2892: A Forth compiler that runs on an embedded system may have a requirement
 2893: for a small memory footprint. On such a system it can be useful to
 2894: separate the header space from the data and code spaces; once the
 2895: application has been compiled, the header space is no longer
 2896: required@footnote{more strictly speaking, most applications can be
 2897: designed so that this is the case}. The header space can be deleted
 2898: entirely, or could be stored in memory on a remote @i{host} system for
 2899: debug and development purposes. In the latter case, the compiler running
 2900: on the @i{target} system could implement a protocol across a
 2901: communication link that would allow it to interrogate the header space.
 2902: @end itemize
 2903: 
 2904: 
 2905: @node Dictionary allocation, Heap Allocation, Memory model, Memory
 2906: @subsection Dictionary allocation
 2907: @cindex reserving data space
 2908: @cindex data space - reserving some
 2909: 
 2910: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
 2911: you want to deallocate X, you also deallocate everything
 2912: allocated after X.
 2913: 
 2914: The allocations using the words below are contiguous and grow the region
 2915: towards increasing addresses.  Other words that allocate dictionary
 2916: memory of any kind (i.e., defining words including @code{:noname}) end
 2917: the contiguous region and start a new one.
 2918: 
 2919: In ANS Forth only @code{create}d words are guaranteed to produce an
 2920: address that is the start of the following contiguous region.  In
 2921: particular, the cell allocated by @code{variable} is not guaranteed to
 2922: be contiguous with following @code{allot}ed memory.
 2923: 
 2924: You can deallocate memory by using @code{allot} with a negative argument
 2925: (with some restrictions, see @code{allot}). For larger deallocations use
 2926: @code{marker}.
 2927: 
 2928: 
 2929: doc-here
 2930: doc-unused
 2931: doc-allot
 2932: doc-c,
 2933: doc-f,
 2934: doc-,
 2935: doc-2,
 2936: @cindex user space
 2937: doc-udp
 2938: doc-uallot
 2939: 
 2940: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
 2941: course you should allocate memory in an aligned way, too. I.e., before
 2942: allocating allocating a cell, @code{here} must be cell-aligned, etc.
 2943: The words below align @code{here} if it is not already.  Basically it is
 2944: only already aligned for a type, if the last allocation was a multiple
 2945: of the size of this type and if @code{here} was aligned for this type
 2946: before.
 2947: 
 2948: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
 2949: ANS Forth (@code{maxalign}ed in Gforth).
 2950: 
 2951: doc-align
 2952: doc-falign
 2953: doc-sfalign
 2954: doc-dfalign
 2955: doc-maxalign
 2956: doc-cfalign
 2957: 
 2958: 
 2959: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
 2960: @subsection Heap allocation
 2961: @cindex heap allocation
 2962: @cindex dynamic allocation of memory
 2963: @cindex memory-allocation word set
 2964: 
 2965: Heap allocation supports deallocation of allocated memory in any
 2966: order. Dictionary allocation is not affected by it (i.e., it does not
 2967: end a contiguous region). In Gforth, these words are implemented using
 2968: the standard C library calls malloc(), free() and resize().
 2969: 
 2970: doc-allocate
 2971: doc-free
 2972: doc-resize
 2973: 
 2974: 
 2975: @node Memory Access, Address arithmetic, Heap Allocation, Memory
 2976: @subsection Memory Access
 2977: @cindex memory access words
 2978: 
 2979: doc-@
 2980: doc-!
 2981: doc-+!
 2982: doc-c@
 2983: doc-c!
 2984: doc-2@
 2985: doc-2!
 2986: doc-f@
 2987: doc-f!
 2988: doc-sf@
 2989: doc-sf!
 2990: doc-df@
 2991: doc-df!
 2992: 
 2993: @node Address arithmetic, Memory Blocks, Memory Access, Memory
 2994: @subsection Address arithmetic
 2995: @cindex address arithmetic words
 2996: 
 2997: Address arithmetic is the foundation on which data structures like
 2998: arrays, records (@pxref{Structures}) and objects (@pxref{Object-oriented
 2999: Forth}) are built.
 3000: 
 3001: ANS Forth does not specify the sizes of the data types. Instead, it
 3002: offers a number of words for computing sizes and doing address
 3003: arithmetic. Address arithmetic is performed in terms of address units
 3004: (aus); on most systems the address unit is one byte. Note that a
 3005: character may have more than one au, so @code{chars} is no noop (on
 3006: systems where it is a noop, it compiles to nothing).
 3007: 
 3008: @cindex alignment of addresses for types
 3009: ANS Forth also defines words for aligning addresses for specific
 3010: types. Many computers require that accesses to specific data types
 3011: must only occur at specific addresses; e.g., that cells may only be
 3012: accessed at addresses divisible by 4. Even if a machine allows unaligned
 3013: accesses, it can usually perform aligned accesses faster. 
 3014: 
 3015: For the performance-conscious: alignment operations are usually only
 3016: necessary during the definition of a data structure, not during the
 3017: (more frequent) accesses to it.
 3018: 
 3019: ANS Forth defines no words for character-aligning addresses. This is not
 3020: an oversight, but reflects the fact that addresses that are not
 3021: char-aligned have no use in the standard and therefore will not be
 3022: created.
 3023: 
 3024: @cindex @code{CREATE} and alignment
 3025: ANS Forth guarantees that addresses returned by @code{CREATE}d words
 3026: are cell-aligned; in addition, Gforth guarantees that these addresses
 3027: are aligned for all purposes.
 3028: 
 3029: Note that the ANS Forth word @code{char} has nothing to do with address
 3030: arithmetic.
 3031: 
 3032: doc-chars
 3033: doc-char+
 3034: doc-cells
 3035: doc-cell+
 3036: doc-cell
 3037: doc-aligned
 3038: doc-floats
 3039: doc-float+
 3040: doc-float
 3041: doc-faligned
 3042: doc-sfloats
 3043: doc-sfloat+
 3044: doc-sfaligned
 3045: doc-dfloats
 3046: doc-dfloat+
 3047: doc-dfaligned
 3048: doc-maxaligned
 3049: doc-cfaligned
 3050: doc-address-unit-bits
 3051: 
 3052: @node Memory Blocks,  , Address arithmetic, Memory
 3053: @subsection Memory Blocks
 3054: @cindex memory block words
 3055: @cindex character strings - moving and copying
 3056: 
 3057: Memory blocks often represent character strings; @xref{String Formats}
 3058: for ways of storing character strings in memory. @xref{Displaying
 3059: characters and strings} for other string-processing words.
 3060: 
 3061: Some of these words work on address units. Others work on character
 3062: units (increments of @code{CHAR}), and expect a @code{CHAR}-aligned
 3063: address. Choose the correct operation depending upon your data type.
 3064: 
 3065: When copying characters between overlapping memory regions, choose
 3066: carefully between @code{cmove} and @code{cmove>}.
 3067: 
 3068: You can only use any of these words @i{portably} to access data space.
 3069: 
 3070: @comment TODO - think the naming of the arguments is wrong for move
 3071: @comment well, really it seems to be the Standard that's wrong; it
 3072: @comment describes MOVE as a word that requires a CELL-aligned source
 3073: @comment and destination address but a xtranfer count that need not
 3074: @comment be a multiple of CELL.
 3075: doc-move
 3076: doc-erase
 3077: doc-cmove
 3078: doc-cmove>
 3079: doc-fill
 3080: doc-blank
 3081: doc-compare
 3082: doc-search
 3083: doc--trailing
 3084: doc-/string
 3085: 
 3086: @comment TODO examples
 3087: 
 3088: 
 3089: @node Control Structures, Defining Words, Memory, Words
 3090: @section Control Structures
 3091: @cindex control structures
 3092: 
 3093: Control structures in Forth cannot be used interpretively, only in a
 3094: colon definition@footnote{To be precise, they have no interpretation
 3095: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
 3096: not like this limitation, but have not seen a satisfying way around it
 3097: yet, although many schemes have been proposed.
 3098: 
 3099: @menu
 3100: * Selection::                   IF ... ELSE ... ENDIF
 3101: * Simple Loops::                BEGIN ...
 3102: * Counted Loops::               DO
 3103: * Arbitrary control structures::
 3104: * Calls and returns::
 3105: * Exception Handling::          
 3106: @end menu
 3107: 
 3108: @node Selection, Simple Loops, Control Structures, Control Structures
 3109: @subsection Selection
 3110: @cindex selection control structures
 3111: @cindex control structures for selection
 3112: 
 3113: @c what's the purpose of all these @i? Maybe we should define a macro
 3114: @c so we can produce logical markup.  - anton
 3115: 
 3116: @cindex @code{IF} control structure
 3117: @example
 3118: @i{flag}
 3119: IF
 3120:   @i{code}
 3121: ENDIF
 3122: @end example
 3123: @noindent
 3124: 
 3125: @var{code} is executed if @var{flag} is non-zero (that's truth as far as
 3126: @code{IF} etc. are concerned).
 3127: 
 3128: @example
 3129: @i{flag}
 3130: IF
 3131:   @i{code1}
 3132: ELSE
 3133:   @i{code2}
 3134: ENDIF
 3135: @end example
 3136: 
 3137: If @var{flag} is true, perform @var{code1}, otherwise @var{code2}.
 3138: 
 3139: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
 3140: standard, and @code{ENDIF} is not, although it is quite popular. We
 3141: recommend using @code{ENDIF}, because it is less confusing for people
 3142: who also know other languages (and is not prone to reinforcing negative
 3143: prejudices against Forth in these people). Adding @code{ENDIF} to a
 3144: system that only supplies @code{THEN} is simple:
 3145: @example
 3146: : ENDIF   POSTPONE THEN ; immediate
 3147: @end example
 3148: 
 3149: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
 3150: (adv.)}  has the following meanings:
 3151: @quotation
 3152: ... 2b: following next after in order ... 3d: as a necessary consequence
 3153: (if you were there, then you saw them).
 3154: @end quotation
 3155: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
 3156: and many other programming languages has the meaning 3d.]
 3157: 
 3158: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
 3159: you can avoid using @code{?dup}. Using these alternatives is also more
 3160: efficient than using @code{?dup}. Definitions in ANS Forth
 3161: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
 3162: @file{compat/control.fs}.
 3163: 
 3164: @cindex @code{CASE} control structure
 3165: @example
 3166: @i{n}
 3167: CASE
 3168:   @i{n1} OF @i{code1} ENDOF
 3169:   @i{n2} OF @i{code2} ENDOF
 3170:   @dots{}
 3171: ENDCASE
 3172: @end example
 3173: 
 3174: Executes the first @i{codei}, where the @i{ni} is equal to
 3175: @i{n}. A default case can be added by simply writing the code after
 3176: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
 3177: but must not consume it.
 3178: 
 3179: @node Simple Loops, Counted Loops, Selection, Control Structures
 3180: @subsection Simple Loops
 3181: @cindex simple loops
 3182: @cindex loops without count 
 3183: 
 3184: @cindex @code{WHILE} loop
 3185: @example
 3186: BEGIN
 3187:   @i{code1}
 3188:   @i{flag}
 3189: WHILE
 3190:   @i{code2}
 3191: REPEAT
 3192: @end example
 3193: 
 3194: @i{code1} is executed and @i{flag} is computed. If it is true,
 3195: @i{code2} is executed and the loop is restarted; If @i{flag} is
 3196: false, execution continues after the @code{REPEAT}.
 3197: 
 3198: @cindex @code{UNTIL} loop
 3199: @example
 3200: BEGIN
 3201:   @i{code}
 3202:   @i{flag}
 3203: UNTIL
 3204: @end example
 3205: 
 3206: @i{code} is executed. The loop is restarted if @code{flag} is false.
 3207: 
 3208: @cindex endless loop
 3209: @cindex loops, endless
 3210: @example
 3211: BEGIN
 3212:   @i{code}
 3213: AGAIN
 3214: @end example
 3215: 
 3216: This is an endless loop.
 3217: 
 3218: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
 3219: @subsection Counted Loops
 3220: @cindex counted loops
 3221: @cindex loops, counted
 3222: @cindex @code{DO} loops
 3223: 
 3224: The basic counted loop is:
 3225: @example
 3226: @i{limit} @i{start}
 3227: ?DO
 3228:   @i{body}
 3229: LOOP
 3230: @end example
 3231: 
 3232: This performs one iteration for every integer, starting from @i{start}
 3233: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
 3234: accessed with @code{i}. For example, the loop:
 3235: @example
 3236: 10 0 ?DO
 3237:   i .
 3238: LOOP
 3239: @end example
 3240: @noindent
 3241: prints @code{0 1 2 3 4 5 6 7 8 9}
 3242: 
 3243: The index of the innermost loop can be accessed with @code{i}, the index
 3244: of the next loop with @code{j}, and the index of the third loop with
 3245: @code{k}.
 3246: 
 3247: doc-i
 3248: doc-j
 3249: doc-k
 3250: 
 3251: The loop control data are kept on the return stack, so there are some
 3252: restrictions on mixing return stack accesses and counted loop words. In
 3253: particuler, if you put values on the return stack outside the loop, you
 3254: cannot read them inside the loop@footnote{well, not in a way that is
 3255: portable.}. If you put values on the return stack within a loop, you
 3256: have to remove them before the end of the loop and before accessing the
 3257: index of the loop.
 3258: 
 3259: There are several variations on the counted loop:
 3260: 
 3261: @itemize @bullet
 3262: @item
 3263: @code{LEAVE} leaves the innermost counted loop immediately; execution
 3264: continues after the associated @code{LOOP} or @code{NEXT}. For example:
 3265: 
 3266: @example
 3267: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
 3268: @end example
 3269: prints @code{0 1 2 3}
 3270: 
 3271: 
 3272: @item
 3273: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
 3274: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
 3275: return stack so @code{EXIT} can get to its return address. For example:
 3276: 
 3277: @example
 3278: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
 3279: @end example
 3280: prints @code{0 1 2 3}
 3281: 
 3282: 
 3283: @item
 3284: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
 3285: (and @code{LOOP} iterates until they become equal by wrap-around
 3286: arithmetic). This behaviour is usually not what you want. Therefore,
 3287: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
 3288: @code{?DO}), which do not enter the loop if @i{start} is greater than
 3289: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
 3290: unsigned loop parameters.
 3291: 
 3292: @item
 3293: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
 3294: the loop, independent of the loop parameters. Do not use @code{DO}, even
 3295: if you know that the loop is entered in any case. Such knowledge tends
 3296: to become invalid during maintenance of a program, and then the
 3297: @code{DO} will make trouble.
 3298: 
 3299: @item
 3300: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
 3301: index by @i{n} instead of by 1. The loop is terminated when the border
 3302: between @i{limit-1} and @i{limit} is crossed. E.g.:
 3303: 
 3304: @example
 3305: 4 0 +DO  i .  2 +LOOP
 3306: @end example
 3307: @noindent
 3308: prints @code{0 2}
 3309: 
 3310: @example
 3311: 4 1 +DO  i .  2 +LOOP
 3312: @end example
 3313: @noindent
 3314: prints @code{1 3}
 3315: 
 3316: 
 3317: @cindex negative increment for counted loops
 3318: @cindex counted loops with negative increment
 3319: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
 3320: 
 3321: @example
 3322: -1 0 ?DO  i .  -1 +LOOP
 3323: @end example
 3324: @noindent
 3325: prints @code{0 -1}
 3326: 
 3327: @example
 3328: 0 0 ?DO  i .  -1 +LOOP
 3329: @end example
 3330: prints nothing.
 3331: 
 3332: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
 3333: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
 3334: index by @i{u} each iteration. The loop is terminated when the border
 3335: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
 3336: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
 3337: 
 3338: @example
 3339: -2 0 -DO  i .  1 -LOOP
 3340: @end example
 3341: @noindent
 3342: prints @code{0 -1}
 3343: 
 3344: @example
 3345: -1 0 -DO  i .  1 -LOOP
 3346: @end example
 3347: @noindent
 3348: prints @code{0}
 3349: 
 3350: @example
 3351: 0 0 -DO  i .  1 -LOOP
 3352: @end example
 3353: @noindent
 3354: prints nothing.
 3355: 
 3356: @end itemize
 3357: 
 3358: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
 3359: @code{-LOOP} are not defined in ANS Forth. However, an implementation
 3360: for these words that uses only standard words is provided in
 3361: @file{compat/loops.fs}.
 3362: 
 3363: 
 3364: @cindex @code{FOR} loops
 3365: Another counted loop is:
 3366: @example
 3367: @i{n}
 3368: FOR
 3369:   @i{body}
 3370: NEXT
 3371: @end example
 3372: This is the preferred loop of native code compiler writers who are too
 3373: lazy to optimize @code{?DO} loops properly. This loop structure is not
 3374: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
 3375: @code{i} produces values starting with @i{n} and ending with 0. Other
 3376: Forth systems may behave differently, even if they support @code{FOR}
 3377: loops. To avoid problems, don't use @code{FOR} loops.
 3378: 
 3379: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
 3380: @subsection Arbitrary control structures
 3381: @cindex control structures, user-defined
 3382: 
 3383: @cindex control-flow stack
 3384: ANS Forth permits and supports using control structures in a non-nested
 3385: way. Information about incomplete control structures is stored on the
 3386: control-flow stack. This stack may be implemented on the Forth data
 3387: stack, and this is what we have done in Gforth.
 3388: 
 3389: @cindex @code{orig}, control-flow stack item
 3390: @cindex @code{dest}, control-flow stack item
 3391: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
 3392: entry represents a backward branch target. A few words are the basis for
 3393: building any control structure possible (except control structures that
 3394: need storage, like calls, coroutines, and backtracking).
 3395: 
 3396: doc-if
 3397: doc-ahead
 3398: doc-then
 3399: doc-begin
 3400: doc-until
 3401: doc-again
 3402: doc-cs-pick
 3403: doc-cs-roll
 3404: 
 3405: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
 3406: manipulate the control-flow stack in a portable way. Without them, you
 3407: would need to know how many stack items are occupied by a control-flow
 3408: entry (many systems use one cell. In Gforth they currently take three,
 3409: but this may change in the future).
 3410: 
 3411: Some standard control structure words are built from these words:
 3412: 
 3413: doc-else
 3414: doc-while
 3415: doc-repeat
 3416: 
 3417: Gforth adds some more control-structure words:
 3418: 
 3419: doc-endif
 3420: doc-?dup-if
 3421: doc-?dup-0=-if
 3422: 
 3423: Counted loop words constitute a separate group of words:
 3424: 
 3425: doc-?do
 3426: doc-+do
 3427: doc-u+do
 3428: doc--do
 3429: doc-u-do
 3430: doc-do
 3431: doc-for
 3432: doc-loop
 3433: doc-+loop
 3434: doc--loop
 3435: doc-next
 3436: doc-leave
 3437: doc-?leave
 3438: doc-unloop
 3439: doc-done
 3440: 
 3441: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
 3442: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
 3443: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
 3444: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
 3445: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
 3446: resolved (by using one of the loop-ending words or @code{DONE}).
 3447: 
 3448: Another group of control structure words are:
 3449: 
 3450: doc-case
 3451: doc-endcase
 3452: doc-of
 3453: doc-endof
 3454: 
 3455: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
 3456: @code{CS-ROLL}.
 3457: 
 3458: @subsubsection Programming Style
 3459: 
 3460: In order to ensure readability we recommend that you do not create
 3461: arbitrary control structures directly, but define new control structure
 3462: words for the control structure you want and use these words in your
 3463: program. For example, instead of writing:
 3464: 
 3465: @example
 3466: BEGIN
 3467:   ...
 3468: IF [ 1 CS-ROLL ]
 3469:   ...
 3470: AGAIN THEN
 3471: @end example
 3472: 
 3473: @noindent
 3474: we recommend defining control structure words, e.g.,
 3475: 
 3476: @example
 3477: : WHILE ( DEST -- ORIG DEST )
 3478:  POSTPONE IF
 3479:  1 CS-ROLL ; immediate
 3480: 
 3481: : REPEAT ( orig dest -- )
 3482:  POSTPONE AGAIN
 3483:  POSTPONE THEN ; immediate
 3484: @end example
 3485: 
 3486: @noindent
 3487: and then using these to create the control structure:
 3488: 
 3489: @example
 3490: BEGIN
 3491:   ...
 3492: WHILE
 3493:   ...
 3494: REPEAT
 3495: @end example
 3496: 
 3497: That's much easier to read, isn't it? Of course, @code{REPEAT} and
 3498: @code{WHILE} are predefined, so in this example it would not be
 3499: necessary to define them.
 3500: 
 3501: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
 3502: @subsection Calls and returns
 3503: @cindex calling a definition
 3504: @cindex returning from a definition
 3505: 
 3506: @cindex recursive definitions
 3507: A definition can be called simply be writing the name of the definition
 3508: to be called. Normally a definition is invisible during its own
 3509: definition. If you want to write a directly recursive definition, you
 3510: can use @code{recursive} to make the current definition visible, or
 3511: @code{recurse} to call the current definition directly.
 3512: 
 3513: doc-recursive
 3514: doc-recurse
 3515: 
 3516: @comment TODO add example of the two recursion methods
 3517: @quotation
 3518: @progstyle
 3519: I prefer using @code{recursive} to @code{recurse}, because calling the
 3520: definition by name is more descriptive (if the name is well-chosen) than
 3521: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
 3522: implementation, it is much better to read (and think) ``now sort the
 3523: partitions'' than to read ``now do a recursive call''.
 3524: @end quotation
 3525: 
 3526: For mutual recursion, use @code{Defer}red words, like this:
 3527: 
 3528: @example
 3529: Defer foo
 3530: 
 3531: : bar ( ... -- ... )
 3532:  ... foo ... ;
 3533: 
 3534: :noname ( ... -- ... )
 3535:  ... bar ... ;
 3536: IS foo
 3537: @end example
 3538: 
 3539: Deferred words are discussed in more detail in @ref{Simple
 3540: Defining Words}.
 3541: 
 3542: The current definition returns control to the calling definition when
 3543: the end of the definition is reached or @code{EXIT} is encountered.
 3544: 
 3545: doc-exit
 3546: doc-;s
 3547: 
 3548: @node Exception Handling,  , Calls and returns, Control Structures
 3549: @subsection Exception Handling
 3550: @cindex exceptions
 3551: 
 3552: If your program detects a fatal error condition, the simplest action
 3553: that it can take is to @code{quit}. This resets the return stack and
 3554: restarts the text interpreter, but does not print any error message.
 3555: 
 3556: The next stage in severity is to execute @code{abort}, which has the
 3557: same effect as @code{quit}, with the addition that it resets the data
 3558: stack.
 3559: 
 3560: A slightly more sophisticated approach is use use @code{abort"}, which
 3561: compiles a string to be used as an error message and does a conditional
 3562: @code{abort} at run-time. For example:
 3563: 
 3564: @example
 3565: @kbd{: checker abort" That flag was true" ." A false flag" ;@key{RET}}  ok
 3566: @kbd{0 checker@key{RET}} A false flag ok
 3567: @kbd{1 checker@key{RET}}
 3568: :1: That flag was true
 3569: 1 checker
 3570:   ^^^^^^^
 3571: $400D1648 throw 
 3572: $400E4660
 3573: @end example
 3574: 
 3575: These simple techniques allow a program to react to a fatal error
 3576: condition, but they are not exactly user-friendly. The ANS Forth
 3577: Exception word set provides the pair of words @code{throw} and
 3578: @code{catch}, which can be used to provide sophisticated error-handling.
 3579: 
 3580: @code{catch} has a similar behaviour to @code{execute}, in that it takes
 3581: an @i{xt} as a parameter and starts execution of the xt. However,
 3582: before passing control to the xt, @code{catch} pushes an
 3583: @dfn{exception frame} onto the @dfn{exception stack}. This exception
 3584: frame is used to restore the system to a known state if a detected error
 3585: occurs during the execution of the xt. A typical way to use @code{catch}
 3586: would be:
 3587: 
 3588: @example
 3589: ... ['] foo catch IF ...
 3590: @end example
 3591: 
 3592: @c TOS is undefined. - anton
 3593: Whilst @code{foo} executes, it can call other words to any level of
 3594: nesting, as usual.  If @code{foo} (and all the words that it calls)
 3595: execute successfully, control will ultimately pass to the word following
 3596: the @code{catch}, and there will be a 0 at TOS.  However, if any word
 3597: detects an error, it can terminate the execution of @code{foo} by
 3598: pushing a non-zero error code onto the stack and then performing a
 3599: @code{throw}. The execution of @code{throw} will pass control to the
 3600: word following the @code{catch}, but this time the TOS will hold the
 3601: error code. Therefore, the @code{IF} in the example can be used to
 3602: determine whether @code{foo} executed successfully.
 3603: 
 3604: This simple example shows how you can use @code{throw} and @code{catch}
 3605: to ``take over'' exception handling from the system:
 3606: @example
 3607: : my-div ['] / catch if ." DIVIDE ERROR" else ." OK.. " . then ;
 3608: @end example
 3609: 
 3610: The next example is more sophisticated and shows a multi-level
 3611: @code{throw} and @code{catch}. To understand this example, start at the
 3612: definition of @code{top-level} and work backwards:
 3613: 
 3614: @example
 3615: : lowest-level ( -- c )
 3616:     key dup 27 = if
 3617: 	1 throw \ ESCAPE key pressed
 3618:     else
 3619: 	." lowest-level successfull" CR
 3620:     then
 3621: ;
 3622: 
 3623: : lower-level ( -- c )
 3624:     lowest-level
 3625:     \ at this level consider a CTRL-U to be a fatal error
 3626:     dup 21 = if \ CTRL-U
 3627: 	2 throw
 3628:     else
 3629: 	." lower-level successfull" CR
 3630:     then
 3631: ;
 3632: 
 3633: : low-level ( -- c )
 3634:     ['] lower-level catch
 3635:     ?dup if
 3636: 	\ error occurred - do we recognise it?
 3637: 	dup 1 = if
 3638: 	    \ ESCAPE key pressed.. pretend it was an E
 3639: 	    [char] E
 3640: 	else throw \ propogate the error upwards
 3641: 	then
 3642:     then
 3643:     ." low-level successfull" CR
 3644: ;
 3645: 
 3646: : top-level ( -- )
 3647:     CR ['] low-level catch \ CATCH is used like EXECUTE
 3648:     ?dup if \ error occurred..
 3649: 	." Error " . ." occurred - contact your supplier"
 3650:     else
 3651: 	." The '" emit ." ' key was pressed" CR
 3652:     then
 3653: ;
 3654: @end example
 3655: 
 3656: The ANS Forth document assigns @code{throw} codes thus:
 3657: 
 3658: @itemize @bullet
 3659: @item
 3660: codes in the range -1 -- -255 are reserved to be assigned by the
 3661: Standard. Assignments for codes in the range -1 -- -58 are currently
 3662: documented in the Standard. In particular, @code{-1 throw} is equivalent
 3663: to @code{abort} and @code{-2 throw} is equivalent to @code{abort"}.
 3664: @item
 3665: codes in the range -256 -- -4095 are reserved to be assigned by the system.
 3666: @item
 3667: all other codes may be assigned by programs.
 3668: @end itemize
 3669: 
 3670: Gforth provides the word @code{exception} as a mechanism for assigning
 3671: system throw codes to applications. This allows multiple applications to
 3672: co-exist in memory without any clash of @code{throw} codes. A definition
 3673: of @code{exception} in ANS Forth is provided in
 3674: @file{compat/exception.fs}.
 3675: 
 3676: doc-quit
 3677: doc-abort
 3678: doc-abort"
 3679: 
 3680: doc-catch
 3681: doc-throw
 3682: doc---exception-exception
 3683: 
 3684: 
 3685: @c -------------------------------------------------------------
 3686: @node Defining Words, The Text Interpreter, Control Structures, Words
 3687: @section Defining Words
 3688: @cindex defining words
 3689: 
 3690: @menu
 3691: * Simple Defining Words::       Variables, values and constants
 3692: * Colon Definitions::
 3693: * User-defined Defining Words::
 3694: * Supplying names::
 3695: * Interpretation and Compilation Semantics::
 3696: @end menu
 3697: 
 3698: @node Simple Defining Words, Colon Definitions, Defining Words, Defining Words
 3699: @subsection Simple Defining Words
 3700: @cindex simple defining words
 3701: @cindex defining words, simple
 3702: 
 3703: @c split this section?
 3704: 
 3705: Defining words are used to create new entries in the dictionary. The
 3706: simplest defining word is @code{CREATE}. @code{CREATE} is used like
 3707: this:
 3708: 
 3709: @example
 3710: CREATE new-word1
 3711: @end example
 3712: 
 3713: @code{CREATE} is a parsing word that generates a dictionary entry for
 3714: @code{new-word1}. When @code{new-word1} is executed, all that it does is
 3715: leave an address on the stack. The address represents the value of
 3716: the data space pointer (@code{HERE}) at the time that @code{new-word1}
 3717: was defined. Therefore, @code{CREATE} is a way of associating a name
 3718: with the address of a region of memory.
 3719: 
 3720: doc-create
 3721: 
 3722: By extending this example to reserve some memory in data space, we end
 3723: up with a @i{variable}. Here are two different ways to do it:
 3724: 
 3725: @example
 3726: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
 3727: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
 3728: @end example
 3729: 
 3730: The variable can be examined and modified using @code{@@} (``fetch'') and
 3731: @code{!} (``store'') like this:
 3732: 
 3733: @example
 3734: new-word2 @@ .      \ get address, fetch from it and display
 3735: 1234 new-word2 !   \ new value, get address, store to it
 3736: @end example
 3737: 
 3738: As a final refinement, the whole code sequence can be wrapped up in a
 3739: defining word (pre-empting the subject of the next section), making it
 3740: easier to create new variables:
 3741: 
 3742: @example
 3743: : myvariable ( "name" -- a-addr ) CREATE 0 , ;
 3744: 
 3745: myvariable foo
 3746: myvariable joe
 3747: 
 3748: 45 3 * foo !   \ set foo to 135
 3749: 1234 joe !     \ set joe to 1234
 3750: 3 joe +!       \ increment joe by 3.. to 1237
 3751: @end example
 3752: 
 3753: Not surprisingly, there is no need to define @code{myvariable}, since
 3754: Forth already has a definition @code{Variable}. It behaves in exactly
 3755: the same way as @code{myvariable}. Forth also provides @code{2Variable}
 3756: and @code{fvariable} for double and floating-point variables,
 3757: respectively.
 3758: 
 3759: doc-variable
 3760: doc-2variable
 3761: doc-fvariable
 3762: 
 3763: @cindex arrays
 3764: A similar mechanism can be used to create arrays. For example, an
 3765: 80-character text input buffer:
 3766: 
 3767: @example
 3768: CREATE text-buf 80 chars allot
 3769: 
 3770: text-buf 0 chars c@@ \ the 1st character (offset 0)
 3771: text-buf 3 chars c@@ \ the 4th character (offset 3)
 3772: @end example
 3773: 
 3774: You can build arbitrarily complex data structures by allocating
 3775: appropriate areas of memory. @xref{Structures} for further discussions
 3776: of this, and to learn about some Gforth tools that make it easier.
 3777: 
 3778: @cindex user variables
 3779: @cindex user space
 3780: The defining word @code{User} behaves in the same way as @code{Variable}.
 3781: The difference is that it reserves space in @i{user (data) space} rather
 3782: than normal data space. In a Forth system that has a multi-tasker, each
 3783: task has its own set of user variables.
 3784: 
 3785: doc-user
 3786: 
 3787: @comment TODO is that stuff about user variables strictly correct? Is it
 3788: @comment just terminal tasks that have user variables?
 3789: @comment should document tasker.fs (with some examples) elsewhere
 3790: @comment in this manual, then expand on user space and user variables.
 3791: 
 3792: After @code{CREATE} and @code{Variable}s, the next defining word to
 3793: consider is @code{Constant}. @code{Constant} allows you to declare a
 3794: fixed value and refer to it by name. For example:
 3795: 
 3796: @example
 3797: 12 Constant INCHES-PER-FOOT
 3798: 3E+08 fconstant SPEED-O-LIGHT
 3799: @end example
 3800: 
 3801: A @code{Variable} can be both read and written, so its run-time
 3802: behaviour is to supply an address through which its current value can be
 3803: manipulated. In contrast, the value of a @code{Constant} cannot be
 3804: changed once it has been declared@footnote{Well, often it can be -- but
 3805: not in a Standard, portable way. It's safer to use a @code{Value} (read
 3806: on).} so it's not necessary to supply the address -- it is more
 3807: efficient to return the value of the constant directly. That's exactly
 3808: what happens; the run-time effect of a constant is to put its value on
 3809: the top of the stack (@ref{User-defined Defining Words} describes one
 3810: way of implementing @code{Constant}).
 3811: 
 3812: Gforth also provides @code{2Constant} and @code{fconstant} for defining
 3813: double and floating-point constants, respectively.
 3814: 
 3815: doc-constant
 3816: doc-2constant
 3817: doc-fconstant
 3818: 
 3819: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
 3820: Constants in Forth behave differently from their equivalents in other
 3821: programming languages. In other languages, a constant (such as an EQU in
 3822: assembler or a #define in C) only exists at compile-time; in the
 3823: executable program the constant has been translated into an absolute
 3824: number and, unless you are using a symbolic debugger, it's impossible to
 3825: know what abstract thing that number represents. In Forth a constant has
 3826: an entry in the header space and remains there after the code that
 3827: uses it has been defined. In fact, it must remain in the dictionary
 3828: since it has run-time duties to perform. For example:
 3829: 
 3830: @example
 3831: 12 Constant INCHES-PER-FOOT
 3832: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
 3833: @end example
 3834: 
 3835: @cindex in-lining of constants
 3836: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
 3837: associated with the constant @code{INCHES-PER-FOOT}. If you use
 3838: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
 3839: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
 3840: attempt to optimise constants by in-lining them where they are used. You
 3841: can force Gforth to in-line a constant like this:
 3842: 
 3843: @example
 3844: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
 3845: @end example
 3846: 
 3847: If you use @code{see} to decompile @i{this} version of
 3848: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
 3849: longer present. @xref{Interpret/Compile states} and @ref{Literals} on
 3850: how this works.
 3851: 
 3852: In-lining constants in this way might improve execution time
 3853: fractionally, and can ensure that a constant is now only referenced at
 3854: compile-time. However, the definition of the constant still remains in
 3855: the dictionary. Some Forth compilers provide a mechanism for controlling
 3856: a second dictionary for holding transient words such that this second
 3857: dictionary can be deleted later in order to recover memory
 3858: space. However, there is no standard way of doing this.
 3859: 
 3860: One aspect of constants and variables that can sometimes be confusing is
 3861: that they have different stack effects; one returns its value whilst the
 3862: other returns the address of its value. The defining word @code{Value}
 3863: provides an alternative to @code{Variable}, and has the same stack
 3864: effect as a constant. A @code{Value} needs an additional word, @code{TO}
 3865: to allow its value to be changed. Here are some examples:
 3866: 
 3867: @example
 3868: 12 Value APPLES \ a Value is initialised when it is declared.. like a
 3869:                 \ constant but unlike a variable
 3870: 34 TO APPLES    \ Change the value of APPLES. TO is a parsing word
 3871: APPLES          \ puts 34 on the top of the stack.
 3872: @end example
 3873: 
 3874: doc-value
 3875: doc-to
 3876: 
 3877: The defining word @code{Defer} allows you to define a word by name
 3878: without defining its behaviour; the definition of its behaviour is
 3879: deferred. Here are two situation where this can be useful:
 3880: 
 3881: @itemize @bullet
 3882: @item
 3883: Where you want to allow the behaviour of a word to be altered later, and
 3884: for all precompiled references to the word to change when its behaviour
 3885: is changed.
 3886: @item
 3887: For mutual recursion; @xref{Calls and returns}.
 3888: @end itemize
 3889: 
 3890: In the following example, @code{foo} always invokes the version of
 3891: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
 3892: always invokes the version that prints ``@code{Hello}''. There is no way
 3893: of getting @code{foo} to use the later version without re-ordering the
 3894: source code and recompilng it.
 3895: 
 3896: @example
 3897: : greet ." Good morning" ;
 3898: : foo ... greet ... ;
 3899: : greet ." Hello" ;
 3900: : bar ... greet ... ;
 3901: @end example
 3902: 
 3903: This problem can be solved by defining @code{greet} as a @code{Defer}red
 3904: word. The behaviour of a @code{Defer}red word can be defined and
 3905: redefined at any time by using @code{IS} to associate the xt of a
 3906: previously-defined word with it. The previous example becomes:
 3907: 
 3908: @example
 3909: Defer greet
 3910: : foo ... greet ... ;
 3911: : bar ... greet ... ;
 3912: : greet1 ." Good morning" ;
 3913: : greet2 ." Hello" ;
 3914: ' greet2 <IS> greet  \ make greet behave like greet2
 3915: @end example
 3916: 
 3917: One thing to note is that @code{<IS>} consumes it's name when it is
 3918: executed.  If you want to specify the name at compile time, use
 3919: @code{[IS]}:
 3920: 
 3921: @example
 3922: : set-greet ( xt -- )
 3923:   [IS] greet ;
 3924: 
 3925: ' greet1 set-greet
 3926: @end example
 3927: 
 3928: A deferred word can only inherit default semantics from the xt (because
 3929: that is all that an xt can represent -- @pxref{Tokens for Words} for
 3930: more discussion of this). However, the semantics of the deferred word
 3931: itself can be modified at the time that it is defined. For example:
 3932: 
 3933: @example
 3934: : bar .... ; compile-only
 3935: Defer fred immediate
 3936: Defer jim
 3937: 
 3938: ' bar <IS> jim  \ jim has default semantics
 3939: ' bar <IS> fred \ fred is immediate
 3940: @end example
 3941: 
 3942: doc-defer
 3943: doc-<is>
 3944: doc-[is]
 3945: @comment TODO document these: what's defers [is]
 3946: doc-what's
 3947: doc-defers
 3948: 
 3949: Definitions in ANS Forth for @code{defer}, @code{<is>} and
 3950: @code{[is]} are provided in @file{compat/defer.fs}.
 3951: 
 3952: The defining word @code{Alias} allows you to define a word by name that
 3953: has the same behaviour as some other word. Here are two situation where
 3954: this can be useful:
 3955: 
 3956: @itemize @bullet
 3957: @item
 3958: When you want access to a word's definition from a different word list
 3959: (for an example of this, see the definition of the @code{Root} word list
 3960: in the Gforth source).
 3961: @item
 3962: When you want to create a synonym; a definition that can be known by
 3963: either of two names (for example, @code{THEN} and @code{ENDIF} are
 3964: aliases).
 3965: @end itemize
 3966: 
 3967: The word whose behaviour the alias is to inherit is represented by an
 3968: xt. Therefore, the alias only inherits default semantics from its
 3969: ancestor. The semantics of the alias itself can be modified at the time
 3970: that it is defined. For example:
 3971: 
 3972: @example
 3973: : foo ... ; immediate
 3974: 
 3975: ' foo Alias bar \ bar is not an immediate word
 3976: ' foo Alias fooby immediate \ fooby is an immediate word
 3977: @end example
 3978: 
 3979: @c "combined words" is an undefined term
 3980: Words that are aliases have the same xt, different headers in the
 3981: dictionary, and consequently different name tokens (@pxref{Tokens for
 3982: Words}) and possibly different immediate flags.  An alias can only have
 3983: default or immediate compilation semantics; you can define aliases for
 3984: combined words with @code{interpret/compile:}.
 3985: 
 3986: @c distribute this to the appropriate paragraphs? - anton
 3987: doc-alias
 3988: 
 3989: @node Colon Definitions, User-defined Defining Words, Simple Defining Words, Defining Words
 3990: @subsection Colon Definitions
 3991: @cindex colon definitions
 3992: 
 3993: @example
 3994: : name ( ... -- ... )
 3995:     word1 word2 word3 ;
 3996: @end example
 3997: 
 3998: @noindent
 3999: Creates a word called @code{name} that, upon execution, executes
 4000: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
 4001: 
 4002: The explanation above is somewhat superficial. @xref{Your first
 4003: definition} for simple examples of colon definitions, then
 4004: @xref{Interpretation and Compilation Semantics} for an in-depth
 4005: discussion of some of the issues involved.
 4006: 
 4007: doc-:
 4008: doc-;
 4009: 
 4010: @node User-defined Defining Words, Supplying names, Colon Definitions, Defining Words
 4011: @subsection User-defined Defining Words
 4012: @cindex user-defined defining words
 4013: @cindex defining words, user-defined
 4014: 
 4015: You can create a new defining word by wrapping defining-time code around
 4016: an existing defining word and putting the sequence in a colon
 4017: definition. For example, suppose that you have a word @code{stats} that
 4018: gathers statistics about colon definitions given the @i{xt} of the
 4019: definition, and you want every colon definition in your application to
 4020: make a call to @code{stats}. You can define and use a new version of
 4021: @code{:} like this:
 4022: 
 4023: @example
 4024: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
 4025:   ... ;  \ other code
 4026: 
 4027: : my: : lastxt postpone literal ['] stats compile, ;
 4028: 
 4029: my: foo + - ;
 4030: @end example
 4031: 
 4032: When @code{foo} is defined using @code{my:} these steps occur:
 4033: 
 4034: @itemize @bullet
 4035: @item
 4036: @code{my:} is executed.
 4037: @item
 4038: The @code{:} within the definition (the one between @code{my:} and
 4039: @code{lastxt}) is executed, and does just what it always does; it parses
 4040: the input stream for a name, builds a dictionary header for the name
 4041: @code{foo} and switches @code{state} from interpret to compile.
 4042: @item
 4043: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
 4044: being defined -- @code{foo} -- onto the stack.
 4045: @item
 4046: The code that was produced by @code{postpone literal} is executed; this
 4047: causes the value on the stack to be compiled as a literal in the code
 4048: area of @code{foo}.
 4049: @item
 4050: The code @code{['] stats} compiles a literal into the definition of
 4051: @code{my:}. When @code{compile,} is executed, that literal -- the
 4052: execution token for @code{stats} -- is layed down in the code area of
 4053: @code{foo} , following the literal@footnote{Strictly speaking, the
 4054: mechanism that @code{compile,} uses to convert an @i{xt} into something
 4055: in the code area is implementation-dependent. A threaded implementation
 4056: might spit out the execution token directly whilst another
 4057: implementation might spit out a native code sequence.}.
 4058: @item
 4059: At this point, the execution of @code{my:} is complete, and control
 4060: returns to the text interpreter. The text interpreter is in compile
 4061: state, so subsequent text @code{+ -} is compiled into the definition of
 4062: @code{foo} and the @code{;} terminates the definition as always.
 4063: @end itemize
 4064: 
 4065: You can use @code{see} to decompile a word that was defined using
 4066: @code{my:} and see how it is different from a normal @code{:}
 4067: definition. For example:
 4068: 
 4069: @example
 4070: : bar + - ;  \ like foo but using : rather than my:
 4071: see bar
 4072: : bar
 4073:   + - ;
 4074: see foo
 4075: : foo
 4076:   107645672 stats + - ;
 4077: 
 4078: \ use ' stats . to show that 107645672 is the xt for stats
 4079: @end example
 4080: 
 4081: 
 4082: @c a deferred word is not neccessary for these examples. - anton
 4083: Rather than edit your application's source code to change every @code{:}
 4084: to a @code{my:}, use a deferred word:
 4085: 
 4086: @example
 4087: : real: : ;     \ retain access to the original
 4088: defer :         \ redefine as a deferred word
 4089: ' my: IS :      \ use special version of :
 4090: \
 4091: \ load application here
 4092: \
 4093: ' real: IS :    \ go back to the original
 4094: @end example
 4095: 
 4096: You can use techniques like this to make new defining words in terms of
 4097: @i{any} existing defining word.
 4098: 
 4099: 
 4100: @cindex defining defining words
 4101: @cindex @code{CREATE} ... @code{DOES>}
 4102: If you want the words defined with your defining words to behave
 4103: differently from words defined with standard defining words, you can
 4104: write your defining word like this:
 4105: 
 4106: @example
 4107: : def-word ( "name" -- )
 4108:     CREATE @i{code1}
 4109: DOES> ( ... -- ... )
 4110:     @i{code2} ;
 4111: 
 4112: def-word name
 4113: @end example
 4114: 
 4115: @cindex child words
 4116: This fragment defines a @dfn{defining word} @code{def-word} and then
 4117: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
 4118: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
 4119: is not executed at this time. The word @code{name} is sometimes called a
 4120: @dfn{child} of @code{def-word}.
 4121: 
 4122: When you execute @code{name}, the address of the body of @code{name} is
 4123: put on the data stack and @i{code2} is executed (the address of the body
 4124: of @code{name} is the address @code{HERE} returns immediately after the
 4125: @code{CREATE}).
 4126: 
 4127: @cindex atavism in child words
 4128: You can use @code{def-word} to define a set of child words that behave
 4129: differently, though atavistically; they all have a common run-time
 4130: behaviour determined by @i{code2}. Typically, the @i{code1} sequence
 4131: builds a data area in the body of the child word. The structure of the
 4132: data is common to all children of @code{def-word}, but the data values
 4133: are specific -- and private -- to each child word. When a child word is
 4134: executed, the address of its private data area is passed as a parameter
 4135: on TOS to be used and manipulated@footnote{It is legitimate both to read
 4136: and write to this data area.} by @i{code2}.
 4137: 
 4138: The two fragments of code that make up the defining words act (are
 4139: executed) at two completely separate times:
 4140: 
 4141: @itemize @bullet
 4142: @item
 4143: At @i{define time}, the defining word executes @i{code1} to generate a
 4144: child word
 4145: @item
 4146: At @i{child execution time}, when a child word is invoked, @i{code2}
 4147: is executed, using parameters (data) that are private and specific to
 4148: the child word.
 4149: @end itemize
 4150: 
 4151: @c NAC I think this is a really bad example, because it diminishes
 4152: @c rather than emphasising the fact that some important stuff happens
 4153: @c at define time, and other important stuff happens at child-invocation
 4154: @c time, and that those two times are potentially very different.
 4155: 
 4156: @c Well, IMO CREATE-DOES> is usually presented with much ado, making
 4157: @c people think that it's hard to understand, and making those people who
 4158: @c understand it easily think that it's hyped.  I prefer presenting it in a
 4159: @c diminished way and only emphasize the special issues later. - anton
 4160: 
 4161: In other words, if you make the following definitions:
 4162: @example
 4163: : def-word1 ( "name" -- )
 4164:     CREATE @i{code1} ;
 4165: 
 4166: : action1 ( ... -- ... )
 4167:     @i{code2} ;
 4168: 
 4169: def-word1 name1
 4170: @end example
 4171: 
 4172: Using @code{name1 action1} is equivalent to using @code{name}.
 4173: 
 4174: The classic example is that you can define @code{CONSTANT} in this way:
 4175: 
 4176: @example
 4177: : CONSTANT ( w "name" -- )
 4178:     CREATE ,
 4179: DOES> ( -- w )
 4180:     @@ ;
 4181: @end example
 4182: 
 4183: @comment There is a beautiful description of how this works and what
 4184: @comment it does in the Forthwrite 100th edition.. as well as an elegant
 4185: @comment commentary on the Counting Fruits problem.
 4186: 
 4187: When you create a constant with @code{5 CONSTANT five}, a set of
 4188: define-time actions take place; first a new word @code{five} is created,
 4189: then the value 5 is laid down in the body of @code{five} with
 4190: @code{,}. When @code{five} is invoked, the address of the body is put on
 4191: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
 4192: no code of its own; it simply contains a data field and a pointer to the
 4193: code that follows @code{DOES>} in its defining word. That makes words
 4194: created in this way very compact.
 4195: 
 4196: The final example in this section is intended to remind you that space
 4197: reserved in @code{CREATE}d words is @i{data} space and therefore can be
 4198: both read and written by a Standard program@footnote{Exercise: use this
 4199: example as a starting point for your own implementation of @code{Value}
 4200: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
 4201: @code{[']}.}:
 4202: 
 4203: @example
 4204: : foo ( "name" -- )
 4205:     CREATE -1 ,
 4206: DOES> ( -- )
 4207:     @@ . ;
 4208: 
 4209: foo first-word
 4210: foo second-word
 4211: 
 4212: 123 ' first-word >BODY !
 4213: @end example
 4214: 
 4215: If @code{first-word} had been a @code{CREATE}d word, we could simply
 4216: have executed it to get the address of its data field. However, since it
 4217: was defined to have @code{DOES>} actions, its execution semantics are to
 4218: perform those @code{DOES>} actions. To get the address of its data field
 4219: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
 4220: translate the xt into the address of the data field.  When you execute
 4221: @code{first-word}, it will display @code{123}. When you execute
 4222: @code{second-word} it will display @code{-1}.
 4223: 
 4224: @cindex stack effect of @code{DOES>}-parts
 4225: @cindex @code{DOES>}-parts, stack effect
 4226: In the examples above the stack comment after the @code{DOES>} specifies
 4227: the stack effect of the defined words, not the stack effect of the
 4228: following code (the following code expects the address of the body on
 4229: the top of stack, which is not reflected in the stack comment). This is
 4230: the convention that I use and recommend (it clashes a bit with using
 4231: locals declarations for stack effect specification, though).
 4232: 
 4233: @subsubsection Applications of @code{CREATE..DOES>}
 4234: @cindex @code{CREATE} ... @code{DOES>}, applications
 4235: 
 4236: You may wonder how to use this feature. Here are some usage patterns:
 4237: 
 4238: @cindex factoring similar colon definitions
 4239: When you see a sequence of code occurring several times, and you can
 4240: identify a meaning, you will factor it out as a colon definition. When
 4241: you see similar colon definitions, you can factor them using
 4242: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
 4243: that look very similar:
 4244: @example
 4245: : ori, ( reg-target reg-source n -- )
 4246:     0 asm-reg-reg-imm ;
 4247: : andi, ( reg-target reg-source n -- )
 4248:     1 asm-reg-reg-imm ;
 4249: @end example
 4250: 
 4251: @noindent
 4252: This could be factored with:
 4253: @example
 4254: : reg-reg-imm ( op-code -- )
 4255:     CREATE ,
 4256: DOES> ( reg-target reg-source n -- )
 4257:     @@ asm-reg-reg-imm ;
 4258: 
 4259: 0 reg-reg-imm ori,
 4260: 1 reg-reg-imm andi,
 4261: @end example
 4262: 
 4263: @cindex currying
 4264: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
 4265: supply a part of the parameters for a word (known as @dfn{currying} in
 4266: the functional language community). E.g., @code{+} needs two
 4267: parameters. Creating versions of @code{+} with one parameter fixed can
 4268: be done like this:
 4269: @example
 4270: : curry+ ( n1 -- )
 4271:     CREATE ,
 4272: DOES> ( n2 -- n1+n2 )
 4273:     @@ + ;
 4274: 
 4275:  3 curry+ 3+
 4276: -2 curry+ 2-
 4277: @end example
 4278: 
 4279: @subsubsection The gory details of @code{CREATE..DOES>}
 4280: @cindex @code{CREATE} ... @code{DOES>}, details
 4281: 
 4282: doc-does>
 4283: 
 4284: @cindex @code{DOES>} in a separate definition
 4285: This means that you need not use @code{CREATE} and @code{DOES>} in the
 4286: same definition; you can put the @code{DOES>}-part in a separate
 4287: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
 4288: @example
 4289: : does1 
 4290: DOES> ( ... -- ... )
 4291:     ... ;
 4292: 
 4293: : does2
 4294: DOES> ( ... -- ... )
 4295:     ... ;
 4296: 
 4297: : def-word ( ... -- ... )
 4298:     create ...
 4299:     IF
 4300:        does1
 4301:     ELSE
 4302:        does2
 4303:     ENDIF ;
 4304: @end example
 4305: 
 4306: In this example, the selection of whether to use @code{does1} or
 4307: @code{does2} is made at compile-time; at the time that the child word is
 4308: @code{CREATE}d.
 4309: 
 4310: @cindex @code{DOES>} in interpretation state
 4311: In a standard program you can apply a @code{DOES>}-part only if the last
 4312: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
 4313: will override the behaviour of the last word defined in any case. In a
 4314: standard program, you can use @code{DOES>} only in a colon
 4315: definition. In Gforth, you can also use it in interpretation state, in a
 4316: kind of one-shot mode; for example:
 4317: @example
 4318: CREATE name ( ... -- ... )
 4319:   @i{initialization}
 4320: DOES>
 4321:   @i{code} ;
 4322: @end example
 4323: 
 4324: @noindent
 4325: is equivalent to the standard:
 4326: @example
 4327: :noname
 4328: DOES>
 4329:     @i{code} ;
 4330: CREATE name EXECUTE ( ... -- ... )
 4331:     @i{initialization}
 4332: @end example
 4333: 
 4334: You can get the address of the body of a word with:
 4335: 
 4336: doc->body
 4337: 
 4338: @node Supplying names, Interpretation and Compilation Semantics, User-defined Defining Words, Defining Words
 4339: @subsection Supplying the name of a defined word
 4340: @cindex names for defined words
 4341: @cindex defining words, name parameter
 4342: 
 4343: @cindex defining words, name given in a string
 4344: By default, a defining word takes the name for the defined word from the
 4345: input stream. Sometimes you want to supply the name from a string. You
 4346: can do this with:
 4347: 
 4348: doc-nextname
 4349: 
 4350: For example:
 4351: 
 4352: @example
 4353: s" foo" nextname create
 4354: @end example
 4355: @noindent
 4356: is equivalent to:
 4357: @example
 4358: create foo
 4359: @end example
 4360: 
 4361: @cindex defining words without name
 4362: Sometimes you want to define an @dfn{anonymous word}; a word without a
 4363: name. You can do this with:
 4364: 
 4365: doc-:noname
 4366: 
 4367: This leaves the execution token for the word on the stack after the
 4368: closing @code{;}. Here's an example in which a deferred word is
 4369: initialised with an @code{xt} from an anonymous colon definition:
 4370: @example
 4371: Defer deferred
 4372: :noname ( ... -- ... )
 4373:   ... ;
 4374: IS deferred
 4375: @end example
 4376: 
 4377: @noindent
 4378: Gforth provides an alternative way of doing this, using two separate
 4379: words:
 4380: 
 4381: doc-noname
 4382: @cindex execution token of last defined word
 4383: doc-lastxt
 4384: 
 4385: @noindent
 4386: The previous example can be rewritten using @code{noname} and
 4387: @code{lastxt}:
 4388: 
 4389: @example
 4390: Defer deferred
 4391: noname : ( ... -- ... )
 4392:   ... ;
 4393: lastxt IS deferred
 4394: @end example
 4395: 
 4396: @noindent
 4397: @code{noname} and @code{nextname} work with any defining word, not just
 4398: @code{:}.
 4399: 
 4400: @code{lastxt} also works when the last word was not defined as
 4401: @code{noname}. It also has the useful property that is is valid as soon
 4402: as the header for a definition has been build. Thus:
 4403: 
 4404: @example
 4405: lastxt . : foo [ lastxt . ] ; ' foo .
 4406: @end example
 4407: 
 4408: @noindent
 4409: prints 3 numbers; the last two are the same.
 4410: 
 4411: 
 4412: @node Interpretation and Compilation Semantics,  , Supplying names, Defining Words
 4413: @subsection Interpretation and Compilation Semantics
 4414: @cindex semantics, interpretation and compilation
 4415: 
 4416: @cindex interpretation semantics
 4417: The @dfn{interpretation semantics} of a word are what the text
 4418: interpreter does when it encounters the word in interpret state. It also
 4419: appears in some other contexts, e.g., the execution token returned by
 4420: @code{' @i{word}} identifies the interpretation semantics of
 4421: @i{word} (in other words, @code{' @i{word} execute} is equivalent to
 4422: interpret-state text interpretation of @code{@i{word}}).
 4423: 
 4424: @cindex compilation semantics
 4425: The @dfn{compilation semantics} of a word are what the text interpreter
 4426: does when it encounters the word in compile state. It also appears in
 4427: other contexts, e.g, @code{POSTPONE @i{word}} compiles@footnote{In
 4428: standard terminology, ``appends to the current definition''.} the
 4429: compilation semantics of @i{word}.
 4430: 
 4431: @cindex execution semantics
 4432: The standard also talks about @dfn{execution semantics}. They are used
 4433: only for defining the interpretation and compilation semantics of many
 4434: words. By default, the interpretation semantics of a word are to
 4435: @code{execute} its execution semantics, and the compilation semantics of
 4436: a word are to @code{compile,} its execution semantics.@footnote{In
 4437: standard terminology: The default interpretation semantics are its
 4438: execution semantics; the default compilation semantics are to append its
 4439: execution semantics to the execution semantics of the current
 4440: definition.}
 4441: 
 4442: @comment TODO expand, make it co-operate with new sections on text interpreter.
 4443: 
 4444: @cindex immediate words
 4445: @cindex compile-only words
 4446: You can change the semantics of the most-recently defined word:
 4447: 
 4448: doc-immediate
 4449: doc-compile-only
 4450: doc-restrict
 4451: 
 4452: Note that ticking (@code{'}) a compile-only word gives an error
 4453: (``Interpreting a compile-only word'').
 4454: 
 4455: Gforth also allows you to define words with arbitrary combinations of
 4456: interpretation and compilation semantics.
 4457: 
 4458: doc-interpret/compile:
 4459: 
 4460: This feature was introduced for implementing @code{TO} and @code{S"}. I
 4461: recommend that you do not define such words, as cute as they may be:
 4462: they make it hard to get at both parts of the word in some contexts.
 4463: E.g., assume you want to get an execution token for the compilation
 4464: part. Instead, define two words, one that embodies the interpretation
 4465: part, and one that embodies the compilation part.  Once you have done
 4466: that, you can define a combined word with @code{interpret/compile:} for
 4467: the convenience of your users.
 4468: 
 4469: You might try to use this feature to provide an optimizing
 4470: implementation of the default compilation semantics of a word. For
 4471: example, by defining:
 4472: @example
 4473: :noname
 4474:    foo bar ;
 4475: :noname
 4476:    POSTPONE foo POSTPONE bar ;
 4477: interpret/compile: opti-foobar
 4478: @end example
 4479: 
 4480: @noindent
 4481: as an optimizing version of:
 4482: 
 4483: @example
 4484: : foobar
 4485:     foo bar ;
 4486: @end example
 4487: 
 4488: Unfortunately, this does not work correctly with @code{[compile]},
 4489: because @code{[compile]} assumes that the compilation semantics of all
 4490: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
 4491: opti-foobar} would compile compilation semantics, whereas
 4492: @code{[compile] foobar} would compile interpretation semantics.
 4493: 
 4494: @cindex state-smart words (are a bad idea)
 4495: Some people try to use @dfn{state-smart} words to emulate the feature provided
 4496: by @code{interpret/compile:} (words are state-smart if they check
 4497: @code{STATE} during execution). E.g., they would try to code
 4498: @code{foobar} like this:
 4499: 
 4500: @example
 4501: : foobar
 4502:   STATE @@
 4503:   IF ( compilation state )
 4504:     POSTPONE foo POSTPONE bar
 4505:   ELSE
 4506:     foo bar
 4507:   ENDIF ; immediate
 4508: @end example
 4509: 
 4510: Although this works if @code{foobar} is only processed by the text
 4511: interpreter, it does not work in other contexts (like @code{'} or
 4512: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
 4513: for a state-smart word, not for the interpretation semantics of the
 4514: original @code{foobar}; when you execute this execution token (directly
 4515: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
 4516: state, the result will not be what you expected (i.e., it will not
 4517: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
 4518: write them@footnote{For a more detailed discussion of this topic, see
 4519: @cite{@code{State}-smartness -- Why it is Evil and How to Exorcise it} by Anton
 4520: Ertl; presented at EuroForth '98 and available from
 4521: @url{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz}}!
 4522: 
 4523: @cindex defining words with arbitrary semantics combinations
 4524: It is also possible to write defining words that define words with
 4525: arbitrary combinations of interpretation and compilation semantics. In
 4526: general, they look like this:
 4527: 
 4528: @example
 4529: : def-word
 4530:     create-interpret/compile
 4531:     @i{code1}
 4532: interpretation>
 4533:     @i{code2}
 4534: <interpretation
 4535: compilation>
 4536:     @i{code3}
 4537: <compilation ;
 4538: @end example
 4539: 
 4540: For a @i{word} defined with @code{def-word}, the interpretation
 4541: semantics are to push the address of the body of @i{word} and perform
 4542: @i{code2}, and the compilation semantics are to push the address of
 4543: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
 4544: can also be defined like this (except that the defined constants don't
 4545: behave correctly when @code{[compile]}d):
 4546: 
 4547: @example
 4548: : constant ( n "name" -- )
 4549:     create-interpret/compile
 4550:     ,
 4551: interpretation> ( -- n )
 4552:     @@
 4553: <interpretation
 4554: compilation> ( compilation. -- ; run-time. -- n )
 4555:     @@ postpone literal
 4556: <compilation ;
 4557: @end example
 4558: 
 4559: doc-create-interpret/compile
 4560: doc-interpretation>
 4561: doc-<interpretation
 4562: doc-compilation>
 4563: doc-<compilation
 4564: 
 4565: Words defined with @code{interpret/compile:} and
 4566: @code{create-interpret/compile} have an extended header structure that
 4567: differs from other words; however, unless you try to access them with
 4568: plain address arithmetic, you should not notice this. Words for
 4569: accessing the header structure usually know how to deal with this; e.g.,
 4570: @code{'} @i{word} @code{>body} also gives you the body of a word created
 4571: with @code{create-interpret/compile}.
 4572: 
 4573: doc-postpone
 4574: @comment TODO -- expand glossary text for POSTPONE
 4575: 
 4576: @c ----------------------------------------------------------
 4577: @node The Text Interpreter, Tokens for Words, Defining Words, Words
 4578: @section  The Text Interpreter
 4579: @cindex interpreter - outer
 4580: @cindex text interpreter
 4581: @cindex outer interpreter
 4582: 
 4583: @c Should we really describe all these ugly details?  IMO the text
 4584: @c interpreter should be much cleaner, but that may not be possible within
 4585: @c ANS Forth. - anton
 4586: 
 4587: The text interpreter@footnote{This is an expanded version of the
 4588: material in @ref{Introducing the Text Interpreter}.} is an endless loop
 4589: that processes input from the current input device. It is also called
 4590: the outer interpreter, in contrast to the inner interpreter
 4591: (@pxref{Engine}) which executes the compiled Forth code on interpretive
 4592: implementations.
 4593: 
 4594: @cindex interpret state
 4595: @cindex compile state
 4596: The text interpreter operates in one of two states: @dfn{interpret
 4597: state} and @dfn{compile state}. The current state is defined by the
 4598: aptly-named variable, @code{state}.
 4599: 
 4600: This section starts by describing how the text interpreter behaves when
 4601: it is in interpret state, processing input from the user input device --
 4602: the keyboard. This is the mode that a Forth system is in after it starts
 4603: up.
 4604: 
 4605: @cindex input buffer
 4606: @cindex terminal input buffer
 4607: The text interpreter works from an area of memory called the @dfn{input
 4608: buffer}@footnote{When the text interpreter is processing input from the
 4609: keyboard, this area of memory is called the @dfn{terminal input buffer}
 4610: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
 4611: @code{#TIB}.}, which stores your keyboard input when you press the
 4612: @key{RET} key. Starting at the beginning of the input buffer, it skips
 4613: leading spaces (called @dfn{delimiters}) then parses a string (a
 4614: sequence of non-space characters) until it reaches either a space
 4615: character or the end of the buffer. Having parsed a string, it makes two
 4616: attempts to process it:
 4617: 
 4618: @cindex dictionary
 4619: @itemize @bullet
 4620: @item
 4621: It looks for the string in a @dfn{dictionary} of definitions. If the
 4622: string is found, the string names a @dfn{definition} (also known as a
 4623: @dfn{word}) and the dictionary search returns information that allows
 4624: the text interpreter to perform the word's @dfn{interpretation
 4625: semantics}. In most cases, this simply means that the word will be
 4626: executed.
 4627: @item
 4628: If the string is not found in the dictionary, the text interpreter
 4629: attempts to treat it as a number, using the rules described in
 4630: @ref{Number Conversion}. If the string represents a legal number in the
 4631: current radix, the number is pushed onto a parameter stack (the data
 4632: stack for integers, the floating-point stack for floating-point
 4633: numbers).
 4634: @end itemize
 4635: 
 4636: If both attempts fail, or if the word is found in the dictionary but has
 4637: no interpretation semantics@footnote{This happens if the word was
 4638: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
 4639: remainder of the input buffer, issues an error message and waits for
 4640: more input. If one of the attempts succeeds, the text interpreter
 4641: repeats the parsing process until the whole of the input buffer has been
 4642: processed, at which point it prints the status message ``@code{ ok}''
 4643: and waits for more input.
 4644: 
 4645: @cindex parse area
 4646: The text interpreter keeps track of its position in the input buffer by
 4647: updating a variable called @code{>IN} (pronounced ``to-in''). The value
 4648: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
 4649: of the input buffer. The region from offset @code{>IN @@} to the end of
 4650: the input buffer is called the @dfn{parse area}@footnote{In other words,
 4651: the text interpreter processes the contents of the input buffer by
 4652: parsing strings from the parse area until the parse area is empty.}.
 4653: This example shows how @code{>IN} changes as the text interpreter parses
 4654: the input buffer:
 4655: 
 4656: @example
 4657: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
 4658:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
 4659: 
 4660: 1 2 3 remaining + remaining . 
 4661: 
 4662: : foo 1 2 3 remaining SWAP remaining ;
 4663: @end example
 4664: 
 4665: @noindent
 4666: The result is:
 4667: 
 4668: @example
 4669: ->+ remaining .<-
 4670: ->.<-5  ok
 4671: 
 4672: ->SWAP remaining ;-<
 4673: ->;<-  ok
 4674: @end example
 4675: 
 4676: @cindex parsing words
 4677: The value of @code{>IN} can also be modified by a word in the input
 4678: buffer that is executed by the text interpreter.  This means that a word
 4679: can ``trick'' the text interpreter into either skipping a section of the
 4680: input buffer@footnote{This is how parsing words work.} or into parsing a
 4681: section twice. For example:
 4682: 
 4683: @example
 4684: : lat ." <<lat>>" ;
 4685: : flat ." <<flat>>" >IN DUP @@ 3 - SWAP ! ;
 4686: @end example
 4687: 
 4688: @noindent
 4689: When @code{flat} is executed, this output is produced@footnote{Exercise
 4690: for the reader: what would happen if the @code{3} were replaced with
 4691: @code{4}?}:
 4692: 
 4693: @example
 4694: <<flat>><<lat>>
 4695: @end example
 4696: 
 4697: @noindent
 4698: Two important notes about the behaviour of the text interpreter:
 4699: 
 4700: @itemize @bullet
 4701: @item
 4702: It processes each input string to completion before parsing additional
 4703: characters from the input buffer.
 4704: @item
 4705: It treats the input buffer as a read-only region (and so must your code).
 4706: @end itemize
 4707: 
 4708: @noindent
 4709: When the text interpreter is in compile state, its behaviour changes in
 4710: these ways:
 4711: 
 4712: @itemize @bullet
 4713: @item
 4714: If a parsed string is found in the dictionary, the text interpreter will
 4715: perform the word's @dfn{compilation semantics}. In most cases, this
 4716: simply means that the execution semantics of the word will be appended
 4717: to the current definition.
 4718: @item
 4719: When a number is encountered, it is compiled into the current definition
 4720: (as a literal) rather than being pushed onto a parameter stack.
 4721: @item
 4722: If an error occurs, @code{state} is modified to put the text interpreter
 4723: back into interpret state.
 4724: @item
 4725: Each time a line is entered from the keyboard, Gforth prints
 4726: ``@code{ compiled}'' rather than `` @code{ok}''.
 4727: @end itemize
 4728: 
 4729: @cindex text interpreter - input sources
 4730: When the text interpreter is using an input device other than the
 4731: keyboard, its behaviour changes in these ways:
 4732: 
 4733: @itemize @bullet
 4734: @item
 4735: When the parse area is empty, the text interpreter attempts to refill
 4736: the input buffer from the input source. When the input source is
 4737: exhausted, the input source is set back to the user input device.
 4738: @item
 4739: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
 4740: time the parse area is emptied.
 4741: @item
 4742: If an error occurs, the input source is set back to the user input
 4743: device.
 4744: @end itemize
 4745: 
 4746: @ref{Input Sources} describes this in more detail.
 4747: 
 4748: doc->in
 4749: doc-source
 4750: 
 4751: doc-tib
 4752: doc-#tib
 4753: 
 4754: @menu
 4755: * Input Sources::
 4756: * Number Conversion::
 4757: * Interpret/Compile states::
 4758: * Literals::
 4759: * Interpreter Directives::
 4760: @end menu
 4761: 
 4762: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
 4763: @subsection Input Sources
 4764: @cindex input sources
 4765: @cindex text interpreter - input sources
 4766: 
 4767: By default, the text interpreter accepts input from the user input
 4768: device (the keyboard) when Forth starts up. The text interpreter can
 4769: process input from any of these sources:
 4770: 
 4771: @itemize @bullet
 4772: @item
 4773: The user input device -- the keyboard.
 4774: @item
 4775: A file, using the words described in @ref{Forth source files}.
 4776: @item
 4777: A block, using the words described in @ref{Blocks}.
 4778: @item
 4779: A text string, using @code{evaluate}.
 4780: @end itemize
 4781: 
 4782: A program can identify the current input device from the values of
 4783: @code{source-id} and @code{blk}.
 4784: 
 4785: doc-source-id
 4786: doc-blk
 4787: 
 4788: doc-save-input
 4789: doc-restore-input
 4790: 
 4791: doc-evaluate
 4792: 
 4793: 
 4794: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
 4795: @subsection Number Conversion
 4796: @cindex number conversion
 4797: @cindex double-cell numbers, input format
 4798: @cindex input format for double-cell numbers
 4799: @cindex single-cell numbers, input format
 4800: @cindex input format for single-cell numbers
 4801: @cindex floating-point numbers, input format
 4802: @cindex input format for floating-point numbers
 4803: 
 4804: This section describes the rules that the text interpreter uses when it
 4805: tries to convert a string into a number.
 4806: 
 4807: Let <digit> represent any character that is a legal digit in the current
 4808: number base@footnote{For example, 0-9 when the number base is decimal or
 4809: 0-9, A-F when the number base is hexadecimal.}.
 4810: 
 4811: Let <decimal digit> represent any character in the range 0-9.
 4812: 
 4813: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
 4814: in the braces (@i{a} or @i{b} or neither).
 4815: 
 4816: Let * represent any number of instances of the previous character
 4817: (including none).
 4818: 
 4819: Let any other character represent itself.
 4820: 
 4821: @noindent
 4822: Now, the conversion rules are:
 4823: 
 4824: @itemize @bullet
 4825: @item
 4826: A string of the form <digit><digit>* is treated as a single-precision
 4827: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
 4828: @item
 4829: A string of the form -<digit><digit>* is treated as a single-precision
 4830: (cell-sized) negative integer, and is represented using 2's-complement
 4831: arithmetic. Examples are -45 -5681 -0
 4832: @item
 4833: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
 4834: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
 4835: (all three of these represent the same number).
 4836: @item
 4837: A string of the form -<digit><digit>*.<digit>* is treated as a
 4838: double-precision (double-cell-sized) negative integer, and is
 4839: represented using 2's-complement arithmetic. Examples are -3465. -3.465
 4840: -34.65 (all three of these represent the same number).
 4841: @item
 4842: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
 4843: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
 4844: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
 4845: number) +12.E-4
 4846: @end itemize
 4847: 
 4848: By default, the number base used for integer number conversion is given
 4849: by the contents of the variable @code{base}.  Note that a lot of
 4850: confusion can result from unexpected values of @code{base}.  If you
 4851: change @code{base} anywhere, make sure to save the old value and restore
 4852: it afterwards.  In general I recommend keeping @code{base} decimal, and
 4853: using the prefixes described below for the popular non-decimal bases.
 4854: 
 4855: doc-dpl
 4856: doc-base
 4857: doc-hex
 4858: doc-decimal
 4859: 
 4860: @cindex '-prefix for character strings
 4861: @cindex &-prefix for decimal numbers
 4862: @cindex %-prefix for binary numbers
 4863: @cindex $-prefix for hexadecimal numbers
 4864: Gforth allows you to override the value of @code{base} by using a
 4865: prefix@footnote{Some Forth implementations provide a similar scheme by
 4866: implementing @code{$} etc. as parsing words that process the subsequent
 4867: number in the input stream and push it onto the stack. For example, see
 4868: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
 4869: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
 4870: is required between the prefix and the number.} before the first digit
 4871: of an (integer) number. Four prefixes are supported:
 4872: 
 4873: @itemize @bullet
 4874: @item
 4875: @code{&} -- decimal
 4876: @item
 4877: @code{%} -- binary
 4878: @item
 4879: @code{$} -- hexadecimal
 4880: @item
 4881: @code{'} -- base @code{max-char+1}
 4882: @end itemize
 4883: 
 4884: Here are some examples, with the equivalent decimal number shown after
 4885: in braces:
 4886: 
 4887: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
 4888: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
 4889: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
 4890: &905 (905), $abc (2478), $ABC (2478).
 4891: 
 4892: @cindex number conversion - traps for the unwary
 4893: @noindent
 4894: Number conversion has a number of traps for the unwary:
 4895: 
 4896: @itemize @bullet
 4897: @item
 4898: You cannot determine the current number base using the code sequence
 4899: @code{base @@ .} -- the number base is always 10 in the current number
 4900: base. Instead, use something like @code{base @@ dec.}
 4901: @item
 4902: If the number base is set to a value greater than 14 (for example,
 4903: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
 4904: it to be intepreted as either a single-precision integer or a
 4905: floating-point number (Gforth treats it as an integer). The ambiguity
 4906: can be resolved by explicitly stating the sign of the mantissa and/or
 4907: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
 4908: ambiguity arises; either representation will be treated as a
 4909: floating-point number.
 4910: @item
 4911: There is a word @code{bin} but it does @i{not} set the number base!
 4912: It is used to specify file types.
 4913: @item
 4914: ANS Forth requires the @code{.} of a double-precision number to
 4915: be the final character in the string. Allowing the @code{.} to be
 4916: anywhere after the first digit is a Gforth extension.
 4917: @item
 4918: The number conversion process does not check for overflow.
 4919: @item
 4920: In Gforth, number conversion to floating-point numbers always use base
 4921: 10, irrespective of the value of @code{base}. In ANS Forth,
 4922: conversion to floating-point numbers whilst the value of
 4923: @code{base} is not 10 is an ambiguous condition.
 4924: @end itemize
 4925: 
 4926: @ref{Input} describes words that you can use to read numbers into your
 4927: programs.
 4928: 
 4929: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
 4930: @subsection Interpret/Compile states
 4931: @cindex Interpret/Compile states
 4932: 
 4933: A standard program is not permitted to change @code{state}
 4934: explicitly. However, it can change @code{state} implicitly, using the
 4935: words @code{[} and @code{]}. When @code{[} is executed it switches
 4936: @code{state} to interpret state, and therefore the text interpreter
 4937: starts interpreting. When @code{]} is executed it switches @code{state}
 4938: to compile state and therefore the text interpreter starts
 4939: compiling. The most common usage for these words is to compile literals,
 4940: as shown in @ref{Literals}. However, they give you the freedom to switch
 4941: modes at will.
 4942: 
 4943: @c This is a bad example: It's non-standard, and it's not necessary.
 4944: @c However, I can't think of a good example for switching into compile
 4945: @c state when there is no current word (@code{state}-smart words are not a
 4946: @c good reason).  So maybe we should use an example for switching into
 4947: @c interpret @code{state} in a colon def. - anton
 4948: 
 4949: Here is an example of building a jump-table of execution
 4950: tokens:
 4951: 
 4952: @example
 4953: : AA ." this is A" ;
 4954: : BB ." this is B" ;
 4955: : CC ." this is C" ;
 4956: 
 4957: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
 4958: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
 4959:   cells table + @ execute ;
 4960: @end example
 4961: 
 4962: @noindent
 4963: Now @code{0 go} will display ``@code{this is A}''. The table can be
 4964: built far more neatly@footnote{The source code is neater.. what is
 4965: compiled in memory in each case is identical.} like this:
 4966: 
 4967: @example
 4968: create table ] aa bb cc [
 4969: @end example
 4970: 
 4971: The problem with this code is that it is not portable; it will only work
 4972: on systems where code space and data space co-incide. The reason is that
 4973: both tables @i{compile} execution tokens -- into code space. The
 4974: Standard only allows data space to be assigned for a @code{CREATE}d
 4975: word. In addition, the Standard only allows @code{@@} to access data
 4976: space, whilst this example is using it to access code space. The only
 4977: portable, Standard way to build this table is to build it in data space,
 4978: like this:
 4979: 
 4980: @example
 4981: create table ' aa , ' bb , ' cc ,
 4982: @end example
 4983: 
 4984: @noindent
 4985: A similar technique can be used to build a table of constants:
 4986: 
 4987: @example
 4988: create primes 1 , 3 , 5 , 7 , 11 ,
 4989: @end example
 4990: 
 4991: doc-state
 4992: doc-[
 4993: doc-]
 4994: 
 4995: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
 4996: @subsection Literals
 4997: @cindex Literals
 4998: 
 4999: Often, you want to use a number within a colon definition. When you do
 5000: this, the text interpreter automatically compiles the number as a
 5001: @i{literal}. A literal is a number whose run-time effect is to be pushed
 5002: onto the stack.  If you had to do some maths to generate the number, you
 5003: might write it like this:
 5004: 
 5005: @example
 5006: : HOUR-TO-SEC ( n1 -- n2 )
 5007:   60 *      \ to minutes
 5008:   60 * ;    \ to seconds
 5009: @end example
 5010: 
 5011: It is very clear what this definition is doing, but it's inefficient
 5012: since it is performing 2 multiples at run-time. An alternative would be
 5013: to write:
 5014: 
 5015: @example
 5016: : HOUR-TO-SEC ( n1 -- n2 )
 5017:   3600 * ;  \ to seconds
 5018: @end example
 5019: 
 5020: Which does the same thing, and has the advantage of using a single
 5021: multiply. Ideally, we'd like the efficiency of the second with the
 5022: readability of the first.
 5023: 
 5024: @code{Literal} allows us to achieve that. It takes a number from the
 5025: stack and lays it down in the current definition just as though the
 5026: number had been typed directly into the definition. Our first attempt
 5027: might look like this:
 5028: 
 5029: @example
 5030: 60          \ mins per hour
 5031: 60 *        \ seconds per minute
 5032: : HOUR-TO-SEC ( n1 -- n2 )
 5033:   Literal * ;  \ to seconds
 5034: @end example
 5035: 
 5036: But this produces the error message @code{unstructured}. What happened?
 5037: The stack notation for @code{:} is (@i{ -- colon-sys}) and the size of
 5038: @i{colon-sys} is implementation-defined. In other words, once we start a
 5039: colon definition we can't portably access anything that was on the stack
 5040: before the definition began@footnote{@cite{Two Problems in ANS Forth},
 5041: by Thomas Worthington; Forth Dimensions 20(2) pages 32--34 describes
 5042: some situations where you might want to access stack items above
 5043: colon-sys, and provides a solution to the problem.}. The correct way of
 5044: solving this problem in this instance is to use @code{[ ]} like this:
 5045: 
 5046: @example
 5047: : HOUR-TO-SEC ( n1 -- n2 )
 5048:   [ 60          \ minutes per hour
 5049:     60 * ]      \ seconds per minute
 5050:   LITERAL * ;   \ to seconds
 5051: @end example
 5052: 
 5053: doc-literal
 5054: doc-]L
 5055: doc-2literal
 5056: doc-fliteral
 5057: 
 5058: @node Interpreter Directives, , Literals, The Text Interpreter
 5059: @subsection Interpreter Directives
 5060: @cindex interpreter directives
 5061: 
 5062: These words are usually used in interpret state; typically to control
 5063: which parts of a source file are processed by the text
 5064: interpreter. There are only a few ANS Forth Standard words, but Gforth
 5065: supplements these with a rich set of immediate control structure words
 5066: to compensate for the fact that the non-immediate versions can only be
 5067: used in compile state (@pxref{Control Structures}). Typical usages:
 5068: 
 5069: @example
 5070: FALSE Constant ASSEMBLER
 5071: .
 5072: .
 5073: ASSEMBLER [IF]
 5074: : ASSEMBLER-FEATURE
 5075:   ...
 5076: ;
 5077: [ENDIF]
 5078: .
 5079: .
 5080: : SEE
 5081:   ... \ general-purpose SEE code
 5082:   [ ASSEMBLER [IF] ]
 5083:   ... \ assembler-specific SEE code
 5084:   [ [ENDIF] ]
 5085: ;
 5086: @end example
 5087: 
 5088: doc-[IF]
 5089: doc-[ELSE]
 5090: doc-[THEN]
 5091: doc-[ENDIF]
 5092: 
 5093: doc-[IFDEF]
 5094: doc-[IFUNDEF]
 5095: 
 5096: doc-[?DO]
 5097: doc-[DO]
 5098: doc-[FOR]
 5099: doc-[LOOP]
 5100: doc-[+LOOP]
 5101: doc-[NEXT]
 5102: 
 5103: doc-[BEGIN]
 5104: doc-[UNTIL]
 5105: doc-[AGAIN]
 5106: doc-[WHILE]
 5107: doc-[REPEAT]
 5108: 
 5109: 
 5110: 
 5111: @c -------------------------------------------------------------
 5112: @node Tokens for Words, Word Lists, The Text Interpreter, Words
 5113: @section Tokens for Words
 5114: @cindex tokens for words
 5115: 
 5116: This section describes the creation and use of tokens that represent
 5117: words.
 5118: 
 5119: Named words have information stored in their header space entries to
 5120: indicate any non-default semantics (@pxref{Interpretation and
 5121: Compilation Semantics}). The semantics can be modified, using
 5122: @code{immediate} and/or @code{compile-only}, at the time that the words
 5123: are defined. Unnamed words have (by definition) no header space
 5124: entry, and therefore must have default semantics.
 5125: 
 5126: Named words have interpretation and compilation semantics. Unnamed words
 5127: just have execution semantics.
 5128: 
 5129: @cindex xt
 5130: @cindex execution token
 5131: The execution semantics of an unnamed word are represented by an
 5132: @dfn{execution token} (@i{xt}). As explained in @ref{Supplying names},
 5133: the execution token of the last word defined can be produced with
 5134: @code{lastxt}.
 5135: 
 5136: The interpretation semantics of a named word are also represented by an
 5137: execution token. You can produce the execution token using @code{'} or
 5138: @code{[']}. A simple example shows the difference between the two:
 5139: 
 5140: @example
 5141: : greet ( -- )   ." Hello" ;
 5142: : foo ( -- xt )  ['] greet execute ; \ ['] parses greet at compile-time
 5143: : bar ( -- )     ' execute ; \  '  parses at run-time
 5144: 
 5145: \ the next four lines all do the same thing
 5146: foo
 5147: bar greet
 5148: greet
 5149: ' greet EXECUTE
 5150: @end example
 5151: 
 5152: An execution token occupies one cell.
 5153: @cindex code field address
 5154: @cindex CFA
 5155: In Gforth, the abstract data type @i{execution token} is implemented
 5156: as a code field address (CFA).
 5157: @comment TODO note that the standard does not say what it represents..
 5158: @comment and you cannot necessarily compile it in all Forths (eg native
 5159: @comment compilers?).
 5160: 
 5161: For literals, use @code{'} in interpreted code and @code{[']} in
 5162: compiled code. Gforth's @code{'} and @code{[']} behave somewhat
 5163: unusually by complaining about compile-only words. To get the execution
 5164: token for a compile-only word @i{name}, use @code{COMP' @i{name} DROP}
 5165: or @code{[COMP'] @i{name} DROP}.
 5166: 
 5167: @cindex compilation token
 5168: The compilation semantics of a named word are represented by a
 5169: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
 5170: @i{xt} is an execution token. The compilation semantics represented by
 5171: the compilation token can be performed with @code{execute}, which
 5172: consumes the whole compilation token, with an additional stack effect
 5173: determined by the represented compilation semantics.
 5174: 
 5175: At present, the @i{w} part of a compilation token is an execution token,
 5176: and the @i{xt} part represents either @code{execute} or
 5177: @code{compile,}@footnote{Depending upon the compilation semantics of the
 5178: word. If the word has default compilation semantics, the @i{xt} will
 5179: represent @code{compile,}. Otherwise (e.g., for immediate words), the
 5180: @i{xt} will represent @code{execute}.}. However, don't rely on that
 5181: knowledge, unless necessary; future versions of Gforth may introduce
 5182: unusual compilation tokens (e.g., a compilation token that represents
 5183: the compilation semantics of a literal).
 5184: 
 5185: You can compile the compilation semantics with @code{postpone,}. I.e.,
 5186: @code{COMP' @i{word} postpone,} is equivalent to @code{postpone
 5187: @i{word}}.
 5188: 
 5189: @cindex name token
 5190: @cindex name field address
 5191: @cindex NFA
 5192: Named words are also represented by the @dfn{name token}, (@i{nt}). In
 5193: Gforth, the abstract data type @emph{name token} is implemented as a
 5194: name field address (NFA).
 5195: 
 5196: doc-execute
 5197: doc-compile,
 5198: doc-[']
 5199: doc-'
 5200: doc-[comp']
 5201: doc-comp'
 5202: doc-postpone,
 5203: 
 5204: doc-find-name
 5205: doc-name>int
 5206: doc-name?int
 5207: doc-name>comp
 5208: doc-name>string
 5209: 
 5210: @c -------------------------------------------------------------
 5211: @node Word Lists, Environmental Queries, Tokens for Words, Words
 5212: @section Word Lists
 5213: @cindex word lists
 5214: @cindex header space
 5215: 
 5216: A wordlist is a list of named words; you can add new words and look up
 5217: words by name (and you can remove words in a restricted way with
 5218: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
 5219: 
 5220: @cindex search order stack
 5221: The text interpreter searches the wordlists present in the search order
 5222: (a stack of wordlists), from the top to the bottom.  Within each
 5223: wordlist, the search starts conceptually at the newest word; i.e., if
 5224: two words in a wordlist have the same name, the newer word is found.
 5225: 
 5226: @cindex compilation word list
 5227: New words are added to the @dfn{compilation wordlist} (aka current
 5228: wordlist).
 5229: 
 5230: @cindex wid
 5231: A word list is identified by a cell-sized word list identifier (@i{wid})
 5232: in much the same way as a file is identified by a file handle. The
 5233: numerical value of the wid has no (portable) meaning, and might change
 5234: from session to session.
 5235: 
 5236: The ANS Forth ``Search order'' word set is intended to provide a set of
 5237: low-level tools that allow various different schemes to be
 5238: implemented. Gforth provides @code{vocabulary}, a traditional Forth
 5239: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
 5240: Standard Forth.
 5241: 
 5242: @comment TODO: locals section refers to here, saying that every word list (aka
 5243: @comment vocabulary) has its own methods for searching etc. Need to document that.
 5244: 
 5245: @comment the thisone- prefix is used to pick out the true definition of a
 5246: @comment word from the source files, rather than some alias.
 5247: doc-forth-wordlist
 5248: doc-definitions
 5249: doc-get-current
 5250: doc-set-current
 5251: doc-get-order
 5252: doc---thisone-set-order
 5253: doc-wordlist
 5254: doc-table
 5255: doc-push-order
 5256: doc-previous
 5257: doc-also
 5258: doc---thisone-forth
 5259: doc-only
 5260: doc---thisone-order
 5261: 
 5262: doc-find
 5263: doc-search-wordlist
 5264: 
 5265: doc-words
 5266: doc-vlist
 5267: 
 5268: doc-mappedwordlist
 5269: doc-root
 5270: doc-vocabulary
 5271: doc-seal
 5272: doc-vocs
 5273: doc-current
 5274: doc-context
 5275: 
 5276: @menu
 5277: * Why use word lists?::
 5278: * Word list examples::
 5279: @end menu
 5280: 
 5281: @node Why use word lists?, Word list examples, Word Lists, Word Lists
 5282: @subsection Why use word lists?
 5283: @cindex word lists - why use them?
 5284: 
 5285: Here are some reasons for using multiple word lists:
 5286: 
 5287: @itemize @bullet
 5288: @item
 5289: To improve compilation speed by reducing the number of header space
 5290: entries that must be searched. This is achieved by creating a new
 5291: word list that contains all of the definitions that are used in the
 5292: definition of a Forth system but which would not usually be used by
 5293: programs running on that system. That word list would be on the search
 5294: list when the Forth system was compiled but would be removed from the
 5295: search list for normal operation. This can be a useful technique for
 5296: low-performance systems (for example, 8-bit processors in embedded
 5297: systems) but is unlikely to be necessary in high-performance desktop
 5298: systems.
 5299: @item
 5300: To prevent a set of words from being used outside the context in which
 5301: they are valid. Two classic examples of this are an integrated editor
 5302: (all of the edit commands are defined in a separate word list; the
 5303: search order is set to the editor word list when the editor is invoked;
 5304: the old search order is restored when the editor is terminated) and an
 5305: integrated assembler (the op-codes for the machine are defined in a
 5306: separate word list which is used when a @code{CODE} word is defined).
 5307: @item
 5308: To prevent a name-space clash between multiple definitions with the same
 5309: name. For example, when building a cross-compiler you might have a word
 5310: @code{IF} that generates conditional code for your target system. By
 5311: placing this definition in a different word list you can control whether
 5312: the host system's @code{IF} or the target system's @code{IF} get used in
 5313: any particular context by controlling the order of the word lists on the
 5314: search order stack.
 5315: @end itemize
 5316: 
 5317: @node Word list examples, ,Why use word lists?, Word Lists
 5318: @subsection Word list examples
 5319: @cindex word lists - examples
 5320: 
 5321: Here is an example of creating and using a new wordlist using ANS
 5322: Forth Standard words:
 5323: 
 5324: @example
 5325: wordlist constant my-new-words-wordlist
 5326: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
 5327: 
 5328: \ add it to the search order
 5329: also my-new-words
 5330: 
 5331: \ alternatively, add it to the search order and make it
 5332: \ the compilation word list
 5333: also my-new-words definitions
 5334: \ type "order" to see the problem
 5335: @end example
 5336: 
 5337: The problem with this example is that @code{order} has no way to
 5338: associate the name @code{my-new-words} with the wid of the word list (in
 5339: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
 5340: that has no associated name). There is no Standard way of associating a
 5341: name with a wid.
 5342: 
 5343: In Gforth, this example can be re-coded using @code{vocabulary}, which
 5344: associates a name with a wid:
 5345: 
 5346: @example
 5347: vocabulary my-new-words
 5348: 
 5349: \ add it to the search order
 5350: my-new-words
 5351: 
 5352: \ alternatively, add it to the search order and make it
 5353: \ the compilation word list
 5354: my-new-words definitions
 5355: \ type "order" to see that the problem is solved
 5356: @end example
 5357: 
 5358: @c -------------------------------------------------------------
 5359: @node Environmental Queries, Files, Word Lists, Words
 5360: @section Environmental Queries
 5361: @cindex environmental queries
 5362: 
 5363: ANS Forth introduced the idea of ``environmental queries'' as a way
 5364: for a program running on a system to determine certain characteristics of the system.
 5365: The Standard specifies a number of strings that might be recognised by a system.
 5366: 
 5367: The Standard requires that the header space used for environmental queries
 5368: be distinct from the header space used for definitions.
 5369: 
 5370: Typically, environmental queries are supported by creating a set of
 5371: definitions in a word list that is @i{only} used during environmental
 5372: queries; that is what Gforth does. There is no Standard way of adding
 5373: definitions to the set of recognised environmental queries, but any
 5374: implementation that supports the loading of optional word sets must have
 5375: some mechanism for doing this (after loading the word set, the
 5376: associated environmental query string must return @code{true}). In
 5377: Gforth, the word list used to honour environmental queries can be
 5378: manipulated just like any other word list.
 5379: 
 5380: doc-environment?
 5381: doc-environment-wordlist
 5382: 
 5383: doc-gforth
 5384: doc-os-class
 5385: 
 5386: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
 5387: returning two items on the stack, querying it using @code{environment?}
 5388: will return an additional item; the @code{true} flag that shows that the
 5389: string was recognised.
 5390: 
 5391: @comment TODO Document the standard strings or note where they are documented herein
 5392: 
 5393: Here are some examples of using environmental queries:
 5394: 
 5395: @example
 5396: s" address-unit-bits" environment? 0=
 5397: [IF]
 5398:      cr .( environmental attribute address-units-bits unknown... ) cr
 5399: [THEN]
 5400: 
 5401: s" block" environment? [IF] DROP include block.fs [THEN]
 5402: 
 5403: s" gforth" environment? [IF] 2DROP include compat/vocabulary.fs [THEN]
 5404: 
 5405: s" gforth" environment? [IF] .( Gforth version ) TYPE
 5406:                         [ELSE] .( Not Gforth..) [THEN]
 5407: @end example
 5408: 
 5409: 
 5410: Here is an example of adding a definition to the environment word list:
 5411: 
 5412: @example
 5413: get-current environment-wordlist set-current
 5414: true constant block
 5415: true constant block-ext
 5416: set-current
 5417: @end example
 5418: 
 5419: You can see what definitions are in the environment word list like this:
 5420: 
 5421: @example
 5422: get-order 1+ environment-wordlist swap set-order words previous
 5423: @end example
 5424: 
 5425: 
 5426: @c -------------------------------------------------------------
 5427: @node Files, Blocks, Environmental Queries, Words
 5428: @section Files
 5429: @cindex files
 5430: @cindex I/O - file-handling
 5431: 
 5432: Gforth provides facilities for accessing files that are stored in the
 5433: host operating system's file-system. Files that are processed by Gforth
 5434: can be divided into two categories:
 5435: 
 5436: @itemize @bullet
 5437: @item
 5438: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
 5439: @item
 5440: Files that are processed by some other program (@dfn{general files}).
 5441: @end itemize
 5442: 
 5443: @menu
 5444: * Forth source files::
 5445: * General files::         
 5446: * Search Paths::                 
 5447: * Forth Search Paths::    
 5448: * General Search Paths::        
 5449: @end menu
 5450: 
 5451: 
 5452: @c -------------------------------------------------------------
 5453: @node Forth source files, General files, Files, Files
 5454: @subsection Forth source files
 5455: @cindex including files
 5456: @cindex Forth source files
 5457: 
 5458: The simplest way to interpret the contents of a file is to use one of
 5459: these two formats:
 5460: 
 5461: @example
 5462: include mysource.fs
 5463: s" mysource.fs" included
 5464: @end example
 5465: 
 5466: Sometimes you want to include a file only if it is not included already
 5467: (by, say, another source file). In that case, you can use one of these
 5468: fomats:
 5469: 
 5470: @example
 5471: require mysource.fs
 5472: needs mysource.fs
 5473: s" mysource.fs" required
 5474: @end example
 5475: 
 5476: @cindex stack effect of included files
 5477: @cindex including files, stack effect
 5478: I recommend that you write your source files such that interpreting them
 5479: does not change the stack. This allows using these files with
 5480: @code{required} and friends without complications. For example:
 5481: 
 5482: @example
 5483: 1 require foo.fs drop
 5484: @end example
 5485: 
 5486: doc-include-file
 5487: doc-included
 5488: doc-included?
 5489: doc-include
 5490: doc-required
 5491: doc-require
 5492: doc-needs
 5493: doc-init-included-files
 5494: 
 5495: A definition in ANS Forth for @code{required} is provided in
 5496: @file{compat/required.fs}.
 5497: 
 5498: @c -------------------------------------------------------------
 5499: @node General files, Search Paths, Forth source files, Files
 5500: @subsection General files
 5501: @cindex general files
 5502: @cindex file-handling
 5503: 
 5504: Files are opened/created by name and type. The following types are
 5505: recognised:
 5506: 
 5507: doc-r/o
 5508: doc-r/w
 5509: doc-w/o
 5510: doc-bin
 5511: 
 5512: When a file is opened/created, it returns a file identifier,
 5513: @i{wfileid} that is used for all other file commands. All file
 5514: commands also return a status value, @i{wior}, that is 0 for a
 5515: successful operation and an implementation-defined non-zero value in the
 5516: case of an error.
 5517: 
 5518: doc-open-file
 5519: doc-create-file
 5520: 
 5521: doc-close-file
 5522: doc-delete-file
 5523: doc-rename-file
 5524: doc-read-file
 5525: doc-read-line
 5526: doc-write-file
 5527: doc-write-line
 5528: doc-emit-file
 5529: doc-flush-file
 5530: 
 5531: doc-file-status
 5532: doc-file-position
 5533: doc-reposition-file
 5534: doc-file-size
 5535: doc-resize-file
 5536: 
 5537: @c ---------------------------------------------------------
 5538: @node Search Paths, Forth Search Paths, General files, Files
 5539: @subsection Search Paths
 5540: @cindex path for @code{included}
 5541: @cindex file search path
 5542: @cindex @code{include} search path
 5543: @cindex search path for files
 5544: 
 5545: If you specify an absolute filename (i.e., a filename starting with
 5546: @file{/} or @file{~}, or with @file{:} in the second position (as in
 5547: @samp{C:...})) for @code{included} and friends, that file is included
 5548: just as you would expect.
 5549: 
 5550: For relative filenames, Gforth uses a search path similar to Forth's
 5551: search order (@pxref{Word Lists}). It tries to find the given filename
 5552: in the directories present in the path, and includes the first one it
 5553: finds. There are separate search paths for Forth source files and
 5554: general files.
 5555: 
 5556: If the search path contains the directory @file{.} (as it should), this
 5557: refers to the directory that the present file was @code{included}
 5558: from. This allows files to include other files relative to their own
 5559: position (irrespective of the current working directory or the absolute
 5560: position).  This feature is essential for libraries consisting of
 5561: several files, where a file may include other files from the library.
 5562: It corresponds to @code{#include "..."} in C. If the current input
 5563: source is not a file, @file{.} refers to the directory of the innermost
 5564: file being included, or, if there is no file being included, to the
 5565: current working directory.
 5566: 
 5567: Use @file{~+} to refer to the current working directory (as in the
 5568: @code{bash}).
 5569: 
 5570: If the filename starts with @file{./}, the search path is not searched
 5571: (just as with absolute filenames), and the @file{.} has the same meaning
 5572: as described above.
 5573: 
 5574: @c ---------------------------------------------------------
 5575: @node Forth Search Paths, General Search Paths, Search Paths, Files
 5576: @subsubsection Forth Search Paths
 5577: @cindex search path control - Forth
 5578: 
 5579: The search path is initialized when you start Gforth (@pxref{Invoking
 5580: Gforth}). You can display it and change it using these words:
 5581: 
 5582: doc-.fpath
 5583: doc-fpath+
 5584: doc-fpath=
 5585: doc-open-fpath-file
 5586: 
 5587: Here is an example of using @code{fpath} and @code{require}:
 5588: 
 5589: @example
 5590: fpath= /usr/lib/forth/|./
 5591: require timer.fs
 5592: @end example
 5593: 
 5594: @c ---------------------------------------------------------
 5595: @node General Search Paths,  , Forth Search Paths, Files
 5596: @subsubsection General Search Paths
 5597: @cindex search path control - for user applications
 5598: 
 5599: Your application may need to search files in several directories, like
 5600: @code{included} does. To facilitate this, Gforth allows you to define
 5601: and use your own search paths, by providing generic equivalents of the
 5602: Forth search path words:
 5603: 
 5604: doc-.path
 5605: doc-path+
 5606: doc-path=
 5607: doc-open-path-file
 5608: 
 5609: Here's an example of creating a search path:
 5610: 
 5611: @example
 5612: \ Make a buffer for the path:
 5613: create mypath   100 chars ,     \ maximum length (is checked)
 5614:                 0 ,             \ real len
 5615:                 100 chars allot \ space for path
 5616: @end example
 5617: 
 5618: @c -------------------------------------------------------------
 5619: @node Blocks, Other I/O, Files, Words
 5620: @section Blocks
 5621: @cindex I/O - blocks
 5622: @cindex blocks
 5623: 
 5624: When you run Gforth on a modern desk-top computer, it runs under the
 5625: control of an operating system which provides certain services.  One of
 5626: these services is @var{file services}, which allows Forth source code
 5627: and data to be stored in files and read into Gforth (@pxref{Files}).
 5628: 
 5629: Traditionally, Forth has been an important programming language on
 5630: systems where it has interfaced directly to the underlying hardware with
 5631: no intervening operating system. Forth provides a mechanism, called
 5632: @dfn{blocks}, for accessing mass storage on such systems.
 5633: 
 5634: A block is a 1024-byte data area, which can be used to hold data or
 5635: Forth source code. No structure is imposed on the contents of the
 5636: block. A block is identified by its number; blocks are numbered
 5637: contiguously from 1 to an implementation-defined maximum.
 5638: 
 5639: A typical system that used blocks but no operating system might use a
 5640: single floppy-disk drive for mass storage, with the disks formatted to
 5641: provide 256-byte sectors. Blocks would be implemented by assigning the
 5642: first four sectors of the disk to block 1, the second four sectors to
 5643: block 2 and so on, up to the limit of the capacity of the disk. The disk
 5644: would not contain any file system information, just the set of blocks.
 5645: 
 5646: @cindex blocks file
 5647: On systems that do provide file services, blocks are typically
 5648: implemented by storing a sequence of blocks within a single @dfn{blocks
 5649: file}.  The size of the blocks file will be an exact multiple of 1024
 5650: bytes, corresponding to the number of blocks it contains. This is the
 5651: mechanism that Gforth uses.
 5652: 
 5653: @cindex @file{blocks.fb}
 5654: Only 1 blocks file can be open at a time. If you use block words without
 5655: having specified a blocks file, Gforth defaults to the blocks file
 5656: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
 5657: locate a blocks file (@pxref{Forth Search Paths}).
 5658: 
 5659: @cindex block buffers
 5660: When you read and write blocks under program control, Gforth uses a
 5661: number of @dfn{block buffers} as intermediate storage. These buffers are
 5662: not used when you use @code{load} to interpret the contents of a block.
 5663: 
 5664: The behaviour of the block buffers is directly analagous to that of a
 5665: cache. Each block buffer has three states:
 5666: 
 5667: @itemize @bullet
 5668: @item
 5669: Unassigned
 5670: @item
 5671: Assigned-clean
 5672: @item
 5673: Assigned-dirty
 5674: @end itemize
 5675: 
 5676: Initially, all block buffers are @i{unassigned}. In order to access a
 5677: block, the block (specified by its block number) must be assigned to a
 5678: block buffer.
 5679: 
 5680: The assignment of a block to a block buffer is performed by @code{block}
 5681: or @code{buffer}. Use @code{block} when you wish to modify the existing
 5682: contents of a block. Use @code{buffer} when you don't care about the
 5683: existing contents of the block@footnote{The ANS Forth definition of
 5684: @code{buffer} is intended not to cause disk I/O; if the data associated
 5685: with the particular block is already stored in a block buffer due to an
 5686: earlier @code{block} command, @code{buffer} will return that block
 5687: buffer and the existing contents of the block will be
 5688: available. Otherwise, @code{buffer} will simply assign a new, empty
 5689: block buffer for the block.}.
 5690: 
 5691: Once a block has been assigned to a block buffer, the block buffer state
 5692: becomes @i{assigned-clean}. Data can now be manipulated within the
 5693: block buffer.
 5694: 
 5695: When the contents of a block buffer is changed it is necessary,
 5696: @i{before calling} @code{block} @i{or} @code{buffer} @i{again}, to
 5697: either abandon the changes (by doing nothing) or commit the changes,
 5698: using @code{update}. Using @code{update} does not change the blocks
 5699: file; it simply changes a block buffer's state to @i{assigned-dirty}.
 5700: 
 5701: The word @code{flush} causes all @i{assigned-dirty} blocks to be
 5702: written back to the blocks file on disk. Leaving Gforth using @code{bye}
 5703: also causes a @code{flush} to be performed.
 5704: 
 5705: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
 5706: algorithm to assign a block buffer to a block. That means that any
 5707: particular block can only be assigned to one specific block buffer,
 5708: called (for the particular operation) the @i{victim buffer}. If the
 5709: victim buffer is @i{unassigned} or @i{assigned-clean} it can be
 5710: allocated to the new block immediately. If it is @i{assigned-dirty}
 5711: its current contents must be written out to disk before it can be
 5712: allocated to the new block.
 5713: 
 5714: Although no structure is imposed on the contents of a block, it is
 5715: traditional to display the contents as 16 lines each of 64 characters.  A
 5716: block provides a single, continuous stream of input (for example, it
 5717: acts as a single parse area) -- there are no end-of-line characters
 5718: within a block, and no end-of-file character at the end of a
 5719: block. There are two consequences of this:
 5720: 
 5721: @itemize @bullet
 5722: @item
 5723: The last character of one line wraps straight into the first character
 5724: of the following line
 5725: @item
 5726: The word @code{\} -- comment to end of line -- requires special
 5727: treatment; in the context of a block it causes all characters until the
 5728: end of the current 64-character ``line'' to be ignored.
 5729: @end itemize
 5730: 
 5731: In Gforth, when you use @code{block} with a non-existent block number,
 5732: the current block file will be extended to the appropriate size and the
 5733: block buffer will be initialised with spaces.
 5734: 
 5735: Gforth doesn't encourage the use of blocks; the mechanism is only
 5736: provided for backward compatibility -- ANS Forth requires blocks to be
 5737: available when files are.
 5738: 
 5739: Common techniques that are used when working with blocks include:
 5740: 
 5741: @itemize @bullet
 5742: @item
 5743: A screen editor that allows you to edit blocks without leaving the Forth
 5744: environment.
 5745: @item
 5746: Shadow screens; where every code block has an associated block
 5747: containing comments (for example: code in odd block numbers, comments in
 5748: even block numbers). Typically, the block editor provides a convenient
 5749: mechanism to toggle between code and comments.
 5750: @item
 5751: Load blocks; a single block (typically block 1) contains a number of
 5752: @code{thru} commands which @code{load} the whole of the application.
 5753: @end itemize
 5754: 
 5755: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
 5756: integrated into a Forth programming environment.
 5757: 
 5758: @comment TODO what about errors on open-blocks?
 5759: doc-open-blocks
 5760: doc-use
 5761: doc-get-block-fid
 5762: doc-block-position
 5763: 
 5764: doc-scr
 5765: doc-list
 5766: 
 5767: doc---block-block
 5768: doc-buffer
 5769: 
 5770: doc-update
 5771: doc-updated?
 5772: doc-save-buffers
 5773: doc-empty-buffers
 5774: doc-empty-buffer
 5775: doc-flush
 5776: 
 5777: doc-load
 5778: doc-thru
 5779: doc-+load
 5780: doc-+thru
 5781: xdoc--gforth--->
 5782: doc-block-included
 5783: 
 5784: @c -------------------------------------------------------------
 5785: @node Other I/O, Programming Tools, Blocks, Words
 5786: @section Other I/O
 5787: @cindex I/O - keyboard and display
 5788: 
 5789: @menu
 5790: * Simple numeric output::       Predefined formats
 5791: * Formatted numeric output::    Formatted (pictured) output
 5792: * String Formats::              How Forth stores strings in memory
 5793: * Displaying characters and strings:: Other stuff
 5794: * Input::                       Input
 5795: @end menu
 5796: 
 5797: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
 5798: @subsection Simple numeric output
 5799: @cindex numeric output - simple/free-format
 5800: 
 5801: The simplest output functions are those that display numbers from the
 5802: data or floating-point stacks. Floating-point output is always displayed
 5803: using base 10. Numbers displayed from the data stack use the value stored
 5804: in @code{base}.
 5805: 
 5806: doc-.
 5807: doc-dec.
 5808: doc-hex.
 5809: doc-u.
 5810: doc-.r
 5811: doc-u.r
 5812: doc-d.
 5813: doc-ud.
 5814: doc-d.r
 5815: doc-ud.r
 5816: doc-f.
 5817: doc-fe.
 5818: doc-fs.
 5819: 
 5820: Examples of printing the number 1234.5678E23 in the different floating-point output
 5821: formats are shown below:
 5822: 
 5823: @example
 5824: f. 123456779999999000000000000.
 5825: fe. 123.456779999999E24
 5826: fs. 1.23456779999999E26
 5827: @end example
 5828: 
 5829: 
 5830: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
 5831: @subsection Formatted numeric output
 5832: @cindex formatted numeric output
 5833: @cindex pictured numeric output
 5834: @cindex numeric output - formatted
 5835: 
 5836: Forth traditionally uses a technique called @dfn{pictured numeric
 5837: output} for formatted printing of integers.  In this technique, digits
 5838: are extracted from the number (using the current output radix defined by
 5839: @code{base}), converted to ASCII codes and appended to a string that is
 5840: built in a scratch-pad area of memory (@pxref{core-idef,
 5841: Implementation-defined options, Implementation-defined
 5842: options}). Arbitrary characters can be appended to the string during the
 5843: extraction process. The completed string is specified by an address
 5844: and length and can be manipulated (@code{TYPE}ed, copied, modified)
 5845: under program control.
 5846: 
 5847: All of the words described in the previous section for simple numeric
 5848: output are implemented in Gforth using pictured numeric output.
 5849: 
 5850: Three important things to remember about Pictured Numeric Output:
 5851: 
 5852: @itemize @bullet
 5853: @item
 5854: It always operates on double-precision numbers; to display a
 5855: single-precision number, convert it first (@pxref{Double precision} for
 5856: ways of doing this).
 5857: @item
 5858: It always treats the double-precision number as though it were
 5859: unsigned. The examples below show ways of printing signed numbers.
 5860: @item
 5861: The string is built up from right to left; least significant digit first.
 5862: @end itemize
 5863: 
 5864: doc-<#
 5865: doc-#
 5866: doc-#s
 5867: doc-hold
 5868: doc-sign
 5869: doc-#>
 5870: 
 5871: doc-represent
 5872: 
 5873: Here are some examples of using pictured numeric output:
 5874: 
 5875: @example
 5876: : my-u. ( u -- )
 5877:   \ Simplest use of pns.. behaves like Standard u. 
 5878:   0              \ convert to unsigned double
 5879:   <#             \ start conversion
 5880:   #s             \ convert all digits
 5881:   #>             \ complete conversion
 5882:   TYPE SPACE ;   \ display, with trailing space
 5883: 
 5884: : cents-only ( u -- )
 5885:   0              \ convert to unsigned double
 5886:   <#             \ start conversion
 5887:   # #            \ convert two least-significant digits
 5888:   #>             \ complete conversion, discard other digits
 5889:   TYPE SPACE ;   \ display, with trailing space
 5890: 
 5891: : dollars-and-cents ( u -- )
 5892:   0              \ convert to unsigned double
 5893:   <#             \ start conversion
 5894:   # #            \ convert two least-significant digits
 5895:   [char] . hold  \ insert decimal point
 5896:   #s             \ convert remaining digits
 5897:   [char] $ hold  \ append currency symbol
 5898:   #>             \ complete conversion
 5899:   TYPE SPACE ;   \ display, with trailing space
 5900: 
 5901: : my-. ( n -- )
 5902:   \ handling negatives.. behaves like Standard .
 5903:   s>d            \ convert to signed double
 5904:   swap over dabs \ leave sign byte followed by unsigned double
 5905:   <#             \ start conversion
 5906:   #s             \ convert all digits
 5907:   rot sign       \ get at sign byte, append "-" if needed
 5908:   #>             \ complete conversion
 5909:   TYPE SPACE ;   \ display, with trailing space
 5910: 
 5911: : account. ( n -- )
 5912:   \ accountants don't like minus signs, they use braces
 5913:   \ for negative numbers
 5914:   s>d            \ convert to signed double
 5915:   swap over dabs \ leave sign byte followed by unsigned double
 5916:   <#             \ start conversion
 5917:   2 pick         \ get copy of sign byte
 5918:   0< IF [char] ) hold THEN \ right-most character of output
 5919:   #s             \ convert all digits
 5920:   rot            \ get at sign byte
 5921:   0< IF [char] ( hold THEN
 5922:   #>             \ complete conversion
 5923:   TYPE SPACE ;   \ display, with trailing space
 5924: @end example
 5925: 
 5926: Here are some examples of using these words:
 5927: 
 5928: @example
 5929: 1 my-u. 1
 5930: hex -1 my-u. decimal FFFFFFFF
 5931: 1 cents-only 01
 5932: 1234 cents-only 34
 5933: 2 dollars-and-cents $0.02
 5934: 1234 dollars-and-cents $12.34
 5935: 123 my-. 123
 5936: -123 my. -123
 5937: 123 account. 123
 5938: -456 account. (456)
 5939: @end example
 5940: 
 5941: 
 5942: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
 5943: @subsection String Formats
 5944: @cindex strings - see character strings
 5945: @cindex character strings - formats
 5946: @cindex I/O - see character strings
 5947: 
 5948: Forth commonly uses two different methods for representing character
 5949: strings:
 5950: 
 5951: @itemize @bullet
 5952: @item
 5953: @cindex address of counted string
 5954: As a @dfn{counted string}, represented by a @i{c-addr}. The char
 5955: addressed by @i{c-addr} contains a character-count, @i{n}, of the
 5956: string and the string occupies the subsequent @i{n} char addresses in
 5957: memory.
 5958: @item
 5959: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
 5960: of the string in characters, and @i{c-addr} is the address of the
 5961: first byte of the string.
 5962: @end itemize
 5963: 
 5964: ANS Forth encourages the use of the second format when representing
 5965: strings on the stack, whilst conceeding that the counted string format
 5966: remains useful as a way of storing strings in memory.
 5967: 
 5968: doc-count
 5969: 
 5970: @xref{Memory Blocks} for words that move, copy and search
 5971: for strings. @xref{Displaying characters and strings,} for words that
 5972: display characters and strings.
 5973: 
 5974: 
 5975: @node Displaying characters and strings, Input, String Formats, Other I/O
 5976: @subsection Displaying characters and strings
 5977: @cindex characters - compiling and displaying
 5978: @cindex character strings - compiling and displaying
 5979: 
 5980: This section starts with a glossary of Forth words and ends with a set
 5981: of examples.
 5982: 
 5983: doc-bl
 5984: doc-space
 5985: doc-spaces
 5986: doc-emit
 5987: doc-toupper
 5988: doc-."
 5989: doc-.(
 5990: doc-type
 5991: doc-cr
 5992: @cindex cursor control
 5993: doc-at-xy
 5994: doc-page
 5995: doc-s"
 5996: doc-c"
 5997: doc-char
 5998: doc-[char]
 5999: doc-sliteral
 6000: 
 6001: As an example, consider the following text, stored in a file @file{test.fs}:
 6002: 
 6003: @example
 6004: .( text-1)
 6005: : my-word
 6006:   ." text-2" cr
 6007:   .( text-3)
 6008: ;
 6009: 
 6010: ." text-4"
 6011: 
 6012: : my-char
 6013:   [char] ALPHABET emit
 6014:   char emit
 6015: ;
 6016: @end example
 6017: 
 6018: When you load this code into Gforth, the following output is generated:
 6019: 
 6020: @example
 6021: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
 6022: @end example
 6023: 
 6024: @itemize @bullet
 6025: @item
 6026: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
 6027: is an immediate word; it behaves in the same way whether it is used inside
 6028: or outside a colon definition.
 6029: @item
 6030: Message @code{text-4} is displayed because of Gforth's added interpretation
 6031: semantics for @code{."}.
 6032: @item
 6033: Message @code{text-2} is @i{not} displayed, because the text interpreter
 6034: performs the compilation semantics for @code{."} within the definition of
 6035: @code{my-word}.
 6036: @end itemize
 6037: 
 6038: Here are some examples of executing @code{my-word} and @code{my-char}:
 6039: 
 6040: @example
 6041: @kbd{my-word @key{RET}} text-2
 6042:  ok
 6043: @kbd{my-char fred @key{RET}} Af ok
 6044: @kbd{my-char jim @key{RET}} Aj ok
 6045: @end example
 6046: 
 6047: @itemize @bullet
 6048: @item
 6049: Message @code{text-2} is displayed because of the run-time behaviour of
 6050: @code{."}.
 6051: @item
 6052: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
 6053: on the stack at run-time. @code{emit} always displays the character
 6054: when @code{my-char} is executed.
 6055: @item
 6056: @code{char} parses a string at run-time and the second @code{emit} displays
 6057: the first character of the string.
 6058: @item
 6059: If you type @code{see my-char} you can see that @code{[char]} discarded
 6060: the text ``LPHABET'' and only compiled the display code for ``A'' into the
 6061: definition of @code{my-char}.
 6062: @end itemize
 6063: 
 6064: 
 6065: 
 6066: @node Input, , Displaying characters and strings, Other I/O
 6067: @subsection Input
 6068: @cindex input
 6069: @cindex I/O - see input
 6070: @cindex parsing a string
 6071: 
 6072: @xref{String Formats} for ways of storing character strings in memory.
 6073: 
 6074: @comment TODO examples for >number >float accept key key? pad parse word refill
 6075: @comment then index them
 6076: 
 6077: doc-key
 6078: doc-key?
 6079: doc->number
 6080: doc->float
 6081: doc-accept
 6082: doc-pad
 6083: doc-parse
 6084: doc-word
 6085: doc-sword
 6086: doc-refill
 6087: @comment obsolescent words..
 6088: doc-convert
 6089: doc-query
 6090: doc-expect
 6091: doc-span
 6092: 
 6093: 
 6094: @c -------------------------------------------------------------
 6095: @node Programming Tools, Assembler and Code Words, Other I/O, Words
 6096: @section Programming Tools
 6097: @cindex programming tools
 6098: 
 6099: @menu
 6100: * Debugging::                   Simple and quick.
 6101: * Assertions::                  Making your programs self-checking.
 6102: * Singlestep Debugger::		Executing your program word by word.
 6103: @end menu
 6104: 
 6105: @node Debugging, Assertions, Programming Tools, Programming Tools
 6106: @subsection Debugging
 6107: @cindex debugging
 6108: 
 6109: Languages with a slow edit/compile/link/test development loop tend to
 6110: require sophisticated tracing/stepping debuggers to facilate
 6111: productive debugging.
 6112: 
 6113: A much better (faster) way in fast-compiling languages is to add
 6114: printing code at well-selected places, let the program run, look at
 6115: the output, see where things went wrong, add more printing code, etc.,
 6116: until the bug is found.
 6117: 
 6118: The simple debugging aids provided in @file{debugs.fs}
 6119: are meant to support this style of debugging. In addition, there are
 6120: words for non-destructively inspecting the stack and memory:
 6121: 
 6122: doc-.s
 6123: doc-f.s
 6124: 
 6125: There is a word @code{.r} but it does @i{not} display the return
 6126: stack! It is used for formatted numeric output.
 6127: 
 6128: doc-depth
 6129: doc-fdepth
 6130: doc-clearstack
 6131: doc-?
 6132: doc-dump
 6133: 
 6134: The word @code{~~} prints debugging information (by default the source
 6135: location and the stack contents). It is easy to insert. If you use Emacs
 6136: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
 6137: query-replace them with nothing). The deferred words
 6138: @code{printdebugdata} and @code{printdebugline} control the output of
 6139: @code{~~}. The default source location output format works well with
 6140: Emacs' compilation mode, so you can step through the program at the
 6141: source level using @kbd{C-x `} (the advantage over a stepping debugger
 6142: is that you can step in any direction and you know where the crash has
 6143: happened or where the strange data has occurred).
 6144: 
 6145: The default actions of @code{~~} clobber the contents of the pictured
 6146: numeric output string, so you should not use @code{~~}, e.g., between
 6147: @code{<#} and @code{#>}.
 6148: 
 6149: doc-~~
 6150: doc-printdebugdata
 6151: doc-printdebugline
 6152: 
 6153: doc-see
 6154: doc-marker
 6155: 
 6156: Here's an example of using @code{marker} at the start of a source file
 6157: that you are debugging; it ensures that you only ever have one copy of
 6158: the file's definitions compiled at any time:
 6159: 
 6160: @example
 6161: [IFDEF] my-code
 6162:     my-code
 6163: [ENDIF]
 6164: 
 6165: marker my-code
 6166: init-included-files
 6167: 
 6168: \ .. definitions start here
 6169: \ .
 6170: \ .
 6171: \ end
 6172: @end example
 6173: 
 6174: 
 6175: 
 6176: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
 6177: @subsection Assertions
 6178: @cindex assertions
 6179: 
 6180: It is a good idea to make your programs self-checking, especially if you
 6181: make an assumption that may become invalid during maintenance (for
 6182: example, that a certain field of a data structure is never zero). Gforth
 6183: supports @dfn{assertions} for this purpose. They are used like this:
 6184: 
 6185: @example
 6186: assert( @i{flag} )
 6187: @end example
 6188: 
 6189: The code between @code{assert(} and @code{)} should compute a flag, that
 6190: should be true if everything is alright and false otherwise. It should
 6191: not change anything else on the stack. The overall stack effect of the
 6192: assertion is @code{( -- )}. E.g.
 6193: 
 6194: @example
 6195: assert( 1 1 + 2 = ) \ what we learn in school
 6196: assert( dup 0<> ) \ assert that the top of stack is not zero
 6197: assert( false ) \ this code should not be reached
 6198: @end example
 6199: 
 6200: The need for assertions is different at different times. During
 6201: debugging, we want more checking, in production we sometimes care more
 6202: for speed. Therefore, assertions can be turned off, i.e., the assertion
 6203: becomes a comment. Depending on the importance of an assertion and the
 6204: time it takes to check it, you may want to turn off some assertions and
 6205: keep others turned on. Gforth provides several levels of assertions for
 6206: this purpose:
 6207: 
 6208: doc-assert0(
 6209: doc-assert1(
 6210: doc-assert2(
 6211: doc-assert3(
 6212: doc-assert(
 6213: doc-)
 6214: 
 6215: The variable @code{assert-level} specifies the highest assertions that
 6216: are turned on. I.e., at the default @code{assert-level} of one,
 6217: @code{assert0(} and @code{assert1(} assertions perform checking, while
 6218: @code{assert2(} and @code{assert3(} assertions are treated as comments.
 6219: 
 6220: The value of @code{assert-level} is evaluated at compile-time, not at
 6221: run-time. Therefore you cannot turn assertions on or off at run-time;
 6222: you have to set the @code{assert-level} appropriately before compiling a
 6223: piece of code. You can compile different pieces of code at different
 6224: @code{assert-level}s (e.g., a trusted library at level 1 and
 6225: newly-written code at level 3).
 6226: 
 6227: doc-assert-level
 6228: 
 6229: If an assertion fails, a message compatible with Emacs' compilation mode
 6230: is produced and the execution is aborted (currently with @code{ABORT"}.
 6231: If there is interest, we will introduce a special throw code. But if you
 6232: intend to @code{catch} a specific condition, using @code{throw} is
 6233: probably more appropriate than an assertion).
 6234: 
 6235: Definitions in ANS Forth for these assertion words are provided
 6236: in @file{compat/assert.fs}.
 6237: 
 6238: 
 6239: @node Singlestep Debugger, , Assertions, Programming Tools
 6240: @subsection Singlestep Debugger
 6241: @cindex singlestep Debugger
 6242: @cindex debugging Singlestep
 6243: @cindex @code{dbg}
 6244: @cindex @code{BREAK:}
 6245: @cindex @code{BREAK"}
 6246: 
 6247: When you create a new word there's often the need to check whether it
 6248: behaves correctly or not. You can do this by typing @code{dbg
 6249: badword}. A debug session might look like this:
 6250: 
 6251: @example
 6252: : badword 0 DO i . LOOP ;  ok
 6253: 2 dbg badword 
 6254: : badword  
 6255: Scanning code...
 6256: 
 6257: Nesting debugger ready!
 6258: 
 6259: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
 6260: 400D4740  8049F68 DO             -> [ 0 ] 
 6261: 400D4744  804A0C8 i              -> [ 1 ] 00000 
 6262: 400D4748 400C5E60 .              -> 0 [ 0 ] 
 6263: 400D474C  8049D0C LOOP           -> [ 0 ] 
 6264: 400D4744  804A0C8 i              -> [ 1 ] 00001 
 6265: 400D4748 400C5E60 .              -> 1 [ 0 ] 
 6266: 400D474C  8049D0C LOOP           -> [ 0 ] 
 6267: 400D4758  804B384 ;              ->  ok
 6268: @end example
 6269: 
 6270: Each line displayed is one step. You always have to hit return to
 6271: execute the next word that is displayed. If you don't want to execute
 6272: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
 6273: an overview what keys are available:
 6274: 
 6275: @table @i
 6276: 
 6277: @item @key{RET}
 6278: Next; Execute the next word.
 6279: 
 6280: @item n
 6281: Nest; Single step through next word.
 6282: 
 6283: @item u
 6284: Unnest; Stop debugging and execute rest of word. If we got to this word
 6285: with nest, continue debugging with the calling word.
 6286: 
 6287: @item d
 6288: Done; Stop debugging and execute rest.
 6289: 
 6290: @item s
 6291: Stop; Abort immediately.
 6292: 
 6293: @end table
 6294: 
 6295: Debugging large application with this mechanism is very difficult, because
 6296: you have to nest very deeply into the program before the interesting part
 6297: begins. This takes a lot of time. 
 6298: 
 6299: To do it more directly put a @code{BREAK:} command into your source code.
 6300: When program execution reaches @code{BREAK:} the single step debugger is
 6301: invoked and you have all the features described above.
 6302: 
 6303: If you have more than one part to debug it is useful to know where the
 6304: program has stopped at the moment. You can do this by the 
 6305: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
 6306: string is typed out when the ``breakpoint'' is reached.
 6307: 
 6308: doc-dbg
 6309: doc-BREAK:
 6310: doc-BREAK"
 6311: 
 6312: 
 6313: @c -------------------------------------------------------------
 6314: @node Assembler and Code Words, Threading Words, Programming Tools, Words
 6315: @section Assembler and Code Words
 6316: @cindex assembler
 6317: @cindex code words
 6318: 
 6319: Gforth provides some words for defining primitives (words written in
 6320: machine code), and for defining the machine-code equivalent of
 6321: @code{DOES>}-based defining words. However, the machine-independent
 6322: nature of Gforth poses a few problems: First of all, Gforth runs on
 6323: several architectures, so it can provide no standard assembler. What's
 6324: worse is that the register allocation not only depends on the processor,
 6325: but also on the @code{gcc} version and options used.
 6326: 
 6327: The words that Gforth offers encapsulate some system dependences (e.g.,
 6328: the header structure), so a system-independent assembler may be used in
 6329: Gforth. If you do not have an assembler, you can compile machine code
 6330: directly with @code{,} and @code{c,}@footnote{This isn't portable,
 6331: because these words emit stuff in @i{data} space; it works because
 6332: Gforth has unified code/data spaces. Assembler isn't likely to be
 6333: portable anyway.}.
 6334: 
 6335: doc-assembler
 6336: doc-code
 6337: doc-end-code
 6338: doc-;code
 6339: doc-flush-icache
 6340: 
 6341: If @code{flush-icache} does not work correctly, @code{code} words
 6342: etc. will not work (reliably), either.
 6343: 
 6344: The typical usage of these @code{code} words can be shown most easily by
 6345: analogy to the equivalent high-level defining words:
 6346: 
 6347: @example
 6348: : foo                                        code foo
 6349:    <high-level Forth words>                        <assembler>
 6350: ;                                            end-code
 6351: 
 6352: : bar                                        : bar
 6353:    <high-level Forth words>                     <high-level Forth words>
 6354:    CREATE                                       CREATE
 6355:       <high-level Forth words>                     <high-level Forth words>
 6356:    DOES>                                        ;code
 6357:       <high-level Forth words>                     <assembler>
 6358: ;                                            end-code
 6359: @end example
 6360: 
 6361: @code{flush-icache} is always present. The other words are rarely used
 6362: and reside in @code{code.fs}, which is usually not loaded. You can load
 6363: it with @code{require code.fs}.
 6364: 
 6365: @cindex registers of the inner interpreter
 6366: In the assembly code you will want to refer to the inner interpreter's
 6367: registers (e.g., the data stack pointer) and you may want to use other
 6368: registers for temporary storage. Unfortunately, the register allocation
 6369: is installation-dependent.
 6370: 
 6371: The easiest solution is to use explicit register declarations
 6372: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
 6373: GNU C Manual}) for all of the inner interpreter's registers: You have to
 6374: compile Gforth with @code{-DFORCE_REG} (configure option
 6375: @code{--enable-force-reg}) and the appropriate declarations must be
 6376: present in the @code{machine.h} file (see @code{mips.h} for an example;
 6377: you can find a full list of all declarable register symbols with
 6378: @code{grep register engine.c}). If you give explicit registers to all
 6379: variables that are declared at the beginning of @code{engine()}, you
 6380: should be able to use the other caller-saved registers for temporary
 6381: storage. Alternatively, you can use the @code{gcc} option
 6382: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
 6383: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
 6384: (however, this restriction on register allocation may slow Gforth
 6385: significantly).
 6386: 
 6387: If this solution is not viable (e.g., because @code{gcc} does not allow
 6388: you to explicitly declare all the registers you need), you have to find
 6389: out by looking at the code where the inner interpreter's registers
 6390: reside and which registers can be used for temporary storage. You can
 6391: get an assembly listing of the engine's code with @code{make engine.s}.
 6392: 
 6393: In any case, it is good practice to abstract your assembly code from the
 6394: actual register allocation. E.g., if the data stack pointer resides in
 6395: register @code{$17}, create an alias for this register called @code{sp},
 6396: and use that in your assembly code.
 6397: 
 6398: @cindex code words, portable
 6399: Another option for implementing normal and defining words efficiently
 6400: is to add the desired functionality to the source of Gforth. For normal
 6401: words you just have to edit @file{primitives} (@pxref{Automatic
 6402: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
 6403: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
 6404: @file{prims2x.fs}, and possibly @file{cross.fs}.
 6405: 
 6406: 
 6407: @c -------------------------------------------------------------
 6408: @node Threading Words, Locals, Assembler and Code Words, Words
 6409: @section Threading Words
 6410: @cindex threading words
 6411: 
 6412: @cindex code address
 6413: These words provide access to code addresses and other threading stuff
 6414: in Gforth (and, possibly, other interpretive Forths). It more or less
 6415: abstracts away the differences between direct and indirect threading
 6416: (and, for direct threading, the machine dependences). However, at
 6417: present this wordset is still incomplete. It is also pretty low-level;
 6418: some day it will hopefully be made unnecessary by an internals wordset
 6419: that abstracts implementation details away completely.
 6420: 
 6421: doc-threading-method
 6422: doc->code-address
 6423: doc->does-code
 6424: doc-code-address!
 6425: doc-does-code!
 6426: doc-does-handler!
 6427: doc-/does-handler
 6428: 
 6429: The code addresses produced by various defining words are produced by
 6430: the following words:
 6431: 
 6432: doc-docol:
 6433: doc-docon:
 6434: doc-dovar:
 6435: doc-douser:
 6436: doc-dodefer:
 6437: doc-dofield:
 6438: 
 6439: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
 6440: with @code{>does-code}. If the word was defined in that way, the value
 6441: returned is non-zero and identifies the @code{DOES>} used by the
 6442: defining word.
 6443: @comment TODO should that be ``identifies the xt of the DOES> ??''
 6444: 
 6445: @c -------------------------------------------------------------
 6446: @node Locals, Structures, Threading Words, Words
 6447: @section Locals
 6448: @cindex locals
 6449: 
 6450: Local variables can make Forth programming more enjoyable and Forth
 6451: programs easier to read. Unfortunately, the locals of ANS Forth are
 6452: laden with restrictions. Therefore, we provide not only the ANS Forth
 6453: locals wordset, but also our own, more powerful locals wordset (we
 6454: implemented the ANS Forth locals wordset through our locals wordset).
 6455: 
 6456: The ideas in this section have also been published in the paper
 6457: @cite{Automatic Scoping of Local Variables} by M. Anton Ertl, presented
 6458: at EuroForth '94; it is available at
 6459: @*@url{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz}.
 6460: 
 6461: @menu
 6462: * Gforth locals::               
 6463: * ANS Forth locals::            
 6464: @end menu
 6465: 
 6466: @node Gforth locals, ANS Forth locals, Locals, Locals
 6467: @subsection Gforth locals
 6468: @cindex Gforth locals
 6469: @cindex locals, Gforth style
 6470: 
 6471: Locals can be defined with
 6472: 
 6473: @example
 6474: @{ local1 local2 ... -- comment @}
 6475: @end example
 6476: or
 6477: @example
 6478: @{ local1 local2 ... @}
 6479: @end example
 6480: 
 6481: E.g.,
 6482: @example
 6483: : max @{ n1 n2 -- n3 @}
 6484:  n1 n2 > if
 6485:    n1
 6486:  else
 6487:    n2
 6488:  endif ;
 6489: @end example
 6490: 
 6491: The similarity of locals definitions with stack comments is intended. A
 6492: locals definition often replaces the stack comment of a word. The order
 6493: of the locals corresponds to the order in a stack comment and everything
 6494: after the @code{--} is really a comment.
 6495: 
 6496: This similarity has one disadvantage: It is too easy to confuse locals
 6497: declarations with stack comments, causing bugs and making them hard to
 6498: find. However, this problem can be avoided by appropriate coding
 6499: conventions: Do not use both notations in the same program. If you do,
 6500: they should be distinguished using additional means, e.g. by position.
 6501: 
 6502: @cindex types of locals
 6503: @cindex locals types
 6504: The name of the local may be preceded by a type specifier, e.g.,
 6505: @code{F:} for a floating point value:
 6506: 
 6507: @example
 6508: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
 6509: \ complex multiplication
 6510:  Ar Br f* Ai Bi f* f-
 6511:  Ar Bi f* Ai Br f* f+ ;
 6512: @end example
 6513: 
 6514: @cindex flavours of locals
 6515: @cindex locals flavours
 6516: @cindex value-flavoured locals
 6517: @cindex variable-flavoured locals
 6518: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
 6519: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
 6520: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
 6521: with @code{W:}, @code{D:} etc.) produces its value and can be changed
 6522: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
 6523: produces its address (which becomes invalid when the variable's scope is
 6524: left). E.g., the standard word @code{emit} can be defined in terms of
 6525: @code{type} like this:
 6526: 
 6527: @example
 6528: : emit @{ C^ char* -- @}
 6529:     char* 1 type ;
 6530: @end example
 6531: 
 6532: @cindex default type of locals
 6533: @cindex locals, default type
 6534: A local without type specifier is a @code{W:} local. Both flavours of
 6535: locals are initialized with values from the data or FP stack.
 6536: 
 6537: Currently there is no way to define locals with user-defined data
 6538: structures, but we are working on it.
 6539: 
 6540: Gforth allows defining locals everywhere in a colon definition. This
 6541: poses the following questions:
 6542: 
 6543: @menu
 6544: * Where are locals visible by name?::  
 6545: * How long do locals live?::    
 6546: * Programming Style::           
 6547: * Implementation::              
 6548: @end menu
 6549: 
 6550: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
 6551: @subsubsection Where are locals visible by name?
 6552: @cindex locals visibility
 6553: @cindex visibility of locals
 6554: @cindex scope of locals
 6555: 
 6556: Basically, the answer is that locals are visible where you would expect
 6557: it in block-structured languages, and sometimes a little longer. If you
 6558: want to restrict the scope of a local, enclose its definition in
 6559: @code{SCOPE}...@code{ENDSCOPE}.
 6560: 
 6561: doc-scope
 6562: doc-endscope
 6563: 
 6564: These words behave like control structure words, so you can use them
 6565: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
 6566: arbitrary ways.
 6567: 
 6568: If you want a more exact answer to the visibility question, here's the
 6569: basic principle: A local is visible in all places that can only be
 6570: reached through the definition of the local@footnote{In compiler
 6571: construction terminology, all places dominated by the definition of the
 6572: local.}. In other words, it is not visible in places that can be reached
 6573: without going through the definition of the local. E.g., locals defined
 6574: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
 6575: defined in @code{BEGIN}...@code{UNTIL} are visible after the
 6576: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
 6577: 
 6578: The reasoning behind this solution is: We want to have the locals
 6579: visible as long as it is meaningful. The user can always make the
 6580: visibility shorter by using explicit scoping. In a place that can
 6581: only be reached through the definition of a local, the meaning of a
 6582: local name is clear. In other places it is not: How is the local
 6583: initialized at the control flow path that does not contain the
 6584: definition? Which local is meant, if the same name is defined twice in
 6585: two independent control flow paths?
 6586: 
 6587: This should be enough detail for nearly all users, so you can skip the
 6588: rest of this section. If you really must know all the gory details and
 6589: options, read on.
 6590: 
 6591: In order to implement this rule, the compiler has to know which places
 6592: are unreachable. It knows this automatically after @code{AHEAD},
 6593: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
 6594: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
 6595: compiler that the control flow never reaches that place. If
 6596: @code{UNREACHABLE} is not used where it could, the only consequence is
 6597: that the visibility of some locals is more limited than the rule above
 6598: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
 6599: lie to the compiler), buggy code will be produced.
 6600: 
 6601: doc-unreachable
 6602: 
 6603: Another problem with this rule is that at @code{BEGIN}, the compiler
 6604: does not know which locals will be visible on the incoming
 6605: back-edge. All problems discussed in the following are due to this
 6606: ignorance of the compiler (we discuss the problems using @code{BEGIN}
 6607: loops as examples; the discussion also applies to @code{?DO} and other
 6608: loops). Perhaps the most insidious example is:
 6609: @example
 6610: AHEAD
 6611: BEGIN
 6612:   x
 6613: [ 1 CS-ROLL ] THEN
 6614:   @{ x @}
 6615:   ...
 6616: UNTIL
 6617: @end example
 6618: 
 6619: This should be legal according to the visibility rule. The use of
 6620: @code{x} can only be reached through the definition; but that appears
 6621: textually below the use.
 6622: 
 6623: From this example it is clear that the visibility rules cannot be fully
 6624: implemented without major headaches. Our implementation treats common
 6625: cases as advertised and the exceptions are treated in a safe way: The
 6626: compiler makes a reasonable guess about the locals visible after a
 6627: @code{BEGIN}; if it is too pessimistic, the
 6628: user will get a spurious error about the local not being defined; if the
 6629: compiler is too optimistic, it will notice this later and issue a
 6630: warning. In the case above the compiler would complain about @code{x}
 6631: being undefined at its use. You can see from the obscure examples in
 6632: this section that it takes quite unusual control structures to get the
 6633: compiler into trouble, and even then it will often do fine.
 6634: 
 6635: If the @code{BEGIN} is reachable from above, the most optimistic guess
 6636: is that all locals visible before the @code{BEGIN} will also be
 6637: visible after the @code{BEGIN}. This guess is valid for all loops that
 6638: are entered only through the @code{BEGIN}, in particular, for normal
 6639: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
 6640: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
 6641: compiler. When the branch to the @code{BEGIN} is finally generated by
 6642: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
 6643: warns the user if it was too optimistic:
 6644: @example
 6645: IF
 6646:   @{ x @}
 6647: BEGIN
 6648:   \ x ? 
 6649: [ 1 cs-roll ] THEN
 6650:   ...
 6651: UNTIL
 6652: @end example
 6653: 
 6654: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
 6655: optimistically assumes that it lives until the @code{THEN}. It notices
 6656: this difference when it compiles the @code{UNTIL} and issues a
 6657: warning. The user can avoid the warning, and make sure that @code{x}
 6658: is not used in the wrong area by using explicit scoping:
 6659: @example
 6660: IF
 6661:   SCOPE
 6662:   @{ x @}
 6663:   ENDSCOPE
 6664: BEGIN
 6665: [ 1 cs-roll ] THEN
 6666:   ...
 6667: UNTIL
 6668: @end example
 6669: 
 6670: Since the guess is optimistic, there will be no spurious error messages
 6671: about undefined locals.
 6672: 
 6673: If the @code{BEGIN} is not reachable from above (e.g., after
 6674: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
 6675: optimistic guess, as the locals visible after the @code{BEGIN} may be
 6676: defined later. Therefore, the compiler assumes that no locals are
 6677: visible after the @code{BEGIN}. However, the user can use
 6678: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
 6679: visible at the BEGIN as at the point where the top control-flow stack
 6680: item was created.
 6681: 
 6682: doc-assume-live
 6683: 
 6684: E.g.,
 6685: @example
 6686: @{ x @}
 6687: AHEAD
 6688: ASSUME-LIVE
 6689: BEGIN
 6690:   x
 6691: [ 1 CS-ROLL ] THEN
 6692:   ...
 6693: UNTIL
 6694: @end example
 6695: 
 6696: Other cases where the locals are defined before the @code{BEGIN} can be
 6697: handled by inserting an appropriate @code{CS-ROLL} before the
 6698: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
 6699: behind the @code{ASSUME-LIVE}).
 6700: 
 6701: Cases where locals are defined after the @code{BEGIN} (but should be
 6702: visible immediately after the @code{BEGIN}) can only be handled by
 6703: rearranging the loop. E.g., the ``most insidious'' example above can be
 6704: arranged into:
 6705: @example
 6706: BEGIN
 6707:   @{ x @}
 6708:   ... 0=
 6709: WHILE
 6710:   x
 6711: REPEAT
 6712: @end example
 6713: 
 6714: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
 6715: @subsubsection How long do locals live?
 6716: @cindex locals lifetime
 6717: @cindex lifetime of locals
 6718: 
 6719: The right answer for the lifetime question would be: A local lives at
 6720: least as long as it can be accessed. For a value-flavoured local this
 6721: means: until the end of its visibility. However, a variable-flavoured
 6722: local could be accessed through its address far beyond its visibility
 6723: scope. Ultimately, this would mean that such locals would have to be
 6724: garbage collected. Since this entails un-Forth-like implementation
 6725: complexities, I adopted the same cowardly solution as some other
 6726: languages (e.g., C): The local lives only as long as it is visible;
 6727: afterwards its address is invalid (and programs that access it
 6728: afterwards are erroneous).
 6729: 
 6730: @node Programming Style, Implementation, How long do locals live?, Gforth locals
 6731: @subsubsection Programming Style
 6732: @cindex locals programming style
 6733: @cindex programming style, locals
 6734: 
 6735: The freedom to define locals anywhere has the potential to change
 6736: programming styles dramatically. In particular, the need to use the
 6737: return stack for intermediate storage vanishes. Moreover, all stack
 6738: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
 6739: determined arguments) can be eliminated: If the stack items are in the
 6740: wrong order, just write a locals definition for all of them; then
 6741: write the items in the order you want.
 6742: 
 6743: This seems a little far-fetched and eliminating stack manipulations is
 6744: unlikely to become a conscious programming objective. Still, the number
 6745: of stack manipulations will be reduced dramatically if local variables
 6746: are used liberally (e.g., compare @code{max} in @ref{Gforth locals} with
 6747: a traditional implementation of @code{max}).
 6748: 
 6749: This shows one potential benefit of locals: making Forth programs more
 6750: readable. Of course, this benefit will only be realized if the
 6751: programmers continue to honour the principle of factoring instead of
 6752: using the added latitude to make the words longer.
 6753: 
 6754: @cindex single-assignment style for locals
 6755: Using @code{TO} can and should be avoided.  Without @code{TO},
 6756: every value-flavoured local has only a single assignment and many
 6757: advantages of functional languages apply to Forth. I.e., programs are
 6758: easier to analyse, to optimize and to read: It is clear from the
 6759: definition what the local stands for, it does not turn into something
 6760: different later.
 6761: 
 6762: E.g., a definition using @code{TO} might look like this:
 6763: @example
 6764: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 6765:  u1 u2 min 0
 6766:  ?do
 6767:    addr1 c@@ addr2 c@@ -
 6768:    ?dup-if
 6769:      unloop exit
 6770:    then
 6771:    addr1 char+ TO addr1
 6772:    addr2 char+ TO addr2
 6773:  loop
 6774:  u1 u2 - ;
 6775: @end example
 6776: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
 6777: every loop iteration. @code{strcmp} is a typical example of the
 6778: readability problems of using @code{TO}. When you start reading
 6779: @code{strcmp}, you think that @code{addr1} refers to the start of the
 6780: string. Only near the end of the loop you realize that it is something
 6781: else.
 6782: 
 6783: This can be avoided by defining two locals at the start of the loop that
 6784: are initialized with the right value for the current iteration.
 6785: @example
 6786: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 6787:  addr1 addr2
 6788:  u1 u2 min 0 
 6789:  ?do @{ s1 s2 @}
 6790:    s1 c@@ s2 c@@ -
 6791:    ?dup-if
 6792:      unloop exit
 6793:    then
 6794:    s1 char+ s2 char+
 6795:  loop
 6796:  2drop
 6797:  u1 u2 - ;
 6798: @end example
 6799: Here it is clear from the start that @code{s1} has a different value
 6800: in every loop iteration.
 6801: 
 6802: @node Implementation,  , Programming Style, Gforth locals
 6803: @subsubsection Implementation
 6804: @cindex locals implementation
 6805: @cindex implementation of locals
 6806: 
 6807: @cindex locals stack
 6808: Gforth uses an extra locals stack. The most compelling reason for
 6809: this is that the return stack is not float-aligned; using an extra stack
 6810: also eliminates the problems and restrictions of using the return stack
 6811: as locals stack. Like the other stacks, the locals stack grows toward
 6812: lower addresses. A few primitives allow an efficient implementation:
 6813: 
 6814: doc-@local#
 6815: doc-f@local#
 6816: doc-laddr#
 6817: doc-lp+!#
 6818: doc-lp!
 6819: doc->l
 6820: doc-f>l
 6821: 
 6822: In addition to these primitives, some specializations of these
 6823: primitives for commonly occurring inline arguments are provided for
 6824: efficiency reasons, e.g., @code{@@local0} as specialization of
 6825: @code{@@local#} for the inline argument 0. The following compiling words
 6826: compile the right specialized version, or the general version, as
 6827: appropriate:
 6828: 
 6829: doc-compile-@local
 6830: doc-compile-f@local
 6831: doc-compile-lp+!
 6832: 
 6833: Combinations of conditional branches and @code{lp+!#} like
 6834: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
 6835: is taken) are provided for efficiency and correctness in loops.
 6836: 
 6837: A special area in the dictionary space is reserved for keeping the
 6838: local variable names. @code{@{} switches the dictionary pointer to this
 6839: area and @code{@}} switches it back and generates the locals
 6840: initializing code. @code{W:} etc.@ are normal defining words. This
 6841: special area is cleared at the start of every colon definition.
 6842: 
 6843: @cindex word list for defining locals
 6844: A special feature of Gforth's dictionary is used to implement the
 6845: definition of locals without type specifiers: every word list (aka
 6846: vocabulary) has its own methods for searching
 6847: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
 6848: with a special search method: When it is searched for a word, it
 6849: actually creates that word using @code{W:}. @code{@{} changes the search
 6850: order to first search the word list containing @code{@}}, @code{W:} etc.,
 6851: and then the word list for defining locals without type specifiers.
 6852: 
 6853: The lifetime rules support a stack discipline within a colon
 6854: definition: The lifetime of a local is either nested with other locals
 6855: lifetimes or it does not overlap them.
 6856: 
 6857: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
 6858: pointer manipulation is generated. Between control structure words
 6859: locals definitions can push locals onto the locals stack. @code{AGAIN}
 6860: is the simplest of the other three control flow words. It has to
 6861: restore the locals stack depth of the corresponding @code{BEGIN}
 6862: before branching. The code looks like this:
 6863: @format
 6864: @code{lp+!#} current-locals-size @minus{} dest-locals-size
 6865: @code{branch} <begin>
 6866: @end format
 6867: 
 6868: @code{UNTIL} is a little more complicated: If it branches back, it
 6869: must adjust the stack just like @code{AGAIN}. But if it falls through,
 6870: the locals stack must not be changed. The compiler generates the
 6871: following code:
 6872: @format
 6873: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
 6874: @end format
 6875: The locals stack pointer is only adjusted if the branch is taken.
 6876: 
 6877: @code{THEN} can produce somewhat inefficient code:
 6878: @format
 6879: @code{lp+!#} current-locals-size @minus{} orig-locals-size
 6880: <orig target>:
 6881: @code{lp+!#} orig-locals-size @minus{} new-locals-size
 6882: @end format
 6883: The second @code{lp+!#} adjusts the locals stack pointer from the
 6884: level at the @i{orig} point to the level after the @code{THEN}. The
 6885: first @code{lp+!#} adjusts the locals stack pointer from the current
 6886: level to the level at the orig point, so the complete effect is an
 6887: adjustment from the current level to the right level after the
 6888: @code{THEN}.
 6889: 
 6890: @cindex locals information on the control-flow stack
 6891: @cindex control-flow stack items, locals information
 6892: In a conventional Forth implementation a dest control-flow stack entry
 6893: is just the target address and an orig entry is just the address to be
 6894: patched. Our locals implementation adds a word list to every orig or dest
 6895: item. It is the list of locals visible (or assumed visible) at the point
 6896: described by the entry. Our implementation also adds a tag to identify
 6897: the kind of entry, in particular to differentiate between live and dead
 6898: (reachable and unreachable) orig entries.
 6899: 
 6900: A few unusual operations have to be performed on locals word lists:
 6901: 
 6902: doc-common-list
 6903: doc-sub-list?
 6904: doc-list-size
 6905: 
 6906: Several features of our locals word list implementation make these
 6907: operations easy to implement: The locals word lists are organised as
 6908: linked lists; the tails of these lists are shared, if the lists
 6909: contain some of the same locals; and the address of a name is greater
 6910: than the address of the names behind it in the list.
 6911: 
 6912: Another important implementation detail is the variable
 6913: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
 6914: determine if they can be reached directly or only through the branch
 6915: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
 6916: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
 6917: definition, by @code{BEGIN} and usually by @code{THEN}.
 6918: 
 6919: Counted loops are similar to other loops in most respects, but
 6920: @code{LEAVE} requires special attention: It performs basically the same
 6921: service as @code{AHEAD}, but it does not create a control-flow stack
 6922: entry. Therefore the information has to be stored elsewhere;
 6923: traditionally, the information was stored in the target fields of the
 6924: branches created by the @code{LEAVE}s, by organizing these fields into a
 6925: linked list. Unfortunately, this clever trick does not provide enough
 6926: space for storing our extended control flow information. Therefore, we
 6927: introduce another stack, the leave stack. It contains the control-flow
 6928: stack entries for all unresolved @code{LEAVE}s.
 6929: 
 6930: Local names are kept until the end of the colon definition, even if
 6931: they are no longer visible in any control-flow path. In a few cases
 6932: this may lead to increased space needs for the locals name area, but
 6933: usually less than reclaiming this space would cost in code size.
 6934: 
 6935: 
 6936: @node ANS Forth locals,  , Gforth locals, Locals
 6937: @subsection ANS Forth locals
 6938: @cindex locals, ANS Forth style
 6939: 
 6940: The ANS Forth locals wordset does not define a syntax for locals, but
 6941: words that make it possible to define various syntaxes. One of the
 6942: possible syntaxes is a subset of the syntax we used in the Gforth locals
 6943: wordset, i.e.:
 6944: 
 6945: @example
 6946: @{ local1 local2 ... -- comment @}
 6947: @end example
 6948: @noindent
 6949: or
 6950: @example
 6951: @{ local1 local2 ... @}
 6952: @end example
 6953: 
 6954: The order of the locals corresponds to the order in a stack comment. The
 6955: restrictions are:
 6956: 
 6957: @itemize @bullet
 6958: @item
 6959: Locals can only be cell-sized values (no type specifiers are allowed).
 6960: @item
 6961: Locals can be defined only outside control structures.
 6962: @item
 6963: Locals can interfere with explicit usage of the return stack. For the
 6964: exact (and long) rules, see the standard. If you don't use return stack
 6965: accessing words in a definition using locals, you will be all right. The
 6966: purpose of this rule is to make locals implementation on the return
 6967: stack easier.
 6968: @item
 6969: The whole definition must be in one line.
 6970: @end itemize
 6971: 
 6972: Locals defined in this way behave like @code{VALUE}s (@xref{Simple
 6973: Defining Words}). I.e., they are initialized from the stack. Using their
 6974: name produces their value. Their value can be changed using @code{TO}.
 6975: 
 6976: Since this syntax is supported by Gforth directly, you need not do
 6977: anything to use it. If you want to port a program using this syntax to
 6978: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
 6979: syntax on the other system.
 6980: 
 6981: Note that a syntax shown in the standard, section A.13 looks
 6982: similar, but is quite different in having the order of locals
 6983: reversed. Beware!
 6984: 
 6985: The ANS Forth locals wordset itself consists of a word:
 6986: 
 6987: doc-(local)
 6988: 
 6989: The ANS Forth locals extension wordset defines a syntax using @code{locals|}, but it is so
 6990: awful that we strongly recommend not to use it. We have implemented this
 6991: syntax to make porting to Gforth easy, but do not document it here. The
 6992: problem with this syntax is that the locals are defined in an order
 6993: reversed with respect to the standard stack comment notation, making
 6994: programs harder to read, and easier to misread and miswrite. The only
 6995: merit of this syntax is that it is easy to implement using the ANS Forth
 6996: locals wordset.
 6997: 
 6998: 
 6999: @c ----------------------------------------------------------
 7000: @node Structures, Object-oriented Forth, Locals, Words
 7001: @section  Structures
 7002: @cindex structures
 7003: @cindex records
 7004: 
 7005: This section presents the structure package that comes with Gforth. A
 7006: version of the package implemented in ANS Forth is available in
 7007: @file{compat/struct.fs}. This package was inspired by a posting on
 7008: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
 7009: possibly John Hayes). A version of this section has been published in
 7010: ???. Marcel Hendrix provided helpful comments.
 7011: 
 7012: @menu
 7013: * Why explicit structure support?::  
 7014: * Structure Usage::             
 7015: * Structure Naming Convention::  
 7016: * Structure Implementation::    
 7017: * Structure Glossary::          
 7018: @end menu
 7019: 
 7020: @node Why explicit structure support?, Structure Usage, Structures, Structures
 7021: @subsection Why explicit structure support?
 7022: 
 7023: @cindex address arithmetic for structures
 7024: @cindex structures using address arithmetic
 7025: If we want to use a structure containing several fields, we could simply
 7026: reserve memory for it, and access the fields using address arithmetic
 7027: (@pxref{Address arithmetic}). As an example, consider a structure with
 7028: the following fields
 7029: 
 7030: @table @code
 7031: @item a
 7032: is a float
 7033: @item b
 7034: is a cell
 7035: @item c
 7036: is a float
 7037: @end table
 7038: 
 7039: Given the (float-aligned) base address of the structure we get the
 7040: address of the field
 7041: 
 7042: @table @code
 7043: @item a
 7044: without doing anything further.
 7045: @item b
 7046: with @code{float+}
 7047: @item c
 7048: with @code{float+ cell+ faligned}
 7049: @end table
 7050: 
 7051: It is easy to see that this can become quite tiring. 
 7052: 
 7053: Moreover, it is not very readable, because seeing a
 7054: @code{cell+} tells us neither which kind of structure is
 7055: accessed nor what field is accessed; we have to somehow infer the kind
 7056: of structure, and then look up in the documentation, which field of
 7057: that structure corresponds to that offset.
 7058: 
 7059: Finally, this kind of address arithmetic also causes maintenance
 7060: troubles: If you add or delete a field somewhere in the middle of the
 7061: structure, you have to find and change all computations for the fields
 7062: afterwards.
 7063: 
 7064: So, instead of using @code{cell+} and friends directly, how
 7065: about storing the offsets in constants:
 7066: 
 7067: @example
 7068: 0 constant a-offset
 7069: 0 float+ constant b-offset
 7070: 0 float+ cell+ faligned c-offset
 7071: @end example
 7072: 
 7073: Now we can get the address of field @code{x} with @code{x-offset
 7074: +}. This is much better in all respects. Of course, you still
 7075: have to change all later offset definitions if you add a field. You can
 7076: fix this by declaring the offsets in the following way:
 7077: 
 7078: @example
 7079: 0 constant a-offset
 7080: a-offset float+ constant b-offset
 7081: b-offset cell+ faligned constant c-offset
 7082: @end example
 7083: 
 7084: Since we always use the offsets with @code{+}, we could use a defining
 7085: word @code{cfield} that includes the @code{+} in the action of the
 7086: defined word:
 7087: 
 7088: @example
 7089: : cfield ( n "name" -- )
 7090:     create ,
 7091: does> ( name execution: addr1 -- addr2 )
 7092:     @@ + ;
 7093: 
 7094: 0 cfield a
 7095: 0 a float+ cfield b
 7096: 0 b cell+ faligned cfield c
 7097: @end example
 7098: 
 7099: Instead of @code{x-offset +}, we now simply write @code{x}.
 7100: 
 7101: The structure field words now can be used quite nicely. However,
 7102: their definition is still a bit cumbersome: We have to repeat the
 7103: name, the information about size and alignment is distributed before
 7104: and after the field definitions etc.  The structure package presented
 7105: here addresses these problems.
 7106: 
 7107: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
 7108: @subsection Structure Usage
 7109: @cindex structure usage
 7110: 
 7111: @cindex @code{field} usage
 7112: @cindex @code{struct} usage
 7113: @cindex @code{end-struct} usage
 7114: You can define a structure for a (data-less) linked list with:
 7115: @example
 7116: struct
 7117:     cell% field list-next
 7118: end-struct list%
 7119: @end example
 7120: 
 7121: With the address of the list node on the stack, you can compute the
 7122: address of the field that contains the address of the next node with
 7123: @code{list-next}. E.g., you can determine the length of a list
 7124: with:
 7125: 
 7126: @example
 7127: : list-length ( list -- n )
 7128: \ "list" is a pointer to the first element of a linked list
 7129: \ "n" is the length of the list
 7130:     0 BEGIN ( list1 n1 )
 7131:         over
 7132:     WHILE ( list1 n1 )
 7133:         1+ swap list-next @@ swap
 7134:     REPEAT
 7135:     nip ;
 7136: @end example
 7137: 
 7138: You can reserve memory for a list node in the dictionary with
 7139: @code{list% %allot}, which leaves the address of the list node on the
 7140: stack. For the equivalent allocation on the heap you can use @code{list%
 7141: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
 7142: use @code{list% %allocate}). You can get the the size of a list
 7143: node with @code{list% %size} and its alignment with @code{list%
 7144: %alignment}.
 7145: 
 7146: Note that in ANS Forth the body of a @code{create}d word is
 7147: @code{aligned} but not necessarily @code{faligned};
 7148: therefore, if you do a:
 7149: @example
 7150: create @emph{name} foo% %allot
 7151: @end example
 7152: 
 7153: @noindent
 7154: then the memory alloted for @code{foo%} is
 7155: guaranteed to start at the body of @code{@emph{name}} only if
 7156: @code{foo%} contains only character, cell and double fields.
 7157: 
 7158: @cindex strcutures containing structures
 7159: You can include a structure @code{foo%} as a field of
 7160: another structure, like this:
 7161: @example
 7162: struct
 7163: ...
 7164:     foo% field ...
 7165: ...
 7166: end-struct ...
 7167: @end example
 7168: 
 7169: @cindex structure extension
 7170: @cindex extended records
 7171: Instead of starting with an empty structure, you can extend an
 7172: existing structure. E.g., a plain linked list without data, as defined
 7173: above, is hardly useful; You can extend it to a linked list of integers,
 7174: like this:@footnote{This feature is also known as @emph{extended
 7175: records}. It is the main innovation in the Oberon language; in other
 7176: words, adding this feature to Modula-2 led Wirth to create a new
 7177: language, write a new compiler etc.  Adding this feature to Forth just
 7178: required a few lines of code.}
 7179: 
 7180: @example
 7181: list%
 7182:     cell% field intlist-int
 7183: end-struct intlist%
 7184: @end example
 7185: 
 7186: @code{intlist%} is a structure with two fields:
 7187: @code{list-next} and @code{intlist-int}.
 7188: 
 7189: @cindex structures containing arrays
 7190: You can specify an array type containing @emph{n} elements of
 7191: type @code{foo%} like this:
 7192: 
 7193: @example
 7194: foo% @emph{n} *
 7195: @end example
 7196: 
 7197: You can use this array type in any place where you can use a normal
 7198: type, e.g., when defining a @code{field}, or with
 7199: @code{%allot}.
 7200: 
 7201: @cindex first field optimization
 7202: The first field is at the base address of a structure and the word
 7203: for this field (e.g., @code{list-next}) actually does not change
 7204: the address on the stack. You may be tempted to leave it away in the
 7205: interest of run-time and space efficiency. This is not necessary,
 7206: because the structure package optimizes this case and compiling such
 7207: words does not generate any code. So, in the interest of readability
 7208: and maintainability you should include the word for the field when
 7209: accessing the field.
 7210: 
 7211: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
 7212: @subsection Structure Naming Convention
 7213: @cindex structure naming convention
 7214: 
 7215: The field names that come to (my) mind are often quite generic, and,
 7216: if used, would cause frequent name clashes. E.g., many structures
 7217: probably contain a @code{counter} field. The structure names
 7218: that come to (my) mind are often also the logical choice for the names
 7219: of words that create such a structure.
 7220: 
 7221: Therefore, I have adopted the following naming conventions: 
 7222: 
 7223: @itemize @bullet
 7224: @cindex field naming convention
 7225: @item
 7226: The names of fields are of the form
 7227: @code{@emph{struct}-@emph{field}}, where
 7228: @code{@emph{struct}} is the basic name of the structure, and
 7229: @code{@emph{field}} is the basic name of the field. You can
 7230: think of field words as converting the (address of the)
 7231: structure into the (address of the) field.
 7232: 
 7233: @cindex structure naming convention
 7234: @item
 7235: The names of structures are of the form
 7236: @code{@emph{struct}%}, where
 7237: @code{@emph{struct}} is the basic name of the structure.
 7238: @end itemize
 7239: 
 7240: This naming convention does not work that well for fields of extended
 7241: structures; e.g., the integer list structure has a field
 7242: @code{intlist-int}, but has @code{list-next}, not
 7243: @code{intlist-next}.
 7244: 
 7245: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
 7246: @subsection Structure Implementation
 7247: @cindex structure implementation
 7248: @cindex implementation of structures
 7249: 
 7250: The central idea in the implementation is to pass the data about the
 7251: structure being built on the stack, not in some global
 7252: variable. Everything else falls into place naturally once this design
 7253: decision is made.
 7254: 
 7255: The type description on the stack is of the form @emph{align
 7256: size}. Keeping the size on the top-of-stack makes dealing with arrays
 7257: very simple.
 7258: 
 7259: @code{field} is a defining word that uses @code{Create}
 7260: and @code{DOES>}. The body of the field contains the offset
 7261: of the field, and the normal @code{DOES>} action is simply:
 7262: 
 7263: @example
 7264: @ +
 7265: @end example
 7266: 
 7267: @noindent
 7268: i.e., add the offset to the address, giving the stack effect
 7269: @i{addr1 -- addr2} for a field.
 7270: 
 7271: @cindex first field optimization, implementation
 7272: This simple structure is slightly complicated by the optimization
 7273: for fields with offset 0, which requires a different
 7274: @code{DOES>}-part (because we cannot rely on there being
 7275: something on the stack if such a field is invoked during
 7276: compilation). Therefore, we put the different @code{DOES>}-parts
 7277: in separate words, and decide which one to invoke based on the
 7278: offset. For a zero offset, the field is basically a noop; it is
 7279: immediate, and therefore no code is generated when it is compiled.
 7280: 
 7281: @node Structure Glossary,  , Structure Implementation, Structures
 7282: @subsection Structure Glossary
 7283: @cindex structure glossary
 7284: 
 7285: doc-%align
 7286: doc-%alignment
 7287: doc-%alloc
 7288: doc-%allocate
 7289: doc-%allot
 7290: doc-cell%
 7291: doc-char%
 7292: doc-dfloat%
 7293: doc-double%
 7294: doc-end-struct
 7295: doc-field
 7296: doc-float%
 7297: doc-naligned
 7298: doc-sfloat%
 7299: doc-%size
 7300: doc-struct
 7301: 
 7302: @c -------------------------------------------------------------
 7303: @node Object-oriented Forth, Passing Commands to the OS, Structures, Words
 7304: @section Object-oriented Forth
 7305: 
 7306: Gforth comes with three packages for object-oriented programming:
 7307: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
 7308: is preloaded, so you have to @code{include} them before use. The most
 7309: important differences between these packages (and others) are discussed
 7310: in @ref{Comparison with other object models}. All packages are written
 7311: in ANS Forth and can be used with any other ANS Forth.
 7312: 
 7313: @menu
 7314: * Why object-oriented programming?::
 7315: * Object-Oriented Terminology::
 7316: * Objects::
 7317: * OOF::
 7318: * Mini-OOF::
 7319: * Comparison with other object models::  
 7320: @end menu
 7321: 
 7322: 
 7323: @node Why object-oriented programming?, Object-Oriented Terminology, , Object-oriented Forth
 7324: @subsubsection Why object-oriented programming?
 7325: @cindex object-oriented programming motivation
 7326: @cindex motivation for object-oriented programming
 7327: 
 7328: Often we have to deal with several data structures (@emph{objects}),
 7329: that have to be treated similarly in some respects, but differently in
 7330: others. Graphical objects are the textbook example: circles, triangles,
 7331: dinosaurs, icons, and others, and we may want to add more during program
 7332: development. We want to apply some operations to any graphical object,
 7333: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
 7334: has to do something different for every kind of object.
 7335: @comment TODO add some other operations eg perimeter, area
 7336: @comment and tie in to concrete examples later..
 7337: 
 7338: We could implement @code{draw} as a big @code{CASE}
 7339: control structure that executes the appropriate code depending on the
 7340: kind of object to be drawn. This would be not be very elegant, and,
 7341: moreover, we would have to change @code{draw} every time we add
 7342: a new kind of graphical object (say, a spaceship).
 7343: 
 7344: What we would rather do is: When defining spaceships, we would tell
 7345: the system: ``Here's how you @code{draw} a spaceship; you figure
 7346: out the rest''.
 7347: 
 7348: This is the problem that all systems solve that (rightfully) call
 7349: themselves object-oriented; the object-oriented packages presented here
 7350: solve this problem (and not much else).
 7351: @comment TODO ?list properties of oo systems.. oo vs o-based?
 7352: 
 7353: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
 7354: @subsubsection Object-Oriented Terminology
 7355: @cindex object-oriented terminology
 7356: @cindex terminology for object-oriented programming
 7357: 
 7358: This section is mainly for reference, so you don't have to understand
 7359: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
 7360: short:
 7361: 
 7362: @table @emph
 7363: @cindex class
 7364: @item class
 7365: a data structure definition with some extras.
 7366: 
 7367: @cindex object
 7368: @item object
 7369: an instance of the data structure described by the class definition.
 7370: 
 7371: @cindex instance variables
 7372: @item instance variables
 7373: fields of the data structure.
 7374: 
 7375: @cindex selector
 7376: @cindex method selector
 7377: @cindex virtual function
 7378: @item selector
 7379: (or @emph{method selector}) a word (e.g.,
 7380: @code{draw}) that performs an operation on a variety of data
 7381: structures (classes). A selector describes @emph{what} operation to
 7382: perform. In C++ terminology: a (pure) virtual function.
 7383: 
 7384: @cindex method
 7385: @item method
 7386: the concrete definition that performs the operation
 7387: described by the selector for a specific class. A method specifies
 7388: @emph{how} the operation is performed for a specific class.
 7389: 
 7390: @cindex selector invocation
 7391: @cindex message send
 7392: @cindex invoking a selector
 7393: @item selector invocation
 7394: a call of a selector. One argument of the call (the TOS (top-of-stack))
 7395: is used for determining which method is used. In Smalltalk terminology:
 7396: a message (consisting of the selector and the other arguments) is sent
 7397: to the object.
 7398: 
 7399: @cindex receiving object
 7400: @item receiving object
 7401: the object used for determining the method executed by a selector
 7402: invocation. In the @file{objects.fs} model, it is the object that is on
 7403: the TOS when the selector is invoked. (@emph{Receiving} comes from
 7404: the Smalltalk @emph{message} terminology.)
 7405: 
 7406: @cindex child class
 7407: @cindex parent class
 7408: @cindex inheritance
 7409: @item child class
 7410: a class that has (@emph{inherits}) all properties (instance variables,
 7411: selectors, methods) from a @emph{parent class}. In Smalltalk
 7412: terminology: The subclass inherits from the superclass. In C++
 7413: terminology: The derived class inherits from the base class.
 7414: 
 7415: @end table
 7416: 
 7417: @c If you wonder about the message sending terminology, it comes from
 7418: @c a time when each object had it's own task and objects communicated via
 7419: @c message passing; eventually the Smalltalk developers realized that
 7420: @c they can do most things through simple (indirect) calls. They kept the
 7421: @c terminology.
 7422: 
 7423: 
 7424: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
 7425: @subsection The @file{objects.fs} model
 7426: @cindex objects
 7427: @cindex object-oriented programming
 7428: 
 7429: @cindex @file{objects.fs}
 7430: @cindex @file{oof.fs}
 7431: 
 7432: This section describes the @file{objects.fs} package. This material also
 7433: has been published in @cite{Yet Another Forth Objects Package} by Anton
 7434: Ertl and appeared in Forth Dimensions 19(2), pages 37--43
 7435: (@url{http://www.complang.tuwien.ac.at/forth/objects/objects.html}).
 7436: @c McKewan's and Zsoter's packages
 7437: 
 7438: This section assumes that you have read @ref{Structures}.
 7439: 
 7440: The techniques on which this model is based have been used to implement
 7441: the parser generator, Gray, and have also been used in Gforth for
 7442: implementing the various flavours of word lists (hashed or not,
 7443: case-sensitive or not, special-purpose word lists for locals etc.).
 7444: 
 7445: 
 7446: @menu
 7447: * Properties of the Objects model::  
 7448: * Basic Objects Usage::         
 7449: * The Objects base class::      
 7450: * Creating objects::            
 7451: * Object-Oriented Programming Style::  
 7452: * Class Binding::               
 7453: * Method conveniences::         
 7454: * Classes and Scoping::         
 7455: * Dividing classes::            
 7456: * Object Interfaces::           
 7457: * Objects Implementation::      
 7458: * Objects Glossary::            
 7459: @end menu
 7460: 
 7461: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
 7462: and Bernd Paysan helped me with the related works section.
 7463: 
 7464: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
 7465: @subsubsection Properties of the @file{objects.fs} model
 7466: @cindex @file{objects.fs} properties
 7467: 
 7468: @itemize @bullet
 7469: @item
 7470: It is straightforward to pass objects on the stack. Passing
 7471: selectors on the stack is a little less convenient, but possible.
 7472: 
 7473: @item
 7474: Objects are just data structures in memory, and are referenced by their
 7475: address. You can create words for objects with normal defining words
 7476: like @code{constant}. Likewise, there is no difference between instance
 7477: variables that contain objects and those that contain other data.
 7478: 
 7479: @item
 7480: Late binding is efficient and easy to use.
 7481: 
 7482: @item
 7483: It avoids parsing, and thus avoids problems with state-smartness
 7484: and reduced extensibility; for convenience there are a few parsing
 7485: words, but they have non-parsing counterparts. There are also a few
 7486: defining words that parse. This is hard to avoid, because all standard
 7487: defining words parse (except @code{:noname}); however, such
 7488: words are not as bad as many other parsing words, because they are not
 7489: state-smart.
 7490: 
 7491: @item
 7492: It does not try to incorporate everything. It does a few things and does
 7493: them well (IMO). In particular, this model was not designed to support
 7494: information hiding (although it has features that may help); you can use
 7495: a separate package for achieving this.
 7496: 
 7497: @item
 7498: It is layered; you don't have to learn and use all features to use this
 7499: model. Only a few features are necessary (@xref{Basic Objects Usage},
 7500: @xref{The Objects base class}, @xref{Creating objects}.), the others
 7501: are optional and independent of each other.
 7502: 
 7503: @item
 7504: An implementation in ANS Forth is available.
 7505: 
 7506: @end itemize
 7507: 
 7508: 
 7509: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
 7510: @subsubsection Basic @file{objects.fs} Usage
 7511: @cindex basic objects usage
 7512: @cindex objects, basic usage
 7513: 
 7514: You can define a class for graphical objects like this:
 7515: 
 7516: @cindex @code{class} usage
 7517: @cindex @code{end-class} usage
 7518: @cindex @code{selector} usage
 7519: @example
 7520: object class \ "object" is the parent class
 7521:   selector draw ( x y graphical -- )
 7522: end-class graphical
 7523: @end example
 7524: 
 7525: This code defines a class @code{graphical} with an
 7526: operation @code{draw}.  We can perform the operation
 7527: @code{draw} on any @code{graphical} object, e.g.:
 7528: 
 7529: @example
 7530: 100 100 t-rex draw
 7531: @end example
 7532: 
 7533: @noindent
 7534: where @code{t-rex} is a word (say, a constant) that produces a
 7535: graphical object.
 7536: 
 7537: @comment TODO add a 2nd operation eg perimeter.. and use for
 7538: @comment a concrete example
 7539: 
 7540: @cindex abstract class
 7541: How do we create a graphical object? With the present definitions,
 7542: we cannot create a useful graphical object. The class
 7543: @code{graphical} describes graphical objects in general, but not
 7544: any concrete graphical object type (C++ users would call it an
 7545: @emph{abstract class}); e.g., there is no method for the selector
 7546: @code{draw} in the class @code{graphical}.
 7547: 
 7548: For concrete graphical objects, we define child classes of the
 7549: class @code{graphical}, e.g.:
 7550: 
 7551: @cindex @code{overrides} usage
 7552: @cindex @code{field} usage in class definition
 7553: @example
 7554: graphical class \ "graphical" is the parent class
 7555:   cell% field circle-radius
 7556: 
 7557: :noname ( x y circle -- )
 7558:   circle-radius @@ draw-circle ;
 7559: overrides draw
 7560: 
 7561: :noname ( n-radius circle -- )
 7562:   circle-radius ! ;
 7563: overrides construct
 7564: 
 7565: end-class circle
 7566: @end example
 7567: 
 7568: Here we define a class @code{circle} as a child of @code{graphical},
 7569: with field @code{circle-radius} (which behaves just like a field
 7570: (@pxref{Structures}); it defines (using @code{overrides}) new methods
 7571: for the selectors @code{draw} and @code{construct} (@code{construct} is
 7572: defined in @code{object}, the parent class of @code{graphical}).
 7573: 
 7574: Now we can create a circle on the heap (i.e.,
 7575: @code{allocate}d memory) with:
 7576: 
 7577: @cindex @code{heap-new} usage
 7578: @example
 7579: 50 circle heap-new constant my-circle
 7580: @end example
 7581: 
 7582: @noindent
 7583: @code{heap-new} invokes @code{construct}, thus
 7584: initializing the field @code{circle-radius} with 50. We can draw
 7585: this new circle at (100,100) with:
 7586: 
 7587: @example
 7588: 100 100 my-circle draw
 7589: @end example
 7590: 
 7591: @cindex selector invocation, restrictions
 7592: @cindex class definition, restrictions
 7593: Note: You can only invoke a selector if the object on the TOS
 7594: (the receiving object) belongs to the class where the selector was
 7595: defined or one of its descendents; e.g., you can invoke
 7596: @code{draw} only for objects belonging to @code{graphical}
 7597: or its descendents (e.g., @code{circle}).  Immediately before
 7598: @code{end-class}, the search order has to be the same as
 7599: immediately after @code{class}.
 7600: 
 7601: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
 7602: @subsubsection The @file{object.fs} base class
 7603: @cindex @code{object} class
 7604: 
 7605: When you define a class, you have to specify a parent class.  So how do
 7606: you start defining classes? There is one class available from the start:
 7607: @code{object}. It is ancestor for all classes and so is the
 7608: only class that has no parent. It has two selectors: @code{construct}
 7609: and @code{print}.
 7610: 
 7611: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
 7612: @subsubsection Creating objects
 7613: @cindex creating objects
 7614: @cindex object creation
 7615: @cindex object allocation options
 7616: 
 7617: @cindex @code{heap-new} discussion
 7618: @cindex @code{dict-new} discussion
 7619: @cindex @code{construct} discussion
 7620: You can create and initialize an object of a class on the heap with
 7621: @code{heap-new} ( ... class -- object ) and in the dictionary
 7622: (allocation with @code{allot}) with @code{dict-new} (
 7623: ... class -- object ). Both words invoke @code{construct}, which
 7624: consumes the stack items indicated by "..." above.
 7625: 
 7626: @cindex @code{init-object} discussion
 7627: @cindex @code{class-inst-size} discussion
 7628: If you want to allocate memory for an object yourself, you can get its
 7629: alignment and size with @code{class-inst-size 2@@} ( class --
 7630: align size ). Once you have memory for an object, you can initialize
 7631: it with @code{init-object} ( ... class object -- );
 7632: @code{construct} does only a part of the necessary work.
 7633: 
 7634: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
 7635: @subsubsection Object-Oriented Programming Style
 7636: @cindex object-oriented programming style
 7637: 
 7638: This section is not exhaustive.
 7639: 
 7640: @cindex stack effects of selectors
 7641: @cindex selectors and stack effects
 7642: In general, it is a good idea to ensure that all methods for the
 7643: same selector have the same stack effect: when you invoke a selector,
 7644: you often have no idea which method will be invoked, so, unless all
 7645: methods have the same stack effect, you will not know the stack effect
 7646: of the selector invocation.
 7647: 
 7648: One exception to this rule is methods for the selector
 7649: @code{construct}. We know which method is invoked, because we
 7650: specify the class to be constructed at the same place. Actually, I
 7651: defined @code{construct} as a selector only to give the users a
 7652: convenient way to specify initialization. The way it is used, a
 7653: mechanism different from selector invocation would be more natural
 7654: (but probably would take more code and more space to explain).
 7655: 
 7656: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
 7657: @subsubsection Class Binding
 7658: @cindex class binding
 7659: @cindex early binding
 7660: 
 7661: @cindex late binding
 7662: Normal selector invocations determine the method at run-time depending
 7663: on the class of the receiving object. This run-time selection is called
 7664: @i{late binding}.
 7665: 
 7666: Sometimes it's preferable to invoke a different method. For example,
 7667: you might want to use the simple method for @code{print}ing
 7668: @code{object}s instead of the possibly long-winded @code{print} method
 7669: of the receiver class. You can achieve this by replacing the invocation
 7670: of @code{print} with:
 7671: 
 7672: @cindex @code{[bind]} usage
 7673: @example
 7674: [bind] object print
 7675: @end example
 7676: 
 7677: @noindent
 7678: in compiled code or:
 7679: 
 7680: @cindex @code{bind} usage
 7681: @example
 7682: bind object print
 7683: @end example
 7684: 
 7685: @cindex class binding, alternative to
 7686: @noindent
 7687: in interpreted code. Alternatively, you can define the method with a
 7688: name (e.g., @code{print-object}), and then invoke it through the
 7689: name. Class binding is just a (often more convenient) way to achieve
 7690: the same effect; it avoids name clutter and allows you to invoke
 7691: methods directly without naming them first.
 7692: 
 7693: @cindex superclass binding
 7694: @cindex parent class binding
 7695: A frequent use of class binding is this: When we define a method
 7696: for a selector, we often want the method to do what the selector does
 7697: in the parent class, and a little more. There is a special word for
 7698: this purpose: @code{[parent]}; @code{[parent]
 7699: @emph{selector}} is equivalent to @code{[bind] @emph{parent
 7700: selector}}, where @code{@emph{parent}} is the parent
 7701: class of the current class. E.g., a method definition might look like:
 7702: 
 7703: @cindex @code{[parent]} usage
 7704: @example
 7705: :noname
 7706:   dup [parent] foo \ do parent's foo on the receiving object
 7707:   ... \ do some more
 7708: ; overrides foo
 7709: @end example
 7710: 
 7711: @cindex class binding as optimization
 7712: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
 7713: March 1997), Andrew McKewan presents class binding as an optimization
 7714: technique. I recommend not using it for this purpose unless you are in
 7715: an emergency. Late binding is pretty fast with this model anyway, so the
 7716: benefit of using class binding is small; the cost of using class binding
 7717: where it is not appropriate is reduced maintainability.
 7718: 
 7719: While we are at programming style questions: You should bind
 7720: selectors only to ancestor classes of the receiving object. E.g., say,
 7721: you know that the receiving object is of class @code{foo} or its
 7722: descendents; then you should bind only to @code{foo} and its
 7723: ancestors.
 7724: 
 7725: @node Method conveniences, Classes and Scoping, Class Binding, Objects
 7726: @subsubsection Method conveniences
 7727: @cindex method conveniences
 7728: 
 7729: In a method you usually access the receiving object pretty often.  If
 7730: you define the method as a plain colon definition (e.g., with
 7731: @code{:noname}), you may have to do a lot of stack
 7732: gymnastics. To avoid this, you can define the method with @code{m:
 7733: ... ;m}. E.g., you could define the method for
 7734: @code{draw}ing a @code{circle} with
 7735: 
 7736: @cindex @code{this} usage
 7737: @cindex @code{m:} usage
 7738: @cindex @code{;m} usage
 7739: @example
 7740: m: ( x y circle -- )
 7741:   ( x y ) this circle-radius @@ draw-circle ;m
 7742: @end example
 7743: 
 7744: @cindex @code{exit} in @code{m: ... ;m}
 7745: @cindex @code{exitm} discussion
 7746: @cindex @code{catch} in @code{m: ... ;m}
 7747: When this method is executed, the receiver object is removed from the
 7748: stack; you can access it with @code{this} (admittedly, in this
 7749: example the use of @code{m: ... ;m} offers no advantage). Note
 7750: that I specify the stack effect for the whole method (i.e. including
 7751: the receiver object), not just for the code between @code{m:}
 7752: and @code{;m}. You cannot use @code{exit} in
 7753: @code{m:...;m}; instead, use
 7754: @code{exitm}.@footnote{Moreover, for any word that calls
 7755: @code{catch} and was defined before loading
 7756: @code{objects.fs}, you have to redefine it like I redefined
 7757: @code{catch}: @code{: catch this >r catch r> to-this ;}}
 7758: 
 7759: @cindex @code{inst-var} usage
 7760: You will frequently use sequences of the form @code{this
 7761: @emph{field}} (in the example above: @code{this
 7762: circle-radius}). If you use the field only in this way, you can
 7763: define it with @code{inst-var} and eliminate the
 7764: @code{this} before the field name. E.g., the @code{circle}
 7765: class above could also be defined with:
 7766: 
 7767: @example
 7768: graphical class
 7769:   cell% inst-var radius
 7770: 
 7771: m: ( x y circle -- )
 7772:   radius @@ draw-circle ;m
 7773: overrides draw
 7774: 
 7775: m: ( n-radius circle -- )
 7776:   radius ! ;m
 7777: overrides construct
 7778: 
 7779: end-class circle
 7780: @end example
 7781: 
 7782: @code{radius} can only be used in @code{circle} and its
 7783: descendent classes and inside @code{m:...;m}.
 7784: 
 7785: @cindex @code{inst-value} usage
 7786: You can also define fields with @code{inst-value}, which is
 7787: to @code{inst-var} what @code{value} is to
 7788: @code{variable}.  You can change the value of such a field with
 7789: @code{[to-inst]}.  E.g., we could also define the class
 7790: @code{circle} like this:
 7791: 
 7792: @example
 7793: graphical class
 7794:   inst-value radius
 7795: 
 7796: m: ( x y circle -- )
 7797:   radius draw-circle ;m
 7798: overrides draw
 7799: 
 7800: m: ( n-radius circle -- )
 7801:   [to-inst] radius ;m
 7802: overrides construct
 7803: 
 7804: end-class circle
 7805: @end example
 7806: 
 7807: Finally, you can define named methods with @code{:m}.  One use of this
 7808: feature is the definition of words that occur only in one class and are
 7809: not intended to be overridden, but which still need method context
 7810: (e.g., for accessing @code{inst-var}s).  Another use is for methods that
 7811: would be bound frequently, if defined anonymously.
 7812: 
 7813: 
 7814: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
 7815: @subsubsection Classes and Scoping
 7816: @cindex classes and scoping
 7817: @cindex scoping and classes
 7818: 
 7819: Inheritance is frequent, unlike structure extension. This exacerbates
 7820: the problem with the field name convention (@pxref{Structure Naming
 7821: Convention}): One always has to remember in which class the field was
 7822: originally defined; changing a part of the class structure would require
 7823: changes for renaming in otherwise unaffected code.
 7824: 
 7825: @cindex @code{inst-var} visibility
 7826: @cindex @code{inst-value} visibility
 7827: To solve this problem, I added a scoping mechanism (which was not in my
 7828: original charter): A field defined with @code{inst-var} (or
 7829: @code{inst-value}) is visible only in the class where it is defined and in
 7830: the descendent classes of this class.  Using such fields only makes
 7831: sense in @code{m:}-defined methods in these classes anyway.
 7832: 
 7833: This scoping mechanism allows us to use the unadorned field name,
 7834: because name clashes with unrelated words become much less likely.
 7835: 
 7836: @cindex @code{protected} discussion
 7837: @cindex @code{private} discussion
 7838: Once we have this mechanism, we can also use it for controlling the
 7839: visibility of other words: All words defined after
 7840: @code{protected} are visible only in the current class and its
 7841: descendents. @code{public} restores the compilation
 7842: (i.e. @code{current}) word list that was in effect before. If you
 7843: have several @code{protected}s without an intervening
 7844: @code{public} or @code{set-current}, @code{public}
 7845: will restore the compilation word list in effect before the first of
 7846: these @code{protected}s.
 7847: 
 7848: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
 7849: @subsubsection Dividing classes
 7850: @cindex Dividing classes
 7851: @cindex @code{methods}...@code{end-methods}
 7852: 
 7853: You may want to do the definition of methods separate from the
 7854: definition of the class, its selectors, fields, and instance variables,
 7855: i.e., separate the implementation from the definition.  You can do this
 7856: in the following way:
 7857: 
 7858: @example
 7859: graphical class
 7860:   inst-value radius
 7861: end-class circle
 7862: 
 7863: ... \ do some other stuff
 7864: 
 7865: circle methods \ now we are ready
 7866: 
 7867: m: ( x y circle -- )
 7868:   radius draw-circle ;m
 7869: overrides draw
 7870: 
 7871: m: ( n-radius circle -- )
 7872:   [to-inst] radius ;m
 7873: overrides construct
 7874: 
 7875: end-methods
 7876: @end example
 7877: 
 7878: You can use several @code{methods}...@code{end-methods} sections.  The
 7879: only things you can do to the class in these sections are: defining
 7880: methods, and overriding the class's selectors.  You must not define new
 7881: selectors or fields.
 7882: 
 7883: Note that you often have to override a selector before using it.  In
 7884: particular, you usually have to override @code{construct} with a new
 7885: method before you can invoke @code{heap-new} and friends.  E.g., you
 7886: must not create a circle before the @code{overrides construct} sequence
 7887: in the example above.
 7888: 
 7889: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
 7890: @subsubsection Object Interfaces
 7891: @cindex object interfaces
 7892: @cindex interfaces for objects
 7893: 
 7894: In this model you can only call selectors defined in the class of the
 7895: receiving objects or in one of its ancestors. If you call a selector
 7896: with a receiving object that is not in one of these classes, the
 7897: result is undefined; if you are lucky, the program crashes
 7898: immediately.
 7899: 
 7900: @cindex selectors common to hardly-related classes
 7901: Now consider the case when you want to have a selector (or several)
 7902: available in two classes: You would have to add the selector to a
 7903: common ancestor class, in the worst case to @code{object}. You
 7904: may not want to do this, e.g., because someone else is responsible for
 7905: this ancestor class.
 7906: 
 7907: The solution for this problem is interfaces. An interface is a
 7908: collection of selectors. If a class implements an interface, the
 7909: selectors become available to the class and its descendents. A class
 7910: can implement an unlimited number of interfaces. For the problem
 7911: discussed above, we would define an interface for the selector(s), and
 7912: both classes would implement the interface.
 7913: 
 7914: As an example, consider an interface @code{storage} for
 7915: writing objects to disk and getting them back, and a class
 7916: @code{foo} that implements it. The code would look like this:
 7917: 
 7918: @cindex @code{interface} usage
 7919: @cindex @code{end-interface} usage
 7920: @cindex @code{implementation} usage
 7921: @example
 7922: interface
 7923:   selector write ( file object -- )
 7924:   selector read1 ( file object -- )
 7925: end-interface storage
 7926: 
 7927: bar class
 7928:   storage implementation
 7929: 
 7930: ... overrides write
 7931: ... overrides read1
 7932: ...
 7933: end-class foo
 7934: @end example
 7935: 
 7936: @noindent
 7937: (I would add a word @code{read} @i{( file -- object )} that uses
 7938: @code{read1} internally, but that's beyond the point illustrated
 7939: here.)
 7940: 
 7941: Note that you cannot use @code{protected} in an interface; and
 7942: of course you cannot define fields.
 7943: 
 7944: In the Neon model, all selectors are available for all classes;
 7945: therefore it does not need interfaces. The price you pay in this model
 7946: is slower late binding, and therefore, added complexity to avoid late
 7947: binding.
 7948: 
 7949: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
 7950: @subsubsection @file{objects.fs} Implementation
 7951: @cindex @file{objects.fs} implementation
 7952: 
 7953: @cindex @code{object-map} discussion
 7954: An object is a piece of memory, like one of the data structures
 7955: described with @code{struct...end-struct}. It has a field
 7956: @code{object-map} that points to the method map for the object's
 7957: class.
 7958: 
 7959: @cindex method map
 7960: @cindex virtual function table
 7961: The @emph{method map}@footnote{This is Self terminology; in C++
 7962: terminology: virtual function table.} is an array that contains the
 7963: execution tokens (@i{xt}s) of the methods for the object's class. Each
 7964: selector contains an offset into a method map.
 7965: 
 7966: @cindex @code{selector} implementation, class
 7967: @code{selector} is a defining word that uses
 7968: @code{CREATE} and @code{DOES>}. The body of the
 7969: selector contains the offset; the @code{does>} action for a
 7970: class selector is, basically:
 7971: 
 7972: @example
 7973: ( object addr ) @@ over object-map @@ + @@ execute
 7974: @end example
 7975: 
 7976: Since @code{object-map} is the first field of the object, it
 7977: does not generate any code. As you can see, calling a selector has a
 7978: small, constant cost.
 7979: 
 7980: @cindex @code{current-interface} discussion
 7981: @cindex class implementation and representation
 7982: A class is basically a @code{struct} combined with a method
 7983: map. During the class definition the alignment and size of the class
 7984: are passed on the stack, just as with @code{struct}s, so
 7985: @code{field} can also be used for defining class
 7986: fields. However, passing more items on the stack would be
 7987: inconvenient, so @code{class} builds a data structure in memory,
 7988: which is accessed through the variable
 7989: @code{current-interface}. After its definition is complete, the
 7990: class is represented on the stack by a pointer (e.g., as parameter for
 7991: a child class definition).
 7992: 
 7993: A new class starts off with the alignment and size of its parent,
 7994: and a copy of the parent's method map. Defining new fields extends the
 7995: size and alignment; likewise, defining new selectors extends the
 7996: method map. @code{overrides} just stores a new @i{xt} in the method
 7997: map at the offset given by the selector.
 7998: 
 7999: @cindex class binding, implementation
 8000: Class binding just gets the @i{xt} at the offset given by the selector
 8001: from the class's method map and @code{compile,}s (in the case of
 8002: @code{[bind]}) it.
 8003: 
 8004: @cindex @code{this} implementation
 8005: @cindex @code{catch} and @code{this}
 8006: @cindex @code{this} and @code{catch}
 8007: I implemented @code{this} as a @code{value}. At the
 8008: start of an @code{m:...;m} method the old @code{this} is
 8009: stored to the return stack and restored at the end; and the object on
 8010: the TOS is stored @code{TO this}. This technique has one
 8011: disadvantage: If the user does not leave the method via
 8012: @code{;m}, but via @code{throw} or @code{exit},
 8013: @code{this} is not restored (and @code{exit} may
 8014: crash). To deal with the @code{throw} problem, I have redefined
 8015: @code{catch} to save and restore @code{this}; the same
 8016: should be done with any word that can catch an exception. As for
 8017: @code{exit}, I simply forbid it (as a replacement, there is
 8018: @code{exitm}).
 8019: 
 8020: @cindex @code{inst-var} implementation
 8021: @code{inst-var} is just the same as @code{field}, with
 8022: a different @code{DOES>} action:
 8023: @example
 8024: @@ this +
 8025: @end example
 8026: Similar for @code{inst-value}.
 8027: 
 8028: @cindex class scoping implementation
 8029: Each class also has a word list that contains the words defined with
 8030: @code{inst-var} and @code{inst-value}, and its protected
 8031: words. It also has a pointer to its parent. @code{class} pushes
 8032: the word lists of the class and all its ancestors onto the search order stack,
 8033: and @code{end-class} drops them.
 8034: 
 8035: @cindex interface implementation
 8036: An interface is like a class without fields, parent and protected
 8037: words; i.e., it just has a method map. If a class implements an
 8038: interface, its method map contains a pointer to the method map of the
 8039: interface. The positive offsets in the map are reserved for class
 8040: methods, therefore interface map pointers have negative
 8041: offsets. Interfaces have offsets that are unique throughout the
 8042: system, unlike class selectors, whose offsets are only unique for the
 8043: classes where the selector is available (invokable).
 8044: 
 8045: This structure means that interface selectors have to perform one
 8046: indirection more than class selectors to find their method. Their body
 8047: contains the interface map pointer offset in the class method map, and
 8048: the method offset in the interface method map. The
 8049: @code{does>} action for an interface selector is, basically:
 8050: 
 8051: @example
 8052: ( object selector-body )
 8053: 2dup selector-interface @@ ( object selector-body object interface-offset )
 8054: swap object-map @@ + @@ ( object selector-body map )
 8055: swap selector-offset @@ + @@ execute
 8056: @end example
 8057: 
 8058: where @code{object-map} and @code{selector-offset} are
 8059: first fields and generate no code.
 8060: 
 8061: As a concrete example, consider the following code:
 8062: 
 8063: @example
 8064: interface
 8065:   selector if1sel1
 8066:   selector if1sel2
 8067: end-interface if1
 8068: 
 8069: object class
 8070:   if1 implementation
 8071:   selector cl1sel1
 8072:   cell% inst-var cl1iv1
 8073: 
 8074: ' m1 overrides construct
 8075: ' m2 overrides if1sel1
 8076: ' m3 overrides if1sel2
 8077: ' m4 overrides cl1sel2
 8078: end-class cl1
 8079: 
 8080: create obj1 object dict-new drop
 8081: create obj2 cl1    dict-new drop
 8082: @end example
 8083: 
 8084: The data structure created by this code (including the data structure
 8085: for @code{object}) is shown in the <a
 8086: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
 8087: @comment TODO add this diagram..
 8088: 
 8089: @node Objects Glossary,  , Objects Implementation, Objects
 8090: @subsubsection @file{objects.fs} Glossary
 8091: @cindex @file{objects.fs} Glossary
 8092: 
 8093: doc---objects-bind
 8094: doc---objects-<bind>
 8095: doc---objects-bind'
 8096: doc---objects-[bind]
 8097: doc---objects-class
 8098: doc---objects-class->map
 8099: doc---objects-class-inst-size
 8100: doc---objects-class-override!
 8101: doc---objects-construct
 8102: doc---objects-current'
 8103: doc---objects-[current]
 8104: doc---objects-current-interface
 8105: doc---objects-dict-new
 8106: doc---objects-drop-order
 8107: doc---objects-end-class
 8108: doc---objects-end-class-noname
 8109: doc---objects-end-interface
 8110: doc---objects-end-interface-noname
 8111: doc---objects-end-methods
 8112: doc---objects-exitm
 8113: doc---objects-heap-new
 8114: doc---objects-implementation
 8115: doc---objects-init-object
 8116: doc---objects-inst-value
 8117: doc---objects-inst-var
 8118: doc---objects-interface
 8119: doc---objects-m:
 8120: doc---objects-:m
 8121: doc---objects-;m
 8122: doc---objects-method
 8123: doc---objects-methods
 8124: doc---objects-object
 8125: doc---objects-overrides
 8126: doc---objects-[parent]
 8127: doc---objects-print
 8128: doc---objects-protected
 8129: doc---objects-public
 8130: doc---objects-push-order
 8131: doc---objects-selector
 8132: doc---objects-this
 8133: doc---objects-<to-inst>
 8134: doc---objects-[to-inst]
 8135: doc---objects-to-this
 8136: doc---objects-xt-new
 8137: 
 8138: @c -------------------------------------------------------------
 8139: @node OOF, Mini-OOF, Objects, Object-oriented Forth
 8140: @subsection The @file{oof.fs} model
 8141: @cindex oof
 8142: @cindex object-oriented programming
 8143: 
 8144: @cindex @file{objects.fs}
 8145: @cindex @file{oof.fs}
 8146: 
 8147: This section describes the @file{oof.fs} package.
 8148: 
 8149: The package described in this section has been used in bigFORTH since 1991, and
 8150: used for two large applications: a chromatographic system used to
 8151: create new medicaments, and a graphic user interface library (MINOS).
 8152: 
 8153: You can find a description (in German) of @file{oof.fs} in @cite{Object
 8154: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
 8155: 10(2), 1994.
 8156: 
 8157: @menu
 8158: * Properties of the OOF model::
 8159: * Basic OOF Usage::
 8160: * The OOF base class::
 8161: * Class Declaration::
 8162: * Class Implementation::
 8163: @end menu
 8164: 
 8165: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
 8166: @subsubsection Properties of the @file{oof.fs} model
 8167: @cindex @file{oof.fs} properties
 8168: 
 8169: @itemize @bullet
 8170: @item
 8171: This model combines object oriented programming with information
 8172: hiding. It helps you writing large application, where scoping is
 8173: necessary, because it provides class-oriented scoping.
 8174: 
 8175: @item
 8176: Named objects, object pointers, and object arrays can be created,
 8177: selector invocation uses the ``object selector'' syntax. Selector invocation
 8178: to objects and/or selectors on the stack is a bit less convenient, but
 8179: possible.
 8180: 
 8181: @item
 8182: Selector invocation and instance variable usage of the active object is
 8183: straightforward, since both make use of the active object.
 8184: 
 8185: @item
 8186: Late binding is efficient and easy to use.
 8187: 
 8188: @item
 8189: State-smart objects parse selectors. However, extensibility is provided
 8190: using a (parsing) selector @code{postpone} and a selector @code{'}.
 8191: 
 8192: @item
 8193: An implementation in ANS Forth is available.
 8194: 
 8195: @end itemize
 8196: 
 8197: 
 8198: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
 8199: @subsubsection Basic @file{oof.fs} Usage
 8200: @cindex @file{oof.fs} usage
 8201: 
 8202: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
 8203: 
 8204: You can define a class for graphical objects like this:
 8205: 
 8206: @cindex @code{class} usage
 8207: @cindex @code{class;} usage
 8208: @cindex @code{method} usage
 8209: @example
 8210: object class graphical \ "object" is the parent class
 8211:   method draw ( x y graphical -- )
 8212: class;
 8213: @end example
 8214: 
 8215: This code defines a class @code{graphical} with an
 8216: operation @code{draw}.  We can perform the operation
 8217: @code{draw} on any @code{graphical} object, e.g.:
 8218: 
 8219: @example
 8220: 100 100 t-rex draw
 8221: @end example
 8222: 
 8223: @noindent
 8224: where @code{t-rex} is an object or object pointer, created with e.g.
 8225: @code{graphical : t-rex}.
 8226: 
 8227: @cindex abstract class
 8228: How do we create a graphical object? With the present definitions,
 8229: we cannot create a useful graphical object. The class
 8230: @code{graphical} describes graphical objects in general, but not
 8231: any concrete graphical object type (C++ users would call it an
 8232: @emph{abstract class}); e.g., there is no method for the selector
 8233: @code{draw} in the class @code{graphical}.
 8234: 
 8235: For concrete graphical objects, we define child classes of the
 8236: class @code{graphical}, e.g.:
 8237: 
 8238: @example
 8239: graphical class circle \ "graphical" is the parent class
 8240:   cell var circle-radius
 8241: how:
 8242:   : draw ( x y -- )
 8243:     circle-radius @@ draw-circle ;
 8244: 
 8245:   : init ( n-radius -- (
 8246:     circle-radius ! ;
 8247: class;
 8248: @end example
 8249: 
 8250: Here we define a class @code{circle} as a child of @code{graphical},
 8251: with a field @code{circle-radius}; it defines new methods for the
 8252: selectors @code{draw} and @code{init} (@code{init} is defined in
 8253: @code{object}, the parent class of @code{graphical}).
 8254: 
 8255: Now we can create a circle in the dictionary with:
 8256: 
 8257: @example
 8258: 50 circle : my-circle
 8259: @end example
 8260: 
 8261: @noindent
 8262: @code{:} invokes @code{init}, thus initializing the field
 8263: @code{circle-radius} with 50. We can draw this new circle at (100,100)
 8264: with:
 8265: 
 8266: @example
 8267: 100 100 my-circle draw
 8268: @end example
 8269: 
 8270: @cindex selector invocation, restrictions
 8271: @cindex class definition, restrictions
 8272: Note: You can only invoke a selector if the receiving object belongs to
 8273: the class where the selector was defined or one of its descendents;
 8274: e.g., you can invoke @code{draw} only for objects belonging to
 8275: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
 8276: mechanism will check if you try to invoke a selector that is not
 8277: defined in this class hierarchy, so you'll get an error at compilation
 8278: time.
 8279: 
 8280: 
 8281: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
 8282: @subsubsection The @file{oof.fs} base class
 8283: @cindex @file{oof.fs} base class
 8284: 
 8285: When you define a class, you have to specify a parent class.  So how do
 8286: you start defining classes? There is one class available from the start:
 8287: @code{object}. You have to use it as ancestor for all classes. It is the
 8288: only class that has no parent. Classes are also objects, except that
 8289: they don't have instance variables; class manipulation such as
 8290: inheritance or changing definitions of a class is handled through
 8291: selectors of the class @code{object}.
 8292: 
 8293: @code{object} provides a number of selectors:
 8294: 
 8295: @itemize @bullet
 8296: @item
 8297: @code{class} for subclassing, @code{definitions} to add definitions
 8298: later on, and @code{class?} to get type informations (is the class a
 8299: subclass of the class passed on the stack?).
 8300: doc---object-class
 8301: doc---object-definitions
 8302: doc---object-class?
 8303: 
 8304: @item
 8305: @code{init} and @code{dispose} as constructor and destructor of the
 8306: object. @code{init} is invocated after the object's memory is allocated,
 8307: while @code{dispose} also handles deallocation. Thus if you redefine
 8308: @code{dispose}, you have to call the parent's dispose with @code{super
 8309: dispose}, too.
 8310: doc---object-init
 8311: doc---object-dispose
 8312: 
 8313: @item
 8314: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
 8315: @code{[]} to create named and unnamed objects and object arrays or
 8316: object pointers.
 8317: doc---object-new
 8318: doc---object-new[]
 8319: doc---object-:
 8320: doc---object-ptr
 8321: doc---object-asptr
 8322: doc---object-[]
 8323: 
 8324: @item
 8325: @code{::} and @code{super} for explicit scoping. You should use explicit
 8326: scoping only for super classes or classes with the same set of instance
 8327: variables. Explicitly-scoped selectors use early binding.
 8328: doc---object-::
 8329: doc---object-super
 8330: 
 8331: @item
 8332: @code{self} to get the address of the object
 8333: doc---object-self
 8334: 
 8335: @item
 8336: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
 8337: pointers and instance defers.
 8338: doc---object-bind
 8339: doc---object-bound
 8340: doc---object-link
 8341: doc---object-is
 8342: 
 8343: @item
 8344: @code{'} to obtain selector tokens, @code{send} to invocate selectors
 8345: form the stack, and @code{postpone} to generate selector invocation code.
 8346: doc---object-'
 8347: doc---object-postpone
 8348: 
 8349: @item
 8350: @code{with} and @code{endwith} to select the active object from the
 8351: stack, and enable its scope. Using @code{with} and @code{endwith}
 8352: also allows you to create code using selector @code{postpone} without being
 8353: trapped by the state-smart objects.
 8354: doc---object-with
 8355: doc---object-endwith
 8356: 
 8357: @end itemize
 8358: 
 8359: @node Class Declaration, Class Implementation, The OOF base class, OOF
 8360: @subsubsection Class Declaration
 8361: @cindex class declaration
 8362: 
 8363: @itemize @bullet
 8364: @item
 8365: Instance variables
 8366: doc---oof-var
 8367: 
 8368: @item
 8369: Object pointers
 8370: doc---oof-ptr
 8371: doc---oof-asptr
 8372: 
 8373: @item
 8374: Instance defers
 8375: doc---oof-defer
 8376: 
 8377: @item
 8378: Method selectors
 8379: doc---oof-early
 8380: doc---oof-method
 8381: 
 8382: @item
 8383: Class-wide variables
 8384: doc---oof-static
 8385: 
 8386: @item
 8387: End declaration
 8388: doc---oof-how:
 8389: doc---oof-class;
 8390: 
 8391: @end itemize
 8392: 
 8393: @c -------------------------------------------------------------
 8394: @node Class Implementation,  , Class Declaration, OOF
 8395: @subsubsection Class Implementation
 8396: @cindex class implementation
 8397: 
 8398: @c -------------------------------------------------------------
 8399: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
 8400: @subsection The @file{mini-oof.fs} model
 8401: @cindex mini-oof
 8402: 
 8403: Gforth's third object oriented Forth package is a 12-liner. It uses a
 8404: mixture of the @file{object.fs} and the @file{oof.fs} syntax,
 8405: and reduces to the bare minimum of features. This is based on a posting
 8406: of Bernd Paysan in comp.arch.
 8407: 
 8408: @menu
 8409: * Basic Mini-OOF Usage::
 8410: * Mini-OOF Example::
 8411: * Mini-OOF Implementation::
 8412: @end menu
 8413: 
 8414: @c -------------------------------------------------------------
 8415: @node Basic Mini-OOF Usage, Mini-OOF Example, , Mini-OOF
 8416: @subsubsection Basic @file{mini-oof.fs} Usage
 8417: @cindex mini-oof usage
 8418: 
 8419: There is a base class (@code{class}, which allocates one cell for the
 8420: object pointer) plus seven other words: to define a method, a variable,
 8421: a class; to end a class, to resolve binding, to allocate an object and
 8422: to compile a class method.
 8423: @comment TODO better description of the last one
 8424: 
 8425: doc-object
 8426: doc-method
 8427: doc-var
 8428: doc-class
 8429: doc-end-class
 8430: doc-defines
 8431: doc-new
 8432: doc-::
 8433: 
 8434: 
 8435: @c -------------------------------------------------------------
 8436: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
 8437: @subsubsection Mini-OOF Example
 8438: @cindex mini-oof example
 8439: 
 8440: A short example shows how to use this package. This example, in slightly
 8441: extended form, is supplied as @file{moof-exm.fs}
 8442: @comment TODO could flesh this out with some comments from the Forthwrite article
 8443: 
 8444: @example
 8445: object class
 8446:   method init
 8447:   method draw
 8448: end-class graphical
 8449: @end example
 8450: 
 8451: This code defines a class @code{graphical} with an
 8452: operation @code{draw}.  We can perform the operation
 8453: @code{draw} on any @code{graphical} object, e.g.:
 8454: 
 8455: @example
 8456: 100 100 t-rex draw
 8457: @end example
 8458: 
 8459: where @code{t-rex} is an object or object pointer, created with e.g.
 8460: @code{graphical new Constant t-rex}.
 8461: 
 8462: For concrete graphical objects, we define child classes of the
 8463: class @code{graphical}, e.g.:
 8464: 
 8465: @example
 8466: graphical class
 8467:   cell var circle-radius
 8468: end-class circle \ "graphical" is the parent class
 8469: 
 8470: :noname ( x y -- )
 8471:   circle-radius @@ draw-circle ; circle defines draw
 8472: :noname ( r -- )
 8473:   circle-radius ! ; circle defines init
 8474: @end example
 8475: 
 8476: There is no implicit init method, so we have to define one. The creation
 8477: code of the object now has to call init explicitely.
 8478: 
 8479: @example
 8480: circle new Constant my-circle
 8481: 50 my-circle init
 8482: @end example
 8483: 
 8484: It is also possible to add a function to create named objects with
 8485: automatic call of @code{init}, given that all objects have @code{init}
 8486: on the same place:
 8487: 
 8488: @example
 8489: : new: ( .. o "name" -- )
 8490:     new dup Constant init ;
 8491: 80 circle new: large-circle
 8492: @end example
 8493: 
 8494: We can draw this new circle at (100,100) with:
 8495: 
 8496: @example
 8497: 100 100 my-circle draw
 8498: @end example
 8499: 
 8500: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
 8501: @subsubsection @file{mini-oof.fs} Implementation
 8502: 
 8503: Object-oriented systems with late binding typically use a
 8504: ``vtable''-approach: the first variable in each object is a pointer to a
 8505: table, which contains the methods as function pointers. The vtable
 8506: may also contain other information.
 8507: 
 8508: So first, let's declare methods:
 8509: 
 8510: @example
 8511: : method ( m v -- m' v ) Create  over , swap cell+ swap
 8512:   DOES> ( ... o -- ... ) @ over @ + @ execute ;
 8513: @end example
 8514: 
 8515: During method declaration, the number of methods and instance
 8516: variables is on the stack (in address units). @code{method} creates
 8517: one method and increments the method number. To execute a method, it
 8518: takes the object, fetches the vtable pointer, adds the offset, and
 8519: executes the @i{xt} stored there. Each method takes the object it is
 8520: invoked from as top of stack parameter. The method itself should
 8521: consume that object.
 8522: 
 8523: Now, we also have to declare instance variables
 8524: 
 8525: @example
 8526: : var ( m v size -- m v' ) Create  over , +
 8527:   DOES> ( o -- addr ) @ + ;
 8528: @end example
 8529: 
 8530: As before, a word is created with the current offset. Instance
 8531: variables can have different sizes (cells, floats, doubles, chars), so
 8532: all we do is take the size and add it to the offset. If your machine
 8533: has alignment restrictions, put the proper @code{aligned} or
 8534: @code{faligned} before the variable, to adjust the variable
 8535: offset. That's why it is on the top of stack.
 8536: 
 8537: We need a starting point (the base object) and some syntactic sugar:
 8538: 
 8539: @example
 8540: Create object  1 cells , 2 cells ,
 8541: : class ( class -- class methods vars ) dup 2@ ;
 8542: @end example
 8543: 
 8544: For inheritance, the vtable of the parent object has to be
 8545: copied when a new, derived class is declared. This gives all the
 8546: methods of the parent class, which can be overridden, though.
 8547: 
 8548: @example
 8549: : end-class  ( class methods vars -- )
 8550:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
 8551:   cell+ dup cell+ r> rot @ 2 cells /string move ;
 8552: @end example
 8553: 
 8554: The first line creates the vtable, initialized with
 8555: @code{noop}s. The second line is the inheritance mechanism, it
 8556: copies the xts from the parent vtable.
 8557: 
 8558: We still have no way to define new methods, let's do that now:
 8559: 
 8560: @example
 8561: : defines ( xt class -- ) ' >body @ + ! ;
 8562: @end example
 8563: 
 8564: To allocate a new object, we need a word, too:
 8565: 
 8566: @example
 8567: : new ( class -- o )  here over @ allot swap over ! ;
 8568: @end example
 8569: 
 8570: Sometimes derived classes want to access the method of the
 8571: parent object. There are two ways to achieve this with Mini-OOF:
 8572: first, you could use named words, and second, you could look up the
 8573: vtable of the parent object.
 8574: 
 8575: @example
 8576: : :: ( class "name" -- ) ' >body @ + @ compile, ;
 8577: @end example
 8578: 
 8579: 
 8580: Nothing can be more confusing than a good example, so here is
 8581: one. First let's declare a text object (called
 8582: @code{button}), that stores text and position:
 8583: 
 8584: @example
 8585: object class
 8586:   cell var text
 8587:   cell var len
 8588:   cell var x
 8589:   cell var y
 8590:   method init
 8591:   method draw
 8592: end-class button
 8593: @end example
 8594: 
 8595: @noindent
 8596: Now, implement the two methods, @code{draw} and @code{init}:
 8597: 
 8598: @example
 8599: :noname ( o -- )
 8600:  >r r@ x @ r@ y @ at-xy  r@ text @ r> len @ type ;
 8601:  button defines draw
 8602: :noname ( addr u o -- )
 8603:  >r 0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
 8604:  button defines init
 8605: @end example
 8606: 
 8607: @noindent
 8608: To demonstrate inheritance, we define a class @code{bold-button}, with no
 8609: new data and no new methods:
 8610: 
 8611: @example
 8612: button class
 8613: end-class bold-button
 8614: 
 8615: : bold   27 emit ." [1m" ;
 8616: : normal 27 emit ." [0m" ;
 8617: @end example
 8618: 
 8619: @noindent
 8620: The class @code{bold-button} has a different draw method to
 8621: @code{button}, but the new method is defined in terms of the draw method
 8622: for @code{button}:
 8623: 
 8624: @example
 8625: :noname bold [ button :: draw ] normal ; bold-button defines draw
 8626: @end example
 8627: 
 8628: @noindent
 8629: Finally, create two objects and apply methods:
 8630: 
 8631: @example
 8632: button new Constant foo
 8633: s" thin foo" foo init
 8634: page
 8635: foo draw
 8636: bold-button new Constant bar
 8637: s" fat bar" bar init
 8638: 1 bar y !
 8639: bar draw
 8640: @end example
 8641: 
 8642: 
 8643: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
 8644: @subsubsection Comparison with other object models
 8645: @cindex comparison of object models
 8646: @cindex object models, comparison
 8647: 
 8648: Many object-oriented Forth extensions have been proposed (@cite{A survey
 8649: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
 8650: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
 8651: relation of the object models described here to two well-known and two
 8652: closely-related (by the use of method maps) models.
 8653: 
 8654: @cindex Neon model
 8655: The most popular model currently seems to be the Neon model (see
 8656: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
 8657: 1997) by Andrew McKewan) but this model has a number of limitations
 8658: @footnote{A longer version of this critique can be
 8659: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
 8660: Dimensions, May 1997) by Anton Ertl.}:
 8661: 
 8662: @itemize @bullet
 8663: @item
 8664: It uses a @code{@emph{selector
 8665: object}} syntax, which makes it unnatural to pass objects on the
 8666: stack.
 8667: 
 8668: @item
 8669: It requires that the selector parses the input stream (at
 8670: compile time); this leads to reduced extensibility and to bugs that are+
 8671: hard to find.
 8672: 
 8673: @item
 8674: It allows using every selector to every object;
 8675: this eliminates the need for classes, but makes it harder to create
 8676: efficient implementations. 
 8677: @end itemize
 8678: 
 8679: @cindex Pountain's object-oriented model
 8680: Another well-known publication is @cite{Object-Oriented Forth} (Academic
 8681: Press, London, 1987) by Dick Pountain. However, it is not really about
 8682: object-oriented programming, because it hardly deals with late
 8683: binding. Instead, it focuses on features like information hiding and
 8684: overloading that are characteristic of modular languages like Ada (83).
 8685: 
 8686: @cindex Zsoter's object-oriented model
 8687: In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1) 1996, pages 31-35)
 8688: Andras Zsoter describes a model that makes heavy use of an active object
 8689: (like @code{this} in @file{objects.fs}): The active object is not only
 8690: used for accessing all fields, but also specifies the receiving object
 8691: of every selector invocation; you have to change the active object
 8692: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
 8693: changes more or less implicitly at @code{m: ... ;m}. Such a change at
 8694: the method entry point is unnecessary with the Zsoter's model, because
 8695: the receiving object is the active object already. On the other hand, the explicit
 8696: change is absolutely necessary in that model, because otherwise no one
 8697: could ever change the active object. An ANS Forth implementation of this
 8698: model is available at @url{http://www.forth.org/fig/oopf.html}.
 8699: 
 8700: @cindex @file{oof.fs}, differences to other models
 8701: The @file{oof.fs} model combines information hiding and overloading
 8702: resolution (by keeping names in various word lists) with object-oriented
 8703: programming. It sets the active object implicitly on method entry, but
 8704: also allows explicit changing (with @code{>o...o>} or with
 8705: @code{with...endwith}). It uses parsing and state-smart objects and
 8706: classes for resolving overloading and for early binding: the object or
 8707: class parses the selector and determines the method from this. If the
 8708: selector is not parsed by an object or class, it performs a call to the
 8709: selector for the active object (late binding), like Zsoter's model.
 8710: Fields are always accessed through the active object. The big
 8711: disadvantage of this model is the parsing and the state-smartness, which
 8712: reduces extensibility and increases the opportunities for subtle bugs;
 8713: essentially, you are only safe if you never tick or @code{postpone} an
 8714: object or class (Bernd disagrees, but I (Anton) am not convinced).
 8715: 
 8716: @cindex @file{mini-oof.fs}, differences to other models
 8717: The @file{mini-oof.fs} model is quite similar to a very stripped-down version of
 8718: the @file{objects.fs} model, but syntactically it is a mixture of the @file{objects.fs} and
 8719: @file{oof.fs} models.
 8720: 
 8721: @c -------------------------------------------------------------
 8722: @node Passing Commands to the OS, Miscellaneous Words, Object-oriented Forth, Words
 8723: @section Passing Commands to the Operating System
 8724: @cindex operating system - passing commands
 8725: @cindex shell commands
 8726: 
 8727: Gforth allows you to pass an arbitrary string to the host operating
 8728: system shell (if such a thing exists) for execution.
 8729: 
 8730: doc-sh
 8731: doc-system
 8732: doc-$?
 8733: doc-getenv
 8734: 
 8735: @c -------------------------------------------------------------
 8736: @node Miscellaneous Words,  , Passing Commands to the OS, Words
 8737: @section Miscellaneous Words
 8738: @cindex miscellaneous words
 8739: 
 8740: @comment TODO find homes for these
 8741: 
 8742: These section lists the ANS Forth words that are not documented
 8743: elsewhere in this manual. Ultimately, they all need proper homes.
 8744: 
 8745: doc-ms
 8746: doc-time&date
 8747: 
 8748: doc-[compile]
 8749: 
 8750: The following ANS Forth words are not currently supported by Gforth 
 8751: (@pxref{ANS conformance}):
 8752: 
 8753: @code{EDITOR} 
 8754: @code{EMIT?} 
 8755: @code{FORGET} 
 8756: 
 8757: @c ******************************************************************
 8758: @node Error messages, Tools, Words, Top
 8759: @chapter Error messages
 8760: @cindex error messages
 8761: @cindex backtrace
 8762: 
 8763: A typical Gforth error message looks like this:
 8764: 
 8765: @example
 8766: in file included from :-1
 8767: in file included from ./yyy.fs:1
 8768: ./xxx.fs:4: Invalid memory address
 8769: bar
 8770: ^^^
 8771: $400E664C @@
 8772: $400E6664 foo
 8773: @end example
 8774: 
 8775: The message identifying the error is @code{Invalid memory address}.  The
 8776: error happened when text-interpreting line 4 of the file
 8777: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
 8778: word on the line where the error happened, is pointed out (with
 8779: @code{^^^}).
 8780: 
 8781: The file containing the error was included in line 1 of @file{./yyy.fs},
 8782: and @file{yyy.fs} was included from a non-file (in this case, by giving
 8783: @file{yyy.fs} as command-line parameter to Gforth).
 8784: 
 8785: At the end of the error message you find a return stack dump that can be
 8786: interpreted as a backtrace (possibly empty). On top you find the top of
 8787: the return stack when the @code{throw} happened, and at the bottom you
 8788: find the return stack entry just above the return stack of the topmost
 8789: text interpreter.
 8790: 
 8791: To the right of most return stack entries you see a guess for the word
 8792: that pushed that return stack entry as its return address. This gives a
 8793: backtrace. In our case we see that @code{bar} called @code{foo}, and
 8794: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
 8795: address} exception).
 8796: 
 8797: Note that the backtrace is not perfect: We don't know which return stack
 8798: entries are return addresses (so we may get false positives); and in
 8799: some cases (e.g., for @code{abort"}) we cannot determine from the return
 8800: address the word that pushed the return address, so for some return
 8801: addresses you see no names in the return stack dump.
 8802: 
 8803: @cindex @code{catch} and backtraces
 8804: The return stack dump represents the return stack at the time when a
 8805: specific @code{throw} was executed.  In programs that make use of
 8806: @code{catch}, it is not necessarily clear which @code{throw} should be
 8807: used for the return stack dump (e.g., consider one @code{throw} that
 8808: indicates an error, which is caught, and during recovery another error
 8809: happens; which @code{throw} should be used for the stack dump).  Gforth
 8810: presents the return stack dump for the first @code{throw} after the last
 8811: executed (not returned-to) @code{catch}; this works well in the usual
 8812: case.
 8813: 
 8814: @cindex @code{gforth-fast} and backtraces
 8815: @cindex @code{gforth-fast}, difference from @code{gforth}
 8816: @cindex backtraces with @code{gforth-fast}
 8817: @cindex return stack dump with @code{gforth-fast}
 8818: @code{gforth} is able to do a return stack dump for throws generated
 8819: from primitives (e.g., invalid memory address, stack empty etc.);
 8820: @code{gforth-fast} is only able to do a return stack dump from a
 8821: directly called @code{throw} (including @code{abort} etc.).  This is the
 8822: only difference (apart from a speed factor of between 1.15 (K6-2) and
 8823: 1.6 (21164A)) between @code{gforth} and @code{gforth-fast}.  Given an
 8824: exception caused by a primitive in @code{gforth-fast}, you will
 8825: typically see no return stack dump at all; however, if the exception is
 8826: caught by @code{catch} (e.g., for restoring some state), and then
 8827: @code{throw}n again, the return stack dump will be for the first such
 8828: @code{throw}.
 8829: 
 8830: @c ******************************************************************
 8831: @node Tools, ANS conformance, Error messages, Top
 8832: @chapter Tools
 8833: 
 8834: @menu
 8835: * ANS Report::                  Report the words used, sorted by wordset.
 8836: @end menu
 8837: 
 8838: See also @ref{Emacs and Gforth}.
 8839: 
 8840: @node ANS Report,  , Tools, Tools
 8841: @section @file{ans-report.fs}: Report the words used, sorted by wordset
 8842: @cindex @file{ans-report.fs}
 8843: @cindex report the words used in your program
 8844: @cindex words used in your program
 8845: 
 8846: If you want to label a Forth program as ANS Forth Program, you must
 8847: document which wordsets the program uses; for extension wordsets, it is
 8848: helpful to list the words the program requires from these wordsets
 8849: (because Forth systems are allowed to provide only some words of them).
 8850: 
 8851: The @file{ans-report.fs} tool makes it easy for you to determine which
 8852: words from which wordset and which non-ANS words your application
 8853: uses. You simply have to include @file{ans-report.fs} before loading the
 8854: program you want to check. After loading your program, you can get the
 8855: report with @code{print-ans-report}. A typical use is to run this as
 8856: batch job like this:
 8857: @example
 8858: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
 8859: @end example
 8860: 
 8861: The output looks like this (for @file{compat/control.fs}):
 8862: @example
 8863: The program uses the following words
 8864: from CORE :
 8865: : POSTPONE THEN ; immediate ?dup IF 0= 
 8866: from BLOCK-EXT :
 8867: \ 
 8868: from FILE :
 8869: ( 
 8870: @end example
 8871: 
 8872: @subsection Caveats
 8873: 
 8874: Note that @file{ans-report.fs} just checks which words are used, not whether
 8875: they are used in an ANS Forth conforming way!
 8876: 
 8877: Some words are defined in several wordsets in the
 8878: standard. @file{ans-report.fs} reports them for only one of the
 8879: wordsets, and not necessarily the one you expect. It depends on usage
 8880: which wordset is the right one to specify. E.g., if you only use the
 8881: compilation semantics of @code{S"}, it is a Core word; if you also use
 8882: its interpretation semantics, it is a File word.
 8883: 
 8884: @c ******************************************************************
 8885: @node ANS conformance, Model, Tools, Top
 8886: @chapter ANS conformance
 8887: @cindex ANS conformance of Gforth
 8888: 
 8889: To the best of our knowledge, Gforth is an
 8890: 
 8891: ANS Forth System
 8892: @itemize @bullet
 8893: @item providing the Core Extensions word set
 8894: @item providing the Block word set
 8895: @item providing the Block Extensions word set
 8896: @item providing the Double-Number word set
 8897: @item providing the Double-Number Extensions word set
 8898: @item providing the Exception word set
 8899: @item providing the Exception Extensions word set
 8900: @item providing the Facility word set
 8901: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
 8902: @item providing the File Access word set
 8903: @item providing the File Access Extensions word set
 8904: @item providing the Floating-Point word set
 8905: @item providing the Floating-Point Extensions word set
 8906: @item providing the Locals word set
 8907: @item providing the Locals Extensions word set
 8908: @item providing the Memory-Allocation word set
 8909: @item providing the Memory-Allocation Extensions word set (that one's easy)
 8910: @item providing the Programming-Tools word set
 8911: @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
 8912: @item providing the Search-Order word set
 8913: @item providing the Search-Order Extensions word set
 8914: @item providing the String word set
 8915: @item providing the String Extensions word set (another easy one)
 8916: @end itemize
 8917: 
 8918: @cindex system documentation
 8919: In addition, ANS Forth systems are required to document certain
 8920: implementation choices. This chapter tries to meet these
 8921: requirements. In many cases it gives a way to ask the system for the
 8922: information instead of providing the information directly, in
 8923: particular, if the information depends on the processor, the operating
 8924: system or the installation options chosen, or if they are likely to
 8925: change during the maintenance of Gforth.
 8926: 
 8927: @comment The framework for the rest has been taken from pfe.
 8928: 
 8929: @menu
 8930: * The Core Words::              
 8931: * The optional Block word set::  
 8932: * The optional Double Number word set::  
 8933: * The optional Exception word set::  
 8934: * The optional Facility word set::  
 8935: * The optional File-Access word set::  
 8936: * The optional Floating-Point word set::  
 8937: * The optional Locals word set::  
 8938: * The optional Memory-Allocation word set::  
 8939: * The optional Programming-Tools word set::  
 8940: * The optional Search-Order word set::  
 8941: @end menu
 8942: 
 8943: 
 8944: @c =====================================================================
 8945: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
 8946: @comment  node-name,  next,  previous,  up
 8947: @section The Core Words
 8948: @c =====================================================================
 8949: @cindex core words, system documentation
 8950: @cindex system documentation, core words
 8951: 
 8952: @menu
 8953: * core-idef::                   Implementation Defined Options                   
 8954: * core-ambcond::                Ambiguous Conditions                
 8955: * core-other::                  Other System Documentation                  
 8956: @end menu
 8957: 
 8958: @c ---------------------------------------------------------------------
 8959: @node core-idef, core-ambcond, The Core Words, The Core Words
 8960: @subsection Implementation Defined Options
 8961: @c ---------------------------------------------------------------------
 8962: @cindex core words, implementation-defined options
 8963: @cindex implementation-defined options, core words
 8964: 
 8965: 
 8966: @table @i
 8967: @item (Cell) aligned addresses:
 8968: @cindex cell-aligned addresses
 8969: @cindex aligned addresses
 8970: processor-dependent. Gforth's alignment words perform natural alignment
 8971: (e.g., an address aligned for a datum of size 8 is divisible by
 8972: 8). Unaligned accesses usually result in a @code{-23 THROW}.
 8973: 
 8974: @item @code{EMIT} and non-graphic characters:
 8975: @cindex @code{EMIT} and non-graphic characters
 8976: @cindex non-graphic characters and @code{EMIT}
 8977: The character is output using the C library function (actually, macro)
 8978: @code{putc}.
 8979: 
 8980: @item character editing of @code{ACCEPT} and @code{EXPECT}:
 8981: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
 8982: @cindex editing in @code{ACCEPT} and @code{EXPECT}
 8983: @cindex @code{ACCEPT}, editing
 8984: @cindex @code{EXPECT}, editing
 8985: This is modeled on the GNU readline library (@pxref{Readline
 8986: Interaction, , Command Line Editing, readline, The GNU Readline
 8987: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
 8988: producing a full word completion every time you type it (instead of
 8989: producing the common prefix of all completions). @xref{Command-line editing}.
 8990: 
 8991: @item character set:
 8992: @cindex character set
 8993: The character set of your computer and display device. Gforth is
 8994: 8-bit-clean (but some other component in your system may make trouble).
 8995: 
 8996: @item Character-aligned address requirements:
 8997: @cindex character-aligned address requirements
 8998: installation-dependent. Currently a character is represented by a C
 8999: @code{unsigned char}; in the future we might switch to @code{wchar_t}
 9000: (Comments on that requested).
 9001: 
 9002: @item character-set extensions and matching of names:
 9003: @cindex character-set extensions and matching of names
 9004: @cindex case-sensitivity for name lookup
 9005: @cindex name lookup, case-sensitivity
 9006: @cindex locale and case-sensitivity
 9007: Any character except the ASCII NUL character can be used in a
 9008: name. Matching is case-insensitive (except in @code{TABLE}s). The
 9009: matching is performed using the C function @code{strncasecmp}, whose
 9010: function is probably influenced by the locale. E.g., the @code{C} locale
 9011: does not know about accents and umlauts, so they are matched
 9012: case-sensitively in that locale. For portability reasons it is best to
 9013: write programs such that they work in the @code{C} locale. Then one can
 9014: use libraries written by a Polish programmer (who might use words
 9015: containing ISO Latin-2 encoded characters) and by a French programmer
 9016: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
 9017: funny results for some of the words (which ones, depends on the font you
 9018: are using)). Also, the locale you prefer may not be available in other
 9019: operating systems. Hopefully, Unicode will solve these problems one day.
 9020: 
 9021: @item conditions under which control characters match a space delimiter:
 9022: @cindex space delimiters
 9023: @cindex control characters as delimiters
 9024: If @code{WORD} is called with the space character as a delimiter, all
 9025: white-space characters (as identified by the C macro @code{isspace()})
 9026: are delimiters. @code{PARSE}, on the other hand, treats space like other
 9027: delimiters. @code{PARSE-WORD} treats space like @code{WORD}, but behaves
 9028: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
 9029: interpreter (aka text interpreter) by default, treats all white-space
 9030: characters as delimiters.
 9031: 
 9032: @item format of the control-flow stack:
 9033: @cindex control-flow stack, format
 9034: The data stack is used as control-flow stack. The size of a control-flow
 9035: stack item in cells is given by the constant @code{cs-item-size}. At the
 9036: time of this writing, an item consists of a (pointer to a) locals list
 9037: (third), an address in the code (second), and a tag for identifying the
 9038: item (TOS). The following tags are used: @code{defstart},
 9039: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
 9040: @code{scopestart}.
 9041: 
 9042: @item conversion of digits > 35
 9043: @cindex digits > 35
 9044: The characters @code{[\]^_'} are the digits with the decimal value
 9045: 36@minus{}41. There is no way to input many of the larger digits.
 9046: 
 9047: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
 9048: @cindex @code{EXPECT}, display after end of input
 9049: @cindex @code{ACCEPT}, display after end of input
 9050: The cursor is moved to the end of the entered string. If the input is
 9051: terminated using the @kbd{Return} key, a space is typed.
 9052: 
 9053: @item exception abort sequence of @code{ABORT"}:
 9054: @cindex exception abort sequence of @code{ABORT"}
 9055: @cindex @code{ABORT"}, exception abort sequence
 9056: The error string is stored into the variable @code{"error} and a
 9057: @code{-2 throw} is performed.
 9058: 
 9059: @item input line terminator:
 9060: @cindex input line terminator
 9061: @cindex line terminator on input
 9062: @cindex newline character on input
 9063: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
 9064: lines. One of these characters is typically produced when you type the
 9065: @kbd{Enter} or @kbd{Return} key.
 9066: 
 9067: @item maximum size of a counted string:
 9068: @cindex maximum size of a counted string
 9069: @cindex counted string, maximum size
 9070: @code{s" /counted-string" environment? drop .}. Currently 255 characters
 9071: on all ports, but this may change.
 9072: 
 9073: @item maximum size of a parsed string:
 9074: @cindex maximum size of a parsed string
 9075: @cindex parsed string, maximum size
 9076: Given by the constant @code{/line}. Currently 255 characters.
 9077: 
 9078: @item maximum size of a definition name, in characters:
 9079: @cindex maximum size of a definition name, in characters
 9080: @cindex name, maximum length
 9081: 31
 9082: 
 9083: @item maximum string length for @code{ENVIRONMENT?}, in characters:
 9084: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
 9085: @cindex @code{ENVIRONMENT?} string length, maximum
 9086: 31
 9087: 
 9088: @item method of selecting the user input device:
 9089: @cindex user input device, method of selecting
 9090: The user input device is the standard input. There is currently no way to
 9091: change it from within Gforth. However, the input can typically be
 9092: redirected in the command line that starts Gforth.
 9093: 
 9094: @item method of selecting the user output device:
 9095: @cindex user output device, method of selecting
 9096: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
 9097: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
 9098: output when the user output device is a terminal, otherwise the output
 9099: is buffered.
 9100: 
 9101: @item methods of dictionary compilation:
 9102: What are we expected to document here?
 9103: 
 9104: @item number of bits in one address unit:
 9105: @cindex number of bits in one address unit
 9106: @cindex address unit, size in bits
 9107: @code{s" address-units-bits" environment? drop .}. 8 in all current
 9108: ports.
 9109: 
 9110: @item number representation and arithmetic:
 9111: @cindex number representation and arithmetic
 9112: Processor-dependent. Binary two's complement on all current ports.
 9113: 
 9114: @item ranges for integer types:
 9115: @cindex ranges for integer types
 9116: @cindex integer types, ranges
 9117: Installation-dependent. Make environmental queries for @code{MAX-N},
 9118: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
 9119: unsigned (and positive) types is 0. The lower bound for signed types on
 9120: two's complement and one's complement machines machines can be computed
 9121: by adding 1 to the upper bound.
 9122: 
 9123: @item read-only data space regions:
 9124: @cindex read-only data space regions
 9125: @cindex data-space, read-only regions
 9126: The whole Forth data space is writable.
 9127: 
 9128: @item size of buffer at @code{WORD}:
 9129: @cindex size of buffer at @code{WORD}
 9130: @cindex @code{WORD} buffer size
 9131: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
 9132: shared with the pictured numeric output string. If overwriting
 9133: @code{PAD} is acceptable, it is as large as the remaining dictionary
 9134: space, although only as much can be sensibly used as fits in a counted
 9135: string.
 9136: 
 9137: @item size of one cell in address units:
 9138: @cindex cell size
 9139: @code{1 cells .}.
 9140: 
 9141: @item size of one character in address units:
 9142: @cindex char size
 9143: @code{1 chars .}. 1 on all current ports.
 9144: 
 9145: @item size of the keyboard terminal buffer:
 9146: @cindex size of the keyboard terminal buffer
 9147: @cindex terminal buffer, size
 9148: Varies. You can determine the size at a specific time using @code{lp@@
 9149: tib - .}. It is shared with the locals stack and TIBs of files that
 9150: include the current file. You can change the amount of space for TIBs
 9151: and locals stack at Gforth startup with the command line option
 9152: @code{-l}.
 9153: 
 9154: @item size of the pictured numeric output buffer:
 9155: @cindex size of the pictured numeric output buffer
 9156: @cindex pictured numeric output buffer, size
 9157: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
 9158: shared with @code{WORD}.
 9159: 
 9160: @item size of the scratch area returned by @code{PAD}:
 9161: @cindex size of the scratch area returned by @code{PAD}
 9162: @cindex @code{PAD} size
 9163: The remainder of dictionary space. @code{unused pad here - - .}.
 9164: 
 9165: @item system case-sensitivity characteristics:
 9166: @cindex case-sensitivity characteristics
 9167: Dictionary searches are case-insensitive (except in
 9168: @code{TABLE}s). However, as explained above under @i{character-set
 9169: extensions}, the matching for non-ASCII characters is determined by the
 9170: locale you are using. In the default @code{C} locale all non-ASCII
 9171: characters are matched case-sensitively.
 9172: 
 9173: @item system prompt:
 9174: @cindex system prompt
 9175: @cindex prompt
 9176: @code{ ok} in interpret state, @code{ compiled} in compile state.
 9177: 
 9178: @item division rounding:
 9179: @cindex division rounding
 9180: installation dependent. @code{s" floored" environment? drop .}. We leave
 9181: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
 9182: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
 9183: 
 9184: @item values of @code{STATE} when true:
 9185: @cindex @code{STATE} values
 9186: -1.
 9187: 
 9188: @item values returned after arithmetic overflow:
 9189: On two's complement machines, arithmetic is performed modulo
 9190: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
 9191: arithmetic (with appropriate mapping for signed types). Division by zero
 9192: typically results in a @code{-55 throw} (Floating-point unidentified
 9193: fault), although a @code{-10 throw} (divide by zero) would be more
 9194: appropriate.
 9195: 
 9196: @item whether the current definition can be found after @t{DOES>}:
 9197: @cindex @t{DOES>}, visibility of current definition
 9198: No.
 9199: 
 9200: @end table
 9201: 
 9202: @c ---------------------------------------------------------------------
 9203: @node core-ambcond, core-other, core-idef, The Core Words
 9204: @subsection Ambiguous conditions
 9205: @c ---------------------------------------------------------------------
 9206: @cindex core words, ambiguous conditions
 9207: @cindex ambiguous conditions, core words
 9208: 
 9209: @table @i
 9210: 
 9211: @item a name is neither a word nor a number:
 9212: @cindex name not found
 9213: @cindex undefined word
 9214: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
 9215: preserves the data and FP stack, so you don't lose more work than
 9216: necessary.
 9217: 
 9218: @item a definition name exceeds the maximum length allowed:
 9219: @cindex word name too long
 9220: @code{-19 throw} (Word name too long)
 9221: 
 9222: @item addressing a region not inside the various data spaces of the forth system:
 9223: @cindex Invalid memory address
 9224: The stacks, code space and header space are accessible. Machine code space is
 9225: typically readable. Accessing other addresses gives results dependent on
 9226: the operating system. On decent systems: @code{-9 throw} (Invalid memory
 9227: address).
 9228: 
 9229: @item argument type incompatible with parameter:
 9230: @cindex argument type mismatch
 9231: This is usually not caught. Some words perform checks, e.g., the control
 9232: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
 9233: mismatch).
 9234: 
 9235: @item attempting to obtain the execution token of a word with undefined execution semantics:
 9236: @cindex Interpreting a compile-only word, for @code{'} etc.
 9237: @cindex execution token of words with undefined execution semantics
 9238: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
 9239: get an execution token for @code{compile-only-error} (which performs a
 9240: @code{-14 throw} when executed).
 9241: 
 9242: @item dividing by zero:
 9243: @cindex dividing by zero
 9244: @cindex floating point unidentified fault, integer division
 9245: On better platforms, this produces a @code{-10 throw} (Division by
 9246: zero); on other systems, this typically results in a @code{-55 throw}
 9247: (Floating-point unidentified fault).
 9248: 
 9249: @item insufficient data stack or return stack space:
 9250: @cindex insufficient data stack or return stack space
 9251: @cindex stack overflow
 9252: @cindex address alignment exception, stack overflow
 9253: @cindex Invalid memory address, stack overflow
 9254: Depending on the operating system, the installation, and the invocation
 9255: of Gforth, this is either checked by the memory management hardware, or
 9256: it is not checked. If it is checked, you typically get a @code{-3 throw}
 9257: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
 9258: throw} (Invalid memory address) (depending on the platform and how you
 9259: achieved the overflow) as soon as the overflow happens. If it is not
 9260: checked, overflows typically result in mysterious illegal memory
 9261: accesses, producing @code{-9 throw} (Invalid memory address) or
 9262: @code{-23 throw} (Address alignment exception); they might also destroy
 9263: the internal data structure of @code{ALLOCATE} and friends, resulting in
 9264: various errors in these words.
 9265: 
 9266: @item insufficient space for loop control parameters:
 9267: @cindex insufficient space for loop control parameters
 9268: like other return stack overflows.
 9269: 
 9270: @item insufficient space in the dictionary:
 9271: @cindex insufficient space in the dictionary
 9272: @cindex dictionary overflow
 9273: If you try to allot (either directly with @code{allot}, or indirectly
 9274: with @code{,}, @code{create} etc.) more memory than available in the
 9275: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
 9276: to access memory beyond the end of the dictionary, the results are
 9277: similar to stack overflows.
 9278: 
 9279: @item interpreting a word with undefined interpretation semantics:
 9280: @cindex interpreting a word with undefined interpretation semantics
 9281: @cindex Interpreting a compile-only word
 9282: For some words, we have defined interpretation semantics. For the
 9283: others: @code{-14 throw} (Interpreting a compile-only word).
 9284: 
 9285: @item modifying the contents of the input buffer or a string literal:
 9286: @cindex modifying the contents of the input buffer or a string literal
 9287: These are located in writable memory and can be modified.
 9288: 
 9289: @item overflow of the pictured numeric output string:
 9290: @cindex overflow of the pictured numeric output string
 9291: @cindex pictured numeric output string, overflow
 9292: @code{-17 throw} (Pictured numeric ouput string overflow).
 9293: 
 9294: @item parsed string overflow:
 9295: @cindex parsed string overflow
 9296: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
 9297: 
 9298: @item producing a result out of range:
 9299: @cindex result out of range
 9300: On two's complement machines, arithmetic is performed modulo
 9301: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
 9302: arithmetic (with appropriate mapping for signed types). Division by zero
 9303: typically results in a @code{-10 throw} (divide by zero) or @code{-55
 9304: throw} (floating point unidentified fault). @code{convert} and
 9305: @code{>number} currently overflow silently.
 9306: 
 9307: @item reading from an empty data or return stack:
 9308: @cindex stack empty
 9309: @cindex stack underflow
 9310: @cindex return stack underflow
 9311: The data stack is checked by the outer (aka text) interpreter after
 9312: every word executed. If it has underflowed, a @code{-4 throw} (Stack
 9313: underflow) is performed. Apart from that, stacks may be checked or not,
 9314: depending on operating system, installation, and invocation. If they are
 9315: caught by a check, they typically result in @code{-4 throw} (Stack
 9316: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
 9317: (Invalid memory address), depending on the platform and which stack
 9318: underflows and by how much. Note that even if the system uses checking
 9319: (through the MMU), your program may have to underflow by a significant
 9320: number of stack items to trigger the reaction (the reason for this is
 9321: that the MMU, and therefore the checking, works with a page-size
 9322: granularity).  If there is no checking, the symptoms resulting from an
 9323: underflow are similar to those from an overflow.  Unbalanced return
 9324: stack errors result in a variaty of symptoms, including @code{-9 throw}
 9325: (Invalid memory address) and Illegal Instruction (typically @code{-260
 9326: throw}).
 9327: 
 9328: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
 9329: @cindex unexpected end of the input buffer
 9330: @cindex zero-length string as a name
 9331: @cindex Attempt to use zero-length string as a name
 9332: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
 9333: use zero-length string as a name). Words like @code{'} probably will not
 9334: find what they search. Note that it is possible to create zero-length
 9335: names with @code{nextname} (should it not?).
 9336: 
 9337: @item @code{>IN} greater than input buffer:
 9338: @cindex @code{>IN} greater than input buffer
 9339: The next invocation of a parsing word returns a string with length 0.
 9340: 
 9341: @item @code{RECURSE} appears after @code{DOES>}:
 9342: @cindex @code{RECURSE} appears after @code{DOES>}
 9343: Compiles a recursive call to the defining word, not to the defined word.
 9344: 
 9345: @item argument input source different than current input source for @code{RESTORE-INPUT}:
 9346: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
 9347: @cindex argument type mismatch, @code{RESTORE-INPUT}
 9348: @cindex @code{RESTORE-INPUT}, Argument type mismatch
 9349: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
 9350: the end of the file was reached), its source-id may be
 9351: reused. Therefore, restoring an input source specification referencing a
 9352: closed file may lead to unpredictable results instead of a @code{-12
 9353: THROW}.
 9354: 
 9355: In the future, Gforth may be able to restore input source specifications
 9356: from other than the current input source.
 9357: 
 9358: @item data space containing definitions gets de-allocated:
 9359: @cindex data space containing definitions gets de-allocated
 9360: Deallocation with @code{allot} is not checked. This typically results in
 9361: memory access faults or execution of illegal instructions.
 9362: 
 9363: @item data space read/write with incorrect alignment:
 9364: @cindex data space read/write with incorrect alignment
 9365: @cindex alignment faults
 9366: @cindex address alignment exception
 9367: Processor-dependent. Typically results in a @code{-23 throw} (Address
 9368: alignment exception). Under Linux-Intel on a 486 or later processor with
 9369: alignment turned on, incorrect alignment results in a @code{-9 throw}
 9370: (Invalid memory address). There are reportedly some processors with
 9371: alignment restrictions that do not report violations.
 9372: 
 9373: @item data space pointer not properly aligned, @code{,}, @code{C,}:
 9374: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
 9375: Like other alignment errors.
 9376: 
 9377: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
 9378: Like other stack underflows.
 9379: 
 9380: @item loop control parameters not available:
 9381: @cindex loop control parameters not available
 9382: Not checked. The counted loop words simply assume that the top of return
 9383: stack items are loop control parameters and behave accordingly.
 9384: 
 9385: @item most recent definition does not have a name (@code{IMMEDIATE}):
 9386: @cindex most recent definition does not have a name (@code{IMMEDIATE})
 9387: @cindex last word was headerless
 9388: @code{abort" last word was headerless"}.
 9389: 
 9390: @item name not defined by @code{VALUE} used by @code{TO}:
 9391: @cindex name not defined by @code{VALUE} used by @code{TO}
 9392: @cindex @code{TO} on non-@code{VALUE}s
 9393: @cindex Invalid name argument, @code{TO}
 9394: @code{-32 throw} (Invalid name argument) (unless name is a local or was
 9395: defined by @code{CONSTANT}; in the latter case it just changes the constant).
 9396: 
 9397: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
 9398: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
 9399: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
 9400: @code{-13 throw} (Undefined word)
 9401: 
 9402: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
 9403: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
 9404: Gforth behaves as if they were of the same type. I.e., you can predict
 9405: the behaviour by interpreting all parameters as, e.g., signed.
 9406: 
 9407: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
 9408: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
 9409: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
 9410: compilation semantics of @code{TO}.
 9411: 
 9412: @item String longer than a counted string returned by @code{WORD}:
 9413: @cindex string longer than a counted string returned by @code{WORD}
 9414: @cindex @code{WORD}, string overflow
 9415: Not checked. The string will be ok, but the count will, of course,
 9416: contain only the least significant bits of the length.
 9417: 
 9418: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
 9419: @cindex @code{LSHIFT}, large shift counts
 9420: @cindex @code{RSHIFT}, large shift counts
 9421: Processor-dependent. Typical behaviours are returning 0 and using only
 9422: the low bits of the shift count.
 9423: 
 9424: @item word not defined via @code{CREATE}:
 9425: @cindex @code{>BODY} of non-@code{CREATE}d words
 9426: @code{>BODY} produces the PFA of the word no matter how it was defined.
 9427: 
 9428: @cindex @code{DOES>} of non-@code{CREATE}d words
 9429: @code{DOES>} changes the execution semantics of the last defined word no
 9430: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
 9431: @code{CREATE , DOES>}.
 9432: 
 9433: @item words improperly used outside @code{<#} and @code{#>}:
 9434: Not checked. As usual, you can expect memory faults.
 9435: 
 9436: @end table
 9437: 
 9438: 
 9439: @c ---------------------------------------------------------------------
 9440: @node core-other,  , core-ambcond, The Core Words
 9441: @subsection Other system documentation
 9442: @c ---------------------------------------------------------------------
 9443: @cindex other system documentation, core words
 9444: @cindex core words, other system documentation
 9445: 
 9446: @table @i
 9447: @item nonstandard words using @code{PAD}:
 9448: @cindex @code{PAD} use by nonstandard words
 9449: None.
 9450: 
 9451: @item operator's terminal facilities available:
 9452: @cindex operator's terminal facilities available
 9453: After processing the command line, Gforth goes into interactive mode,
 9454: and you can give commands to Gforth interactively. The actual facilities
 9455: available depend on how you invoke Gforth.
 9456: 
 9457: @item program data space available:
 9458: @cindex program data space available
 9459: @cindex data space available
 9460: @code{UNUSED .} gives the remaining dictionary space. The total
 9461: dictionary space can be specified with the @code{-m} switch
 9462: (@pxref{Invoking Gforth}) when Gforth starts up.
 9463: 
 9464: @item return stack space available:
 9465: @cindex return stack space available
 9466: You can compute the total return stack space in cells with
 9467: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
 9468: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
 9469: 
 9470: @item stack space available:
 9471: @cindex stack space available
 9472: You can compute the total data stack space in cells with
 9473: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
 9474: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
 9475: 
 9476: @item system dictionary space required, in address units:
 9477: @cindex system dictionary space required, in address units
 9478: Type @code{here forthstart - .} after startup. At the time of this
 9479: writing, this gives 80080 (bytes) on a 32-bit system.
 9480: @end table
 9481: 
 9482: 
 9483: @c =====================================================================
 9484: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
 9485: @section The optional Block word set
 9486: @c =====================================================================
 9487: @cindex system documentation, block words
 9488: @cindex block words, system documentation
 9489: 
 9490: @menu
 9491: * block-idef::                  Implementation Defined Options
 9492: * block-ambcond::               Ambiguous Conditions               
 9493: * block-other::                 Other System Documentation                 
 9494: @end menu
 9495: 
 9496: 
 9497: @c ---------------------------------------------------------------------
 9498: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
 9499: @subsection Implementation Defined Options
 9500: @c ---------------------------------------------------------------------
 9501: @cindex implementation-defined options, block words
 9502: @cindex block words, implementation-defined options
 9503: 
 9504: @table @i
 9505: @item the format for display by @code{LIST}:
 9506: @cindex @code{LIST} display format
 9507: First the screen number is displayed, then 16 lines of 64 characters,
 9508: each line preceded by the line number.
 9509: 
 9510: @item the length of a line affected by @code{\}:
 9511: @cindex length of a line affected by @code{\}
 9512: @cindex @code{\}, line length in blocks
 9513: 64 characters.
 9514: @end table
 9515: 
 9516: 
 9517: @c ---------------------------------------------------------------------
 9518: @node block-ambcond, block-other, block-idef, The optional Block word set
 9519: @subsection Ambiguous conditions
 9520: @c ---------------------------------------------------------------------
 9521: @cindex block words, ambiguous conditions
 9522: @cindex ambiguous conditions, block words
 9523: 
 9524: @table @i
 9525: @item correct block read was not possible:
 9526: @cindex block read not possible
 9527: Typically results in a @code{throw} of some OS-derived value (between
 9528: -512 and -2048). If the blocks file was just not long enough, blanks are
 9529: supplied for the missing portion.
 9530: 
 9531: @item I/O exception in block transfer:
 9532: @cindex I/O exception in block transfer
 9533: @cindex block transfer, I/O exception
 9534: Typically results in a @code{throw} of some OS-derived value (between
 9535: -512 and -2048).
 9536: 
 9537: @item invalid block number:
 9538: @cindex invalid block number
 9539: @cindex block number invalid
 9540: @code{-35 throw} (Invalid block number)
 9541: 
 9542: @item a program directly alters the contents of @code{BLK}:
 9543: @cindex @code{BLK}, altering @code{BLK}
 9544: The input stream is switched to that other block, at the same
 9545: position. If the storing to @code{BLK} happens when interpreting
 9546: non-block input, the system will get quite confused when the block ends.
 9547: 
 9548: @item no current block buffer for @code{UPDATE}:
 9549: @cindex @code{UPDATE}, no current block buffer
 9550: @code{UPDATE} has no effect.
 9551: 
 9552: @end table
 9553: 
 9554: @c ---------------------------------------------------------------------
 9555: @node block-other,  , block-ambcond, The optional Block word set
 9556: @subsection Other system documentation
 9557: @c ---------------------------------------------------------------------
 9558: @cindex other system documentation, block words
 9559: @cindex block words, other system documentation
 9560: 
 9561: @table @i
 9562: @item any restrictions a multiprogramming system places on the use of buffer addresses:
 9563: No restrictions (yet).
 9564: 
 9565: @item the number of blocks available for source and data:
 9566: depends on your disk space.
 9567: 
 9568: @end table
 9569: 
 9570: 
 9571: @c =====================================================================
 9572: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
 9573: @section The optional Double Number word set
 9574: @c =====================================================================
 9575: @cindex system documentation, double words
 9576: @cindex double words, system documentation
 9577: 
 9578: @menu
 9579: * double-ambcond::              Ambiguous Conditions              
 9580: @end menu
 9581: 
 9582: 
 9583: @c ---------------------------------------------------------------------
 9584: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
 9585: @subsection Ambiguous conditions
 9586: @c ---------------------------------------------------------------------
 9587: @cindex double words, ambiguous conditions
 9588: @cindex ambiguous conditions, double words
 9589: 
 9590: @table @i
 9591: @item @i{d} outside of range of @i{n} in @code{D>S}:
 9592: @cindex @code{D>S}, @i{d} out of range of @i{n} 
 9593: The least significant cell of @i{d} is produced.
 9594: 
 9595: @end table
 9596: 
 9597: 
 9598: @c =====================================================================
 9599: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
 9600: @section The optional Exception word set
 9601: @c =====================================================================
 9602: @cindex system documentation, exception words
 9603: @cindex exception words, system documentation
 9604: 
 9605: @menu
 9606: * exception-idef::              Implementation Defined Options              
 9607: @end menu
 9608: 
 9609: 
 9610: @c ---------------------------------------------------------------------
 9611: @node exception-idef,  , The optional Exception word set, The optional Exception word set
 9612: @subsection Implementation Defined Options
 9613: @c ---------------------------------------------------------------------
 9614: @cindex implementation-defined options, exception words
 9615: @cindex exception words, implementation-defined options
 9616: 
 9617: @table @i
 9618: @item @code{THROW}-codes used in the system:
 9619: @cindex @code{THROW}-codes used in the system
 9620: The codes -256@minus{}-511 are used for reporting signals. The mapping
 9621: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
 9622: codes -512@minus{}-2047 are used for OS errors (for file and memory
 9623: allocation operations). The mapping from OS error numbers to throw codes
 9624: is -512@minus{}@code{errno}. One side effect of this mapping is that
 9625: undefined OS errors produce a message with a strange number; e.g.,
 9626: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
 9627: @end table
 9628: 
 9629: @c =====================================================================
 9630: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
 9631: @section The optional Facility word set
 9632: @c =====================================================================
 9633: @cindex system documentation, facility words
 9634: @cindex facility words, system documentation
 9635: 
 9636: @menu
 9637: * facility-idef::               Implementation Defined Options               
 9638: * facility-ambcond::            Ambiguous Conditions            
 9639: @end menu
 9640: 
 9641: 
 9642: @c ---------------------------------------------------------------------
 9643: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
 9644: @subsection Implementation Defined Options
 9645: @c ---------------------------------------------------------------------
 9646: @cindex implementation-defined options, facility words
 9647: @cindex facility words, implementation-defined options
 9648: 
 9649: @table @i
 9650: @item encoding of keyboard events (@code{EKEY}):
 9651: @cindex keyboard events, encoding in @code{EKEY}
 9652: @cindex @code{EKEY}, encoding of keyboard events
 9653: Keys corresponding to ASCII characters are encoded as ASCII characters.
 9654: Other keys are encoded with the constants \code{k-left}, \code{k-right},
 9655: \code{k-up}, \code{k-down}, \code{k-home}, \code{k-end}, \code{k1},
 9656: \code{k2}, \code{k3}, \code{k4}, \code{k5}, \code{k6}, \code{k7},
 9657: \code{k8}, \code{k9}, \code{k10}, \code{k11}, \code{k12}.
 9658: 
 9659: 
 9660: @item duration of a system clock tick:
 9661: @cindex duration of a system clock tick
 9662: @cindex clock tick duration
 9663: System dependent. With respect to @code{MS}, the time is specified in
 9664: microseconds. How well the OS and the hardware implement this, is
 9665: another question.
 9666: 
 9667: @item repeatability to be expected from the execution of @code{MS}:
 9668: @cindex repeatability to be expected from the execution of @code{MS}
 9669: @cindex @code{MS}, repeatability to be expected
 9670: System dependent. On Unix, a lot depends on load. If the system is
 9671: lightly loaded, and the delay is short enough that Gforth does not get
 9672: swapped out, the performance should be acceptable. Under MS-DOS and
 9673: other single-tasking systems, it should be good.
 9674: 
 9675: @end table
 9676: 
 9677: 
 9678: @c ---------------------------------------------------------------------
 9679: @node facility-ambcond,  , facility-idef, The optional Facility word set
 9680: @subsection Ambiguous conditions
 9681: @c ---------------------------------------------------------------------
 9682: @cindex facility words, ambiguous conditions
 9683: @cindex ambiguous conditions, facility words
 9684: 
 9685: @table @i
 9686: @item @code{AT-XY} can't be performed on user output device:
 9687: @cindex @code{AT-XY} can't be performed on user output device
 9688: Largely terminal dependent. No range checks are done on the arguments.
 9689: No errors are reported. You may see some garbage appearing, you may see
 9690: simply nothing happen.
 9691: 
 9692: @end table
 9693: 
 9694: 
 9695: @c =====================================================================
 9696: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
 9697: @section The optional File-Access word set
 9698: @c =====================================================================
 9699: @cindex system documentation, file words
 9700: @cindex file words, system documentation
 9701: 
 9702: @menu
 9703: * file-idef::                   Implementation Defined Options
 9704: * file-ambcond::                Ambiguous Conditions                
 9705: @end menu
 9706: 
 9707: @c ---------------------------------------------------------------------
 9708: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
 9709: @subsection Implementation Defined Options
 9710: @c ---------------------------------------------------------------------
 9711: @cindex implementation-defined options, file words
 9712: @cindex file words, implementation-defined options
 9713: 
 9714: @table @i
 9715: @item file access methods used:
 9716: @cindex file access methods used
 9717: @code{R/O}, @code{R/W} and @code{BIN} work as you would
 9718: expect. @code{W/O} translates into the C file opening mode @code{w} (or
 9719: @code{wb}): The file is cleared, if it exists, and created, if it does
 9720: not (with both @code{open-file} and @code{create-file}).  Under Unix
 9721: @code{create-file} creates a file with 666 permissions modified by your
 9722: umask.
 9723: 
 9724: @item file exceptions:
 9725: @cindex file exceptions
 9726: The file words do not raise exceptions (except, perhaps, memory access
 9727: faults when you pass illegal addresses or file-ids).
 9728: 
 9729: @item file line terminator:
 9730: @cindex file line terminator
 9731: System-dependent. Gforth uses C's newline character as line
 9732: terminator. What the actual character code(s) of this are is
 9733: system-dependent.
 9734: 
 9735: @item file name format:
 9736: @cindex file name format
 9737: System dependent. Gforth just uses the file name format of your OS.
 9738: 
 9739: @item information returned by @code{FILE-STATUS}:
 9740: @cindex @code{FILE-STATUS}, returned information
 9741: @code{FILE-STATUS} returns the most powerful file access mode allowed
 9742: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
 9743: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
 9744: along with the returned mode.
 9745: 
 9746: @item input file state after an exception when including source:
 9747: @cindex exception when including source
 9748: All files that are left via the exception are closed.
 9749: 
 9750: @item @i{ior} values and meaning:
 9751: @cindex @i{ior} values and meaning
 9752: The @i{ior}s returned by the file and memory allocation words are
 9753: intended as throw codes. They typically are in the range
 9754: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
 9755: @i{ior}s is -512@minus{}@i{errno}.
 9756: 
 9757: @item maximum depth of file input nesting:
 9758: @cindex maximum depth of file input nesting
 9759: @cindex file input nesting, maximum depth
 9760: limited by the amount of return stack, locals/TIB stack, and the number
 9761: of open files available. This should not give you troubles.
 9762: 
 9763: @item maximum size of input line:
 9764: @cindex maximum size of input line
 9765: @cindex input line size, maximum
 9766: @code{/line}. Currently 255.
 9767: 
 9768: @item methods of mapping block ranges to files:
 9769: @cindex mapping block ranges to files
 9770: @cindex files containing blocks
 9771: @cindex blocks in files
 9772: By default, blocks are accessed in the file @file{blocks.fb} in the
 9773: current working directory. The file can be switched with @code{USE}.
 9774: 
 9775: @item number of string buffers provided by @code{S"}:
 9776: @cindex @code{S"}, number of string buffers
 9777: 1
 9778: 
 9779: @item size of string buffer used by @code{S"}:
 9780: @cindex @code{S"}, size of string buffer
 9781: @code{/line}. currently 255.
 9782: 
 9783: @end table
 9784: 
 9785: @c ---------------------------------------------------------------------
 9786: @node file-ambcond,  , file-idef, The optional File-Access word set
 9787: @subsection Ambiguous conditions
 9788: @c ---------------------------------------------------------------------
 9789: @cindex file words, ambiguous conditions
 9790: @cindex ambiguous conditions, file words
 9791: 
 9792: @table @i
 9793: @item attempting to position a file outside its boundaries:
 9794: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
 9795: @code{REPOSITION-FILE} is performed as usual: Afterwards,
 9796: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
 9797: 
 9798: @item attempting to read from file positions not yet written:
 9799: @cindex reading from file positions not yet written
 9800: End-of-file, i.e., zero characters are read and no error is reported.
 9801: 
 9802: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
 9803: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
 9804: An appropriate exception may be thrown, but a memory fault or other
 9805: problem is more probable.
 9806: 
 9807: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
 9808: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
 9809: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
 9810: The @i{ior} produced by the operation, that discovered the problem, is
 9811: thrown.
 9812: 
 9813: @item named file cannot be opened (@code{INCLUDED}):
 9814: @cindex @code{INCLUDED}, named file cannot be opened
 9815: The @i{ior} produced by @code{open-file} is thrown.
 9816: 
 9817: @item requesting an unmapped block number:
 9818: @cindex unmapped block numbers
 9819: There are no unmapped legal block numbers. On some operating systems,
 9820: writing a block with a large number may overflow the file system and
 9821: have an error message as consequence.
 9822: 
 9823: @item using @code{source-id} when @code{blk} is non-zero:
 9824: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
 9825: @code{source-id} performs its function. Typically it will give the id of
 9826: the source which loaded the block. (Better ideas?)
 9827: 
 9828: @end table
 9829: 
 9830: 
 9831: @c =====================================================================
 9832: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
 9833: @section The optional Floating-Point word set
 9834: @c =====================================================================
 9835: @cindex system documentation, floating-point words
 9836: @cindex floating-point words, system documentation
 9837: 
 9838: @menu
 9839: * floating-idef::               Implementation Defined Options
 9840: * floating-ambcond::            Ambiguous Conditions            
 9841: @end menu
 9842: 
 9843: 
 9844: @c ---------------------------------------------------------------------
 9845: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
 9846: @subsection Implementation Defined Options
 9847: @c ---------------------------------------------------------------------
 9848: @cindex implementation-defined options, floating-point words
 9849: @cindex floating-point words, implementation-defined options
 9850: 
 9851: @table @i
 9852: @item format and range of floating point numbers:
 9853: @cindex format and range of floating point numbers
 9854: @cindex floating point numbers, format and range
 9855: System-dependent; the @code{double} type of C.
 9856: 
 9857: @item results of @code{REPRESENT} when @i{float} is out of range:
 9858: @cindex  @code{REPRESENT}, results when @i{float} is out of range
 9859: System dependent; @code{REPRESENT} is implemented using the C library
 9860: function @code{ecvt()} and inherits its behaviour in this respect.
 9861: 
 9862: @item rounding or truncation of floating-point numbers:
 9863: @cindex rounding of floating-point numbers
 9864: @cindex truncation of floating-point numbers
 9865: @cindex floating-point numbers, rounding or truncation
 9866: System dependent; the rounding behaviour is inherited from the hosting C
 9867: compiler. IEEE-FP-based (i.e., most) systems by default round to
 9868: nearest, and break ties by rounding to even (i.e., such that the last
 9869: bit of the mantissa is 0).
 9870: 
 9871: @item size of floating-point stack:
 9872: @cindex floating-point stack size
 9873: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
 9874: the floating-point stack (in floats). You can specify this on startup
 9875: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
 9876: 
 9877: @item width of floating-point stack:
 9878: @cindex floating-point stack width 
 9879: @code{1 floats}.
 9880: 
 9881: @end table
 9882: 
 9883: 
 9884: @c ---------------------------------------------------------------------
 9885: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
 9886: @subsection Ambiguous conditions
 9887: @c ---------------------------------------------------------------------
 9888: @cindex floating-point words, ambiguous conditions
 9889: @cindex ambiguous conditions, floating-point words
 9890: 
 9891: @table @i
 9892: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
 9893: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
 9894: System-dependent. Typically results in a @code{-23 THROW} like other
 9895: alignment violations.
 9896: 
 9897: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
 9898: @cindex @code{f@@} used with an address that is not float aligned
 9899: @cindex @code{f!} used with an address that is not float aligned
 9900: System-dependent. Typically results in a @code{-23 THROW} like other
 9901: alignment violations.
 9902: 
 9903: @item floating-point result out of range:
 9904: @cindex floating-point result out of range
 9905: System-dependent. Can result in a @code{-55 THROW} (Floating-point
 9906: unidentified fault), or can produce a special value representing, e.g.,
 9907: Infinity.
 9908: 
 9909: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
 9910: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
 9911: System-dependent. Typically results in an alignment fault like other
 9912: alignment violations.
 9913: 
 9914: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
 9915: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
 9916: The floating-point number is converted into decimal nonetheless.
 9917: 
 9918: @item Both arguments are equal to zero (@code{FATAN2}):
 9919: @cindex @code{FATAN2}, both arguments are equal to zero
 9920: System-dependent. @code{FATAN2} is implemented using the C library
 9921: function @code{atan2()}.
 9922: 
 9923: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
 9924: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
 9925: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
 9926: because of small errors and the tan will be a very large (or very small)
 9927: but finite number.
 9928: 
 9929: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
 9930: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
 9931: The result is rounded to the nearest float.
 9932: 
 9933: @item dividing by zero:
 9934: @cindex dividing by zero, floating-point
 9935: @cindex floating-point dividing by zero
 9936: @cindex floating-point unidentified fault, FP divide-by-zero
 9937: @code{-55 throw} (Floating-point unidentified fault)
 9938: 
 9939: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
 9940: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
 9941: System dependent. On IEEE-FP based systems the number is converted into
 9942: an infinity.
 9943: 
 9944: @item @i{float}<1 (@code{FACOSH}):
 9945: @cindex @code{FACOSH}, @i{float}<1
 9946: @cindex floating-point unidentified fault, @code{FACOSH}
 9947: @code{-55 throw} (Floating-point unidentified fault)
 9948: 
 9949: @item @i{float}=<-1 (@code{FLNP1}):
 9950: @cindex @code{FLNP1}, @i{float}=<-1
 9951: @cindex floating-point unidentified fault, @code{FLNP1}
 9952: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
 9953: negative infinity is typically produced for @i{float}=-1.
 9954: 
 9955: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
 9956: @cindex @code{FLN}, @i{float}=<0
 9957: @cindex @code{FLOG}, @i{float}=<0
 9958: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
 9959: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
 9960: negative infinity is typically produced for @i{float}=0.
 9961: 
 9962: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
 9963: @cindex @code{FASINH}, @i{float}<0
 9964: @cindex @code{FSQRT}, @i{float}<0
 9965: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
 9966: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
 9967: produces values for these inputs on my Linux box (Bug in the C library?)
 9968: 
 9969: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
 9970: @cindex @code{FACOS}, |@i{float}|>1
 9971: @cindex @code{FASIN}, |@i{float}|>1
 9972: @cindex @code{FATANH}, |@i{float}|>1
 9973: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
 9974: @code{-55 throw} (Floating-point unidentified fault).
 9975: 
 9976: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
 9977: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
 9978: @cindex floating-point unidentified fault, @code{F>D}
 9979: @code{-55 throw} (Floating-point unidentified fault).
 9980: 
 9981: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
 9982: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
 9983: This does not happen.
 9984: @end table
 9985: 
 9986: @c =====================================================================
 9987: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
 9988: @section The optional Locals word set
 9989: @c =====================================================================
 9990: @cindex system documentation, locals words
 9991: @cindex locals words, system documentation
 9992: 
 9993: @menu
 9994: * locals-idef::                 Implementation Defined Options                 
 9995: * locals-ambcond::              Ambiguous Conditions              
 9996: @end menu
 9997: 
 9998: 
 9999: @c ---------------------------------------------------------------------
10000: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
10001: @subsection Implementation Defined Options
10002: @c ---------------------------------------------------------------------
10003: @cindex implementation-defined options, locals words
10004: @cindex locals words, implementation-defined options
10005: 
10006: @table @i
10007: @item maximum number of locals in a definition:
10008: @cindex maximum number of locals in a definition
10009: @cindex locals, maximum number in a definition
10010: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
10011: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
10012: characters. The number of locals in a definition is bounded by the size
10013: of locals-buffer, which contains the names of the locals.
10014: 
10015: @end table
10016: 
10017: 
10018: @c ---------------------------------------------------------------------
10019: @node locals-ambcond,  , locals-idef, The optional Locals word set
10020: @subsection Ambiguous conditions
10021: @c ---------------------------------------------------------------------
10022: @cindex locals words, ambiguous conditions
10023: @cindex ambiguous conditions, locals words
10024: 
10025: @table @i
10026: @item executing a named local in interpretation state:
10027: @cindex local in interpretation state
10028: @cindex Interpreting a compile-only word, for a local
10029: Locals have no interpretation semantics. If you try to perform the
10030: interpretation semantics, you will get a @code{-14 throw} somewhere
10031: (Interpreting a compile-only word). If you perform the compilation
10032: semantics, the locals access will be compiled (irrespective of state).
10033: 
10034: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
10035: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
10036: @cindex @code{TO} on non-@code{VALUE}s and non-locals
10037: @cindex Invalid name argument, @code{TO}
10038: @code{-32 throw} (Invalid name argument)
10039: 
10040: @end table
10041: 
10042: 
10043: @c =====================================================================
10044: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
10045: @section The optional Memory-Allocation word set
10046: @c =====================================================================
10047: @cindex system documentation, memory-allocation words
10048: @cindex memory-allocation words, system documentation
10049: 
10050: @menu
10051: * memory-idef::                 Implementation Defined Options                 
10052: @end menu
10053: 
10054: 
10055: @c ---------------------------------------------------------------------
10056: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
10057: @subsection Implementation Defined Options
10058: @c ---------------------------------------------------------------------
10059: @cindex implementation-defined options, memory-allocation words
10060: @cindex memory-allocation words, implementation-defined options
10061: 
10062: @table @i
10063: @item values and meaning of @i{ior}:
10064: @cindex  @i{ior} values and meaning
10065: The @i{ior}s returned by the file and memory allocation words are
10066: intended as throw codes. They typically are in the range
10067: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
10068: @i{ior}s is -512@minus{}@i{errno}.
10069: 
10070: @end table
10071: 
10072: @c =====================================================================
10073: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
10074: @section The optional Programming-Tools word set
10075: @c =====================================================================
10076: @cindex system documentation, programming-tools words
10077: @cindex programming-tools words, system documentation
10078: 
10079: @menu
10080: * programming-idef::            Implementation Defined Options            
10081: * programming-ambcond::         Ambiguous Conditions         
10082: @end menu
10083: 
10084: 
10085: @c ---------------------------------------------------------------------
10086: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
10087: @subsection Implementation Defined Options
10088: @c ---------------------------------------------------------------------
10089: @cindex implementation-defined options, programming-tools words
10090: @cindex programming-tools words, implementation-defined options
10091: 
10092: @table @i
10093: @item ending sequence for input following @code{;CODE} and @code{CODE}:
10094: @cindex @code{;CODE} ending sequence
10095: @cindex @code{CODE} ending sequence
10096: @code{END-CODE}
10097: 
10098: @item manner of processing input following @code{;CODE} and @code{CODE}:
10099: @cindex @code{;CODE}, processing input
10100: @cindex @code{CODE}, processing input
10101: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
10102: the input is processed by the text interpreter, (starting) in interpret
10103: state.
10104: 
10105: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
10106: @cindex @code{ASSEMBLER}, search order capability
10107: The ANS Forth search order word set.
10108: 
10109: @item source and format of display by @code{SEE}:
10110: @cindex @code{SEE}, source and format of output
10111: The source for @code{see} is the intermediate code used by the inner
10112: interpreter.  The current @code{see} tries to output Forth source code
10113: as well as possible.
10114: 
10115: @end table
10116: 
10117: @c ---------------------------------------------------------------------
10118: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
10119: @subsection Ambiguous conditions
10120: @c ---------------------------------------------------------------------
10121: @cindex programming-tools words, ambiguous conditions
10122: @cindex ambiguous conditions, programming-tools words
10123: 
10124: @table @i
10125: 
10126: @item deleting the compilation word list (@code{FORGET}):
10127: @cindex @code{FORGET}, deleting the compilation word list
10128: Not implemented (yet).
10129: 
10130: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
10131: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
10132: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
10133: @cindex control-flow stack underflow
10134: This typically results in an @code{abort"} with a descriptive error
10135: message (may change into a @code{-22 throw} (Control structure mismatch)
10136: in the future). You may also get a memory access error. If you are
10137: unlucky, this ambiguous condition is not caught.
10138: 
10139: @item @i{name} can't be found (@code{FORGET}):
10140: @cindex @code{FORGET}, @i{name} can't be found
10141: Not implemented (yet).
10142: 
10143: @item @i{name} not defined via @code{CREATE}:
10144: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
10145: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
10146: the execution semantics of the last defined word no matter how it was
10147: defined.
10148: 
10149: @item @code{POSTPONE} applied to @code{[IF]}:
10150: @cindex @code{POSTPONE} applied to @code{[IF]}
10151: @cindex @code{[IF]} and @code{POSTPONE}
10152: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
10153: equivalent to @code{[IF]}.
10154: 
10155: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
10156: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
10157: Continue in the same state of conditional compilation in the next outer
10158: input source. Currently there is no warning to the user about this.
10159: 
10160: @item removing a needed definition (@code{FORGET}):
10161: @cindex @code{FORGET}, removing a needed definition
10162: Not implemented (yet).
10163: 
10164: @end table
10165: 
10166: 
10167: @c =====================================================================
10168: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
10169: @section The optional Search-Order word set
10170: @c =====================================================================
10171: @cindex system documentation, search-order words
10172: @cindex search-order words, system documentation
10173: 
10174: @menu
10175: * search-idef::                 Implementation Defined Options                 
10176: * search-ambcond::              Ambiguous Conditions              
10177: @end menu
10178: 
10179: 
10180: @c ---------------------------------------------------------------------
10181: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
10182: @subsection Implementation Defined Options
10183: @c ---------------------------------------------------------------------
10184: @cindex implementation-defined options, search-order words
10185: @cindex search-order words, implementation-defined options
10186: 
10187: @table @i
10188: @item maximum number of word lists in search order:
10189: @cindex maximum number of word lists in search order
10190: @cindex search order, maximum depth
10191: @code{s" wordlists" environment? drop .}. Currently 16.
10192: 
10193: @item minimum search order:
10194: @cindex minimum search order
10195: @cindex search order, minimum
10196: @code{root root}.
10197: 
10198: @end table
10199: 
10200: @c ---------------------------------------------------------------------
10201: @node search-ambcond,  , search-idef, The optional Search-Order word set
10202: @subsection Ambiguous conditions
10203: @c ---------------------------------------------------------------------
10204: @cindex search-order words, ambiguous conditions
10205: @cindex ambiguous conditions, search-order words
10206: 
10207: @table @i
10208: @item changing the compilation word list (during compilation):
10209: @cindex changing the compilation word list (during compilation)
10210: @cindex compilation word list, change before definition ends
10211: The word is entered into the word list that was the compilation word list
10212: at the start of the definition. Any changes to the name field (e.g.,
10213: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
10214: are applied to the latest defined word (as reported by @code{last} or
10215: @code{lastxt}), if possible, irrespective of the compilation word list.
10216: 
10217: @item search order empty (@code{previous}):
10218: @cindex @code{previous}, search order empty
10219: @cindex vocstack empty, @code{previous}
10220: @code{abort" Vocstack empty"}.
10221: 
10222: @item too many word lists in search order (@code{also}):
10223: @cindex @code{also}, too many word lists in search order
10224: @cindex vocstack full, @code{also}
10225: @code{abort" Vocstack full"}.
10226: 
10227: @end table
10228: 
10229: @c ***************************************************************
10230: @node Model, Integrating Gforth, ANS conformance, Top
10231: @chapter Model
10232: 
10233: This chapter has yet to be written. It will contain information, on
10234: which internal structures you can rely.
10235: 
10236: @c ***************************************************************
10237: @node Integrating Gforth, Emacs and Gforth, Model, Top
10238: @chapter Integrating Gforth into C programs
10239: 
10240: This is not yet implemented.
10241: 
10242: Several people like to use Forth as scripting language for applications
10243: that are otherwise written in C, C++, or some other language.
10244: 
10245: The Forth system ATLAST provides facilities for embedding it into
10246: applications; unfortunately it has several disadvantages: most
10247: importantly, it is not based on ANS Forth, and it is apparently dead
10248: (i.e., not developed further and not supported). The facilities
10249: provided by Gforth in this area are inspired by ATLAST's facilities, so
10250: making the switch should not be hard.
10251: 
10252: We also tried to design the interface such that it can easily be
10253: implemented by other Forth systems, so that we may one day arrive at a
10254: standardized interface. Such a standard interface would allow you to
10255: replace the Forth system without having to rewrite C code.
10256: 
10257: You embed the Gforth interpreter by linking with the library
10258: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
10259: global symbols in this library that belong to the interface, have the
10260: prefix @code{forth_}. (Global symbols that are used internally have the
10261: prefix @code{gforth_}).
10262: 
10263: You can include the declarations of Forth types and the functions and
10264: variables of the interface with @code{#include <forth.h>}.
10265: 
10266: Types.
10267: 
10268: Variables.
10269: 
10270: Data and FP Stack pointer. Area sizes.
10271: 
10272: functions.
10273: 
10274: forth_init(imagefile)
10275: forth_evaluate(string) exceptions?
10276: forth_goto(address) (or forth_execute(xt)?)
10277: forth_continue() (a corountining mechanism)
10278: 
10279: Adding primitives.
10280: 
10281: No checking.
10282: 
10283: Signals?
10284: 
10285: Accessing the Stacks
10286: 
10287: @c ******************************************************************
10288: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
10289: @chapter Emacs and Gforth
10290: @cindex Emacs and Gforth
10291: 
10292: @cindex @file{gforth.el}
10293: @cindex @file{forth.el}
10294: @cindex Rydqvist, Goran
10295: @cindex comment editing commands
10296: @cindex @code{\}, editing with Emacs
10297: @cindex debug tracer editing commands
10298: @cindex @code{~~}, removal with Emacs
10299: @cindex Forth mode in Emacs
10300: Gforth comes with @file{gforth.el}, an improved version of
10301: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
10302: improvements are:
10303: 
10304: @itemize @bullet
10305: @item
10306: A better (but still not perfect) handling of indentation.
10307: @item
10308: Comment paragraph filling (@kbd{M-q})
10309: @item
10310: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
10311: @item
10312: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
10313: @end itemize
10314: 
10315: I left the stuff I do not use alone, even though some of it only makes
10316: sense for TILE. To get a description of these features, enter Forth mode
10317: and type @kbd{C-h m}.
10318: 
10319: @cindex source location of error or debugging output in Emacs
10320: @cindex error output, finding the source location in Emacs
10321: @cindex debugging output, finding the source location in Emacs
10322: In addition, Gforth supports Emacs quite well: The source code locations
10323: given in error messages, debugging output (from @code{~~}) and failed
10324: assertion messages are in the right format for Emacs' compilation mode
10325: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
10326: Manual}) so the source location corresponding to an error or other
10327: message is only a few keystrokes away (@kbd{C-x `} for the next error,
10328: @kbd{C-c C-c} for the error under the cursor).
10329: 
10330: @cindex @file{TAGS} file
10331: @cindex @file{etags.fs}
10332: @cindex viewing the source of a word in Emacs
10333: Also, if you @code{include} @file{etags.fs}, a new @file{TAGS} file will
10334: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
10335: contains the definitions of all words defined afterwards. You can then
10336: find the source for a word using @kbd{M-.}. Note that emacs can use
10337: several tags files at the same time (e.g., one for the Gforth sources
10338: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
10339: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
10340: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
10341: @file{/usr/local/share/gforth/0.2.0/TAGS}).
10342: 
10343: @cindex @file{.emacs}
10344: To get all these benefits, add the following lines to your @file{.emacs}
10345: file:
10346: 
10347: @example
10348: (autoload 'forth-mode "gforth.el")
10349: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
10350: @end example
10351: 
10352: @c ******************************************************************
10353: @node Image Files, Engine, Emacs and Gforth, Top
10354: @chapter Image Files
10355: @cindex image file
10356: @cindex @file{.fi} files
10357: @cindex precompiled Forth code
10358: @cindex dictionary in persistent form
10359: @cindex persistent form of dictionary
10360: 
10361: An image file is a file containing an image of the Forth dictionary,
10362: i.e., compiled Forth code and data residing in the dictionary.  By
10363: convention, we use the extension @code{.fi} for image files.
10364: 
10365: @menu
10366: * Image Licensing Issues::      Distribution terms for images.
10367: * Image File Background::       Why have image files?
10368: * Non-Relocatable Image Files::   don't always work.
10369: * Data-Relocatable Image Files::  are better.
10370: * Fully Relocatable Image Files:: better yet.
10371: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
10372: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
10373: * Modifying the Startup Sequence::  and turnkey applications.
10374: @end menu
10375: 
10376: @node Image Licensing Issues, Image File Background, Image Files, Image Files
10377: @section Image Licensing Issues
10378: @cindex license for images
10379: @cindex image license
10380: 
10381: An image created with @code{gforthmi} (@pxref{gforthmi}) or
10382: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
10383: original image; i.e., according to copyright law it is a derived work of
10384: the original image.
10385: 
10386: Since Gforth is distributed under the GNU GPL, the newly created image
10387: falls under the GNU GPL, too. In particular, this means that if you
10388: distribute the image, you have to make all of the sources for the image
10389: available, including those you wrote.  For details see @ref{License, ,
10390: GNU General Public License (Section 3)}.
10391: 
10392: If you create an image with @code{cross} (@pxref{cross.fs}), the image
10393: contains only code compiled from the sources you gave it; if none of
10394: these sources is under the GPL, the terms discussed above do not apply
10395: to the image. However, if your image needs an engine (a gforth binary)
10396: that is under the GPL, you should make sure that you distribute both in
10397: a way that is at most a @emph{mere aggregation}, if you don't want the
10398: terms of the GPL to apply to the image.
10399: 
10400: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
10401: @section Image File Background
10402: @cindex image file background
10403: 
10404: Our Forth system consists not only of primitives, but also of
10405: definitions written in Forth. Since the Forth compiler itself belongs to
10406: those definitions, it is not possible to start the system with the
10407: primitives and the Forth source alone. Therefore we provide the Forth
10408: code as an image file in nearly executable form. When Gforth starts up,
10409: a C routine loads the image file into memory, optionally relocates the
10410: addresses, then sets up the memory (stacks etc.) according to
10411: information in the image file, and (finally) starts executing Forth
10412: code.
10413: 
10414: The image file variants represent different compromises between the
10415: goals of making it easy to generate image files and making them
10416: portable.
10417: 
10418: @cindex relocation at run-time
10419: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
10420: run-time. This avoids many of the complications discussed below (image
10421: files are data relocatable without further ado), but costs performance
10422: (one addition per memory access).
10423: 
10424: @cindex relocation at load-time
10425: By contrast, the Gforth loader performs relocation at image load time. The
10426: loader also has to replace tokens that represent primitive calls with the
10427: appropriate code-field addresses (or code addresses in the case of
10428: direct threading).
10429: 
10430: There are three kinds of image files, with different degrees of
10431: relocatability: non-relocatable, data-relocatable, and fully relocatable
10432: image files.
10433: 
10434: @cindex image file loader
10435: @cindex relocating loader
10436: @cindex loader for image files
10437: These image file variants have several restrictions in common; they are
10438: caused by the design of the image file loader:
10439: 
10440: @itemize @bullet
10441: @item
10442: There is only one segment; in particular, this means, that an image file
10443: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
10444: them). The contents of the stacks are not represented, either.
10445: 
10446: @item
10447: The only kinds of relocation supported are: adding the same offset to
10448: all cells that represent data addresses; and replacing special tokens
10449: with code addresses or with pieces of machine code.
10450: 
10451: If any complex computations involving addresses are performed, the
10452: results cannot be represented in the image file. Several applications that
10453: use such computations come to mind:
10454: @itemize @minus
10455: @item
10456: Hashing addresses (or data structures which contain addresses) for table
10457: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
10458: purpose, you will have no problem, because the hash tables are
10459: recomputed automatically when the system is started. If you use your own
10460: hash tables, you will have to do something similar.
10461: 
10462: @item
10463: There's a cute implementation of doubly-linked lists that uses
10464: @code{XOR}ed addresses. You could represent such lists as singly-linked
10465: in the image file, and restore the doubly-linked representation on
10466: startup.@footnote{In my opinion, though, you should think thrice before
10467: using a doubly-linked list (whatever implementation).}
10468: 
10469: @item
10470: The code addresses of run-time routines like @code{docol:} cannot be
10471: represented in the image file (because their tokens would be replaced by
10472: machine code in direct threaded implementations). As a workaround,
10473: compute these addresses at run-time with @code{>code-address} from the
10474: executions tokens of appropriate words (see the definitions of
10475: @code{docol:} and friends in @file{kernel.fs}).
10476: 
10477: @item
10478: On many architectures addresses are represented in machine code in some
10479: shifted or mangled form. You cannot put @code{CODE} words that contain
10480: absolute addresses in this form in a relocatable image file. Workarounds
10481: are representing the address in some relative form (e.g., relative to
10482: the CFA, which is present in some register), or loading the address from
10483: a place where it is stored in a non-mangled form.
10484: @end itemize
10485: @end itemize
10486: 
10487: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
10488: @section Non-Relocatable Image Files
10489: @cindex non-relocatable image files
10490: @cindex image file, non-relocatable
10491: 
10492: These files are simple memory dumps of the dictionary. They are specific
10493: to the executable (i.e., @file{gforth} file) they were created
10494: with. What's worse, they are specific to the place on which the
10495: dictionary resided when the image was created. Now, there is no
10496: guarantee that the dictionary will reside at the same place the next
10497: time you start Gforth, so there's no guarantee that a non-relocatable
10498: image will work the next time (Gforth will complain instead of crashing,
10499: though).
10500: 
10501: You can create a non-relocatable image file with
10502: 
10503: doc-savesystem
10504: 
10505: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
10506: @section Data-Relocatable Image Files
10507: @cindex data-relocatable image files
10508: @cindex image file, data-relocatable
10509: 
10510: These files contain relocatable data addresses, but fixed code addresses
10511: (instead of tokens). They are specific to the executable (i.e.,
10512: @file{gforth} file) they were created with. For direct threading on some
10513: architectures (e.g., the i386), data-relocatable images do not work. You
10514: get a data-relocatable image, if you use @file{gforthmi} with a
10515: Gforth binary that is not doubly indirect threaded (@pxref{Fully
10516: Relocatable Image Files}).
10517: 
10518: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
10519: @section Fully Relocatable Image Files
10520: @cindex fully relocatable image files
10521: @cindex image file, fully relocatable
10522: 
10523: @cindex @file{kern*.fi}, relocatability
10524: @cindex @file{gforth.fi}, relocatability
10525: These image files have relocatable data addresses, and tokens for code
10526: addresses. They can be used with different binaries (e.g., with and
10527: without debugging) on the same machine, and even across machines with
10528: the same data formats (byte order, cell size, floating point
10529: format). However, they are usually specific to the version of Gforth
10530: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
10531: are fully relocatable.
10532: 
10533: There are two ways to create a fully relocatable image file:
10534: 
10535: @menu
10536: * gforthmi::                    The normal way
10537: * cross.fs::                    The hard way
10538: @end menu
10539: 
10540: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
10541: @subsection @file{gforthmi}
10542: @cindex @file{comp-i.fs}
10543: @cindex @file{gforthmi}
10544: 
10545: You will usually use @file{gforthmi}. If you want to create an
10546: image @i{file} that contains everything you would load by invoking
10547: Gforth with @code{gforth @i{options}}, you simply say:
10548: @example
10549: gforthmi @i{file} @i{options}
10550: @end example
10551: 
10552: E.g., if you want to create an image @file{asm.fi} that has the file
10553: @file{asm.fs} loaded in addition to the usual stuff, you could do it
10554: like this:
10555: 
10556: @example
10557: gforthmi asm.fi asm.fs
10558: @end example
10559: 
10560: @file{gforthmi} is implemented as a sh script and works like this: It
10561: produces two non-relocatable images for different addresses and then
10562: compares them. Its output reflects this: first you see the output (if
10563: any) of the two Gforth invocations that produce the nonrelocatable image
10564: files, then you see the output of the comparing program: It displays the
10565: offset used for data addresses and the offset used for code addresses;
10566: moreover, for each cell that cannot be represented correctly in the
10567: image files, it displays a line like the following one:
10568: 
10569: @example
10570:      78DC         BFFFFA50         BFFFFA40
10571: @end example
10572: 
10573: This means that at offset $78dc from @code{forthstart}, one input image
10574: contains $bffffa50, and the other contains $bffffa40. Since these cells
10575: cannot be represented correctly in the output image, you should examine
10576: these places in the dictionary and verify that these cells are dead
10577: (i.e., not read before they are written).
10578: 
10579: @cindex --application, @code{gforthmi} option
10580: If you insert the option @code{--application} in front of the image file
10581: name, you will get an image that uses the @code{--appl-image} option
10582: instead of the @code{--image-file} option (@pxref{Invoking
10583: Gforth}). When you execute such an image on Unix (by typing the image
10584: name as command), the Gforth engine will pass all options to the image
10585: instead of trying to interpret them as engine options.
10586: 
10587: If you type @file{gforthmi} with no arguments, it prints some usage
10588: instructions.
10589: 
10590: @cindex @code{savesystem} during @file{gforthmi}
10591: @cindex @code{bye} during @file{gforthmi}
10592: @cindex doubly indirect threaded code
10593: @cindex environment variable @code{GFORTHD}
10594: @cindex @code{GFORTHD} environment variable
10595: @cindex @code{gforth-ditc}
10596: There are a few wrinkles: After processing the passed @i{options}, the
10597: words @code{savesystem} and @code{bye} must be visible. A special doubly
10598: indirect threaded version of the @file{gforth} executable is used for
10599: creating the nonrelocatable images; you can pass the exact filename of
10600: this executable through the environment variable @code{GFORTHD}
10601: (default: @file{gforth-ditc}); if you pass a version that is not doubly
10602: indirect threaded, you will not get a fully relocatable image, but a
10603: data-relocatable image (because there is no code address offset). The
10604: normal @file{gforth} executable is used for creating the relocatable
10605: image; you can pass the exact filename of this executable through the
10606: environment variable @code{GFORTH}.
10607: 
10608: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
10609: @subsection @file{cross.fs}
10610: @cindex @file{cross.fs}
10611: @cindex cross-compiler
10612: @cindex metacompiler
10613: 
10614: You can also use @code{cross}, a batch compiler that accepts a Forth-like
10615: programming language. This @code{cross} language has to be documented
10616: yet.
10617: 
10618: @cindex target compiler
10619: @code{cross} also allows you to create image files for machines with
10620: different data sizes and data formats than the one used for generating
10621: the image file. You can also use it to create an application image that
10622: does not contain a Forth compiler. These features are bought with
10623: restrictions and inconveniences in programming. E.g., addresses have to
10624: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
10625: order to make the code relocatable.
10626: 
10627: 
10628: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
10629: @section Stack and Dictionary Sizes
10630: @cindex image file, stack and dictionary sizes
10631: @cindex dictionary size default
10632: @cindex stack size default
10633: 
10634: If you invoke Gforth with a command line flag for the size
10635: (@pxref{Invoking Gforth}), the size you specify is stored in the
10636: dictionary. If you save the dictionary with @code{savesystem} or create
10637: an image with @file{gforthmi}, this size will become the default
10638: for the resulting image file. E.g., the following will create a
10639: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
10640: 
10641: @example
10642: gforthmi gforth.fi -m 1M
10643: @end example
10644: 
10645: In other words, if you want to set the default size for the dictionary
10646: and the stacks of an image, just invoke @file{gforthmi} with the
10647: appropriate options when creating the image.
10648: 
10649: @cindex stack size, cache-friendly
10650: Note: For cache-friendly behaviour (i.e., good performance), you should
10651: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
10652: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
10653: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
10654: 
10655: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
10656: @section Running Image Files
10657: @cindex running image files
10658: @cindex invoking image files
10659: @cindex image file invocation
10660: 
10661: @cindex -i, invoke image file
10662: @cindex --image file, invoke image file
10663: You can invoke Gforth with an image file @i{image} instead of the
10664: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
10665: @example
10666: gforth -i @i{image}
10667: @end example
10668: 
10669: @cindex executable image file
10670: @cindex image file, executable
10671: If your operating system supports starting scripts with a line of the
10672: form @code{#! ...}, you just have to type the image file name to start
10673: Gforth with this image file (note that the file extension @code{.fi} is
10674: just a convention). I.e., to run Gforth with the image file @i{image},
10675: you can just type @i{image} instead of @code{gforth -i @i{image}}.
10676: This works because every @code{.fi} file starts with a line of this
10677: format:
10678: 
10679: @example
10680: #! /usr/local/bin/gforth-0.4.0 -i
10681: @end example
10682: 
10683: The file and pathname for the Gforth engine specified on this line is
10684: the specific Gforth executable that it was built against; i.e. the value
10685: of the environment variable @code{GFORTH} at the time that
10686: @file{gforthmi} was executed.
10687: 
10688: You can make use of the same shell capability to make a Forth source
10689: file into an executable. For example, if you place this text in a file:
10690: 
10691: @example
10692: #! /usr/local/bin/gforth
10693: 
10694: ." Hello, world" CR
10695: bye
10696: @end example
10697: 
10698: @noindent
10699: and then make the file executable (chmod +x in Unix), you can run it
10700: directly from the command line. The sequence @code{#!} is used in two
10701: ways; firstly, it is recognised as a ``magic sequence'' by the operating
10702: system@footnote{The Unix kernel actually recognises two types of files:
10703: executable files and files of data, where the data is processed by an
10704: interpreter that is specified on the ``interpreter line'' -- the first
10705: line of the file, starting with the sequence #!. There may be a small
10706: limit (e.g., 32) on the number of characters that may be specified on
10707: the interpreter line.} secondly it is treated as a comment character by
10708: Gforth. Because of the second usage, a space is required between
10709: @code{#!} and the path to the executable.
10710: 
10711: The disadvantage of this latter technique, compared with using
10712: @file{gforthmi}, is that it is slower; the Forth source code is compiled
10713: on-the-fly, each time the program is invoked.
10714: 
10715: @comment TODO describe the #! magic with reference to the Power Tools book.
10716: 
10717: doc-#!
10718: 
10719: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
10720: @section Modifying the Startup Sequence
10721: @cindex startup sequence for image file
10722: @cindex image file initialization sequence
10723: @cindex initialization sequence of image file
10724: 
10725: You can add your own initialization to the startup sequence through the
10726: deferred word @code{'cold}. @code{'cold} is invoked just before the
10727: image-specific command line processing (by default, loading files and
10728: evaluating (@code{-e}) strings) starts.
10729: 
10730: A sequence for adding your initialization usually looks like this:
10731: 
10732: @example
10733: :noname
10734:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
10735:     ... \ your stuff
10736: ; IS 'cold
10737: @end example
10738: 
10739: @cindex turnkey image files
10740: @cindex image file, turnkey applications
10741: You can make a turnkey image by letting @code{'cold} execute a word
10742: (your turnkey application) that never returns; instead, it exits Gforth
10743: via @code{bye} or @code{throw}.
10744: 
10745: @cindex command-line arguments, access
10746: @cindex arguments on the command line, access
10747: You can access the (image-specific) command-line arguments through the
10748: variables @code{argc} and @code{argv}. @code{arg} provides convenient
10749: access to @code{argv}.
10750: 
10751: If @code{'cold} exits normally, Gforth processes the command-line
10752: arguments as files to be loaded and strings to be evaluated.  Therefore,
10753: @code{'cold} should remove the arguments it has used in this case.
10754: 
10755: doc-'cold
10756: doc-argc
10757: doc-argv
10758: doc-arg
10759: 
10760: 
10761: @c ******************************************************************
10762: @node Engine, Binding to System Library, Image Files, Top
10763: @chapter Engine
10764: @cindex engine
10765: @cindex virtual machine
10766: 
10767: Reading this chapter is not necessary for programming with Gforth. It
10768: may be helpful for finding your way in the Gforth sources.
10769: 
10770: The ideas in this section have also been published in the papers
10771: @cite{ANS fig/GNU/??? Forth} (in German) by Bernd Paysan, presented at
10772: the Forth-Tagung '93 and @cite{A Portable Forth Engine} by M. Anton
10773: Ertl, presented at EuroForth '93; the latter is available at
10774: @*@url{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z}.
10775: 
10776: @menu
10777: * Portability::                 
10778: * Threading::                   
10779: * Primitives::                  
10780: * Performance::                 
10781: @end menu
10782: 
10783: @node Portability, Threading, Engine, Engine
10784: @section Portability
10785: @cindex engine portability
10786: 
10787: An important goal of the Gforth Project is availability across a wide
10788: range of personal machines. fig-Forth, and, to a lesser extent, F83,
10789: achieved this goal by manually coding the engine in assembly language
10790: for several then-popular processors. This approach is very
10791: labor-intensive and the results are short-lived due to progress in
10792: computer architecture.
10793: 
10794: @cindex C, using C for the engine
10795: Others have avoided this problem by coding in C, e.g., Mitch Bradley
10796: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
10797: particularly popular for UNIX-based Forths due to the large variety of
10798: architectures of UNIX machines. Unfortunately an implementation in C
10799: does not mix well with the goals of efficiency and with using
10800: traditional techniques: Indirect or direct threading cannot be expressed
10801: in C, and switch threading, the fastest technique available in C, is
10802: significantly slower. Another problem with C is that it is very
10803: cumbersome to express double integer arithmetic.
10804: 
10805: @cindex GNU C for the engine
10806: @cindex long long
10807: Fortunately, there is a portable language that does not have these
10808: limitations: GNU C, the version of C processed by the GNU C compiler
10809: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
10810: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
10811: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
10812: threading possible, its @code{long long} type (@pxref{Long Long, ,
10813: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
10814: double numbers@footnote{Unfortunately, long longs are not implemented
10815: properly on all machines (e.g., on alpha-osf1, long longs are only 64
10816: bits, the same size as longs (and pointers), but they should be twice as
10817: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
10818: C Manual}). So, we had to implement doubles in C after all. Still, on
10819: most machines we can use long longs and achieve better performance than
10820: with the emulation package.}. GNU C is available for free on all
10821: important (and many unimportant) UNIX machines, VMS, 80386s running
10822: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
10823: on all these machines.
10824: 
10825: Writing in a portable language has the reputation of producing code that
10826: is slower than assembly. For our Forth engine we repeatedly looked at
10827: the code produced by the compiler and eliminated most compiler-induced
10828: inefficiencies by appropriate changes in the source code.
10829: 
10830: @cindex explicit register declarations
10831: @cindex --enable-force-reg, configuration flag
10832: @cindex -DFORCE_REG
10833: However, register allocation cannot be portably influenced by the
10834: programmer, leading to some inefficiencies on register-starved
10835: machines. We use explicit register declarations (@pxref{Explicit Reg
10836: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
10837: improve the speed on some machines. They are turned on by using the
10838: configuration flag @code{--enable-force-reg} (@code{gcc} switch
10839: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
10840: machine, but also on the compiler version: On some machines some
10841: compiler versions produce incorrect code when certain explicit register
10842: declarations are used. So by default @code{-DFORCE_REG} is not used.
10843: 
10844: @node Threading, Primitives, Portability, Engine
10845: @section Threading
10846: @cindex inner interpreter implementation
10847: @cindex threaded code implementation
10848: 
10849: @cindex labels as values
10850: GNU C's labels as values extension (available since @code{gcc-2.0},
10851: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
10852: makes it possible to take the address of @i{label} by writing
10853: @code{&&@i{label}}.  This address can then be used in a statement like
10854: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
10855: @code{goto x}.
10856: 
10857: @cindex @code{NEXT}, indirect threaded
10858: @cindex indirect threaded inner interpreter
10859: @cindex inner interpreter, indirect threaded
10860: With this feature an indirect threaded @code{NEXT} looks like:
10861: @example
10862: cfa = *ip++;
10863: ca = *cfa;
10864: goto *ca;
10865: @end example
10866: @cindex instruction pointer
10867: For those unfamiliar with the names: @code{ip} is the Forth instruction
10868: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
10869: execution token and points to the code field of the next word to be
10870: executed; The @code{ca} (code address) fetched from there points to some
10871: executable code, e.g., a primitive or the colon definition handler
10872: @code{docol}.
10873: 
10874: @cindex @code{NEXT}, direct threaded
10875: @cindex direct threaded inner interpreter
10876: @cindex inner interpreter, direct threaded
10877: Direct threading is even simpler:
10878: @example
10879: ca = *ip++;
10880: goto *ca;
10881: @end example
10882: 
10883: Of course we have packaged the whole thing neatly in macros called
10884: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
10885: 
10886: @menu
10887: * Scheduling::                  
10888: * Direct or Indirect Threaded?::  
10889: * DOES>::                       
10890: @end menu
10891: 
10892: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
10893: @subsection Scheduling
10894: @cindex inner interpreter optimization
10895: 
10896: There is a little complication: Pipelined and superscalar processors,
10897: i.e., RISC and some modern CISC machines can process independent
10898: instructions while waiting for the results of an instruction. The
10899: compiler usually reorders (schedules) the instructions in a way that
10900: achieves good usage of these delay slots. However, on our first tries
10901: the compiler did not do well on scheduling primitives. E.g., for
10902: @code{+} implemented as
10903: @example
10904: n=sp[0]+sp[1];
10905: sp++;
10906: sp[0]=n;
10907: NEXT;
10908: @end example
10909: the @code{NEXT} comes strictly after the other code, i.e., there is nearly no
10910: scheduling. After a little thought the problem becomes clear: The
10911: compiler cannot know that @code{sp} and @code{ip} point to different
10912: addresses (and the version of @code{gcc} we used would not know it even
10913: if it was possible), so it could not move the load of the cfa above the
10914: store to the TOS. Indeed the pointers could be the same, if code on or
10915: very near the top of stack were executed. In the interest of speed we
10916: chose to forbid this probably unused ``feature'' and helped the compiler
10917: in scheduling: @code{NEXT} is divided into the loading part (@code{NEXT_P1})
10918: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
10919: @example
10920: n=sp[0]+sp[1];
10921: sp++;
10922: NEXT_P1;
10923: sp[0]=n;
10924: NEXT_P2;
10925: @end example
10926: This can be scheduled optimally by the compiler.
10927: 
10928: This division can be turned off with the switch @code{-DCISC_NEXT}. This
10929: switch is on by default on machines that do not profit from scheduling
10930: (e.g., the 80386), in order to preserve registers.
10931: 
10932: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
10933: @subsection Direct or Indirect Threaded?
10934: @cindex threading, direct or indirect?
10935: 
10936: @cindex -DDIRECT_THREADED
10937: Both! After packaging the nasty details in macro definitions we
10938: realized that we could switch between direct and indirect threading by
10939: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
10940: defining a few machine-specific macros for the direct-threading case.
10941: On the Forth level we also offer access words that hide the
10942: differences between the threading methods (@pxref{Threading Words}).
10943: 
10944: Indirect threading is implemented completely machine-independently.
10945: Direct threading needs routines for creating jumps to the executable
10946: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
10947: machine-dependent, but they do not amount to many source lines. Therefore,
10948: even porting direct threading to a new machine requires little effort.
10949: 
10950: @cindex --enable-indirect-threaded, configuration flag
10951: @cindex --enable-direct-threaded, configuration flag
10952: The default threading method is machine-dependent. You can enforce a
10953: specific threading method when building Gforth with the configuration
10954: flag @code{--enable-direct-threaded} or
10955: @code{--enable-indirect-threaded}. Note that direct threading is not
10956: supported on all machines.
10957: 
10958: @node DOES>,  , Direct or Indirect Threaded?, Threading
10959: @subsection DOES>
10960: @cindex @code{DOES>} implementation
10961: 
10962: @cindex @code{dodoes} routine
10963: @cindex @code{DOES>}-code
10964: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
10965: the chunk of code executed by every word defined by a
10966: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
10967: the Forth code to be executed, i.e. the code after the
10968: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
10969: 
10970: In fig-Forth the code field points directly to the @code{dodoes} and the
10971: @code{DOES>}code address is stored in the cell after the code address (i.e. at
10972: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
10973: the Forth-79 and all later standards, because in fig-Forth this address
10974: lies in the body (which is illegal in these standards). However, by
10975: making the code field larger for all words this solution becomes legal
10976: again. We use this approach for the indirect threaded version and for
10977: direct threading on some machines. Leaving a cell unused in most words
10978: is a bit wasteful, but on the machines we are targeting this is hardly a
10979: problem. The other reason for having a code field size of two cells is
10980: to avoid having different image files for direct and indirect threaded
10981: systems (direct threaded systems require two-cell code fields on many
10982: machines).
10983: 
10984: @cindex @code{DOES>}-handler
10985: The other approach is that the code field points or jumps to the cell
10986: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
10987: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
10988: @code{DOES>}-code address by computing the code address, i.e., the address of
10989: the jump to dodoes, and add the length of that jump field. A variant of
10990: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
10991: return address (which can be found in the return register on RISCs) is
10992: the @code{DOES>}-code address. Since the two cells available in the code field
10993: are used up by the jump to the code address in direct threading on many
10994: architectures, we use this approach for direct threading on these
10995: architectures. We did not want to add another cell to the code field.
10996: 
10997: @node Primitives, Performance, Threading, Engine
10998: @section Primitives
10999: @cindex primitives, implementation
11000: @cindex virtual machine instructions, implementation
11001: 
11002: @menu
11003: * Automatic Generation::        
11004: * TOS Optimization::            
11005: * Produced code::               
11006: @end menu
11007: 
11008: @node Automatic Generation, TOS Optimization, Primitives, Primitives
11009: @subsection Automatic Generation
11010: @cindex primitives, automatic generation
11011: 
11012: @cindex @file{prims2x.fs}
11013: Since the primitives are implemented in a portable language, there is no
11014: longer any need to minimize the number of primitives. On the contrary,
11015: having many primitives has an advantage: speed. In order to reduce the
11016: number of errors in primitives and to make programming them easier, we
11017: provide a tool, the primitive generator (@file{prims2x.fs}), that
11018: automatically generates most (and sometimes all) of the C code for a
11019: primitive from the stack effect notation.  The source for a primitive
11020: has the following form:
11021: 
11022: @cindex primitive source format
11023: @format
11024: @i{Forth-name}	@i{stack-effect}	@i{category}	[@i{pronounc.}]
11025: [@code{""}@i{glossary entry}@code{""}]
11026: @i{C code}
11027: [@code{:}
11028: @i{Forth code}]
11029: @end format
11030: 
11031: The items in brackets are optional. The category and glossary fields
11032: are there for generating the documentation, the Forth code is there
11033: for manual implementations on machines without GNU C. E.g., the source
11034: for the primitive @code{+} is:
11035: @example
11036: +    n1 n2 -- n    core    plus
11037: n = n1+n2;
11038: @end example
11039: 
11040: This looks like a specification, but in fact @code{n = n1+n2} is C
11041: code. Our primitive generation tool extracts a lot of information from
11042: the stack effect notations@footnote{We use a one-stack notation, even
11043: though we have separate data and floating-point stacks; The separate
11044: notation can be generated easily from the unified notation.}: The number
11045: of items popped from and pushed on the stack, their type, and by what
11046: name they are referred to in the C code. It then generates a C code
11047: prelude and postlude for each primitive. The final C code for @code{+}
11048: looks like this:
11049: 
11050: @example
11051: I_plus:	/* + ( n1 n2 -- n ) */  /* label, stack effect */
11052: /*  */                          /* documentation */
11053: @{
11054: DEF_CA                          /* definition of variable ca (indirect threading) */
11055: Cell n1;                        /* definitions of variables */
11056: Cell n2;
11057: Cell n;
11058: n1 = (Cell) sp[1];              /* input */
11059: n2 = (Cell) TOS;
11060: sp += 1;                        /* stack adjustment */
11061: NAME("+")                       /* debugging output (with -DDEBUG) */
11062: @{
11063: n = n1+n2;                      /* C code taken from the source */
11064: @}
11065: NEXT_P1;                        /* NEXT part 1 */
11066: TOS = (Cell)n;                  /* output */
11067: NEXT_P2;                        /* NEXT part 2 */
11068: @}
11069: @end example
11070: 
11071: This looks long and inefficient, but the GNU C compiler optimizes quite
11072: well and produces optimal code for @code{+} on, e.g., the R3000 and the
11073: HP RISC machines: Defining the @code{n}s does not produce any code, and
11074: using them as intermediate storage also adds no cost.
11075: 
11076: There are also other optimizations that are not illustrated by this
11077: example: assignments between simple variables are usually for free (copy
11078: propagation). If one of the stack items is not used by the primitive
11079: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
11080: (dead code elimination). On the other hand, there are some things that
11081: the compiler does not do, therefore they are performed by
11082: @file{prims2x.fs}: The compiler does not optimize code away that stores
11083: a stack item to the place where it just came from (e.g., @code{over}).
11084: 
11085: While programming a primitive is usually easy, there are a few cases
11086: where the programmer has to take the actions of the generator into
11087: account, most notably @code{?dup}, but also words that do not (always)
11088: fall through to @code{NEXT}.
11089: 
11090: @node TOS Optimization, Produced code, Automatic Generation, Primitives
11091: @subsection TOS Optimization
11092: @cindex TOS optimization for primitives
11093: @cindex primitives, keeping the TOS in a register
11094: 
11095: An important optimization for stack machine emulators, e.g., Forth
11096: engines, is keeping  one or more of the top stack items in
11097: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
11098: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
11099: @itemize @bullet
11100: @item
11101: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
11102: due to fewer loads from and stores to the stack.
11103: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
11104: @i{y<n}, due to additional moves between registers.
11105: @end itemize
11106: 
11107: @cindex -DUSE_TOS
11108: @cindex -DUSE_NO_TOS
11109: In particular, keeping one item in a register is never a disadvantage,
11110: if there are enough registers. Keeping two items in registers is a
11111: disadvantage for frequent words like @code{?branch}, constants,
11112: variables, literals and @code{i}. Therefore our generator only produces
11113: code that keeps zero or one items in registers. The generated C code
11114: covers both cases; the selection between these alternatives is made at
11115: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
11116: code for @code{+} is just a simple variable name in the one-item case,
11117: otherwise it is a macro that expands into @code{sp[0]}. Note that the
11118: GNU C compiler tries to keep simple variables like @code{TOS} in
11119: registers, and it usually succeeds, if there are enough registers.
11120: 
11121: @cindex -DUSE_FTOS
11122: @cindex -DUSE_NO_FTOS
11123: The primitive generator performs the TOS optimization for the
11124: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
11125: operations the benefit of this optimization is even larger:
11126: floating-point operations take quite long on most processors, but can be
11127: performed in parallel with other operations as long as their results are
11128: not used. If the FP-TOS is kept in a register, this works. If
11129: it is kept on the stack, i.e., in memory, the store into memory has to
11130: wait for the result of the floating-point operation, lengthening the
11131: execution time of the primitive considerably.
11132: 
11133: The TOS optimization makes the automatic generation of primitives a
11134: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
11135: @code{TOS} is not sufficient. There are some special cases to
11136: consider:
11137: @itemize @bullet
11138: @item In the case of @code{dup ( w -- w w )} the generator must not
11139: eliminate the store to the original location of the item on the stack,
11140: if the TOS optimization is turned on.
11141: @item Primitives with stack effects of the form @code{--}
11142: @i{out1}...@i{outy} must store the TOS to the stack at the start.
11143: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
11144: must load the TOS from the stack at the end. But for the null stack
11145: effect @code{--} no stores or loads should be generated.
11146: @end itemize
11147: 
11148: @node Produced code,  , TOS Optimization, Primitives
11149: @subsection Produced code
11150: @cindex primitives, assembly code listing
11151: 
11152: @cindex @file{engine.s}
11153: To see what assembly code is produced for the primitives on your machine
11154: with your compiler and your flag settings, type @code{make engine.s} and
11155: look at the resulting file @file{engine.s}.
11156: 
11157: @node  Performance,  , Primitives, Engine
11158: @section Performance
11159: @cindex performance of some Forth interpreters
11160: @cindex engine performance
11161: @cindex benchmarking Forth systems
11162: @cindex Gforth performance
11163: 
11164: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
11165: impossible to write a significantly faster engine.
11166: 
11167: On register-starved machines like the 386 architecture processors
11168: improvements are possible, because @code{gcc} does not utilize the
11169: registers as well as a human, even with explicit register declarations;
11170: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
11171: and hand-tuned it for the 486; this system is 1.19 times faster on the
11172: Sieve benchmark on a 486DX2/66 than Gforth compiled with
11173: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
11174: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
11175: registers fit in real registers (and we can even afford to use the TOS
11176: optimization), resulting in a speedup of 1.14 on the sieve over the
11177: earlier results.
11178: 
11179: @cindex Win32Forth performance
11180: @cindex NT Forth performance
11181: @cindex eforth performance
11182: @cindex ThisForth performance
11183: @cindex PFE performance
11184: @cindex TILE performance
11185: The potential advantage of assembly language implementations
11186: is not necessarily realized in complete Forth systems: We compared
11187: Gforth-0.4.9 (direct threaded, compiled with @code{gcc-2.95.1} and
11188: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
11189: 1994) and Eforth (with and without peephole (aka pinhole) optimization
11190: of the threaded code); all these systems were written in assembly
11191: language. We also compared Gforth with three systems written in C:
11192: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
11193: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
11194: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
11195: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
11196: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
11197: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
11198: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
11199: 486DX2/66 with similar memory performance under Windows NT. Marcel
11200: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
11201: added the peephole optimizer, ran the benchmarks and reported the
11202: results.
11203: 
11204: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
11205: matrix multiplication come from the Stanford integer benchmarks and have
11206: been translated into Forth by Martin Fraeman; we used the versions
11207: included in the TILE Forth package, but with bigger data set sizes; and
11208: a recursive Fibonacci number computation for benchmarking calling
11209: performance. The following table shows the time taken for the benchmarks
11210: scaled by the time taken by Gforth (in other words, it shows the speedup
11211: factor that Gforth achieved over the other systems).
11212: 
11213: @example
11214: relative      Win32-    NT       eforth       This-      
11215:   time  Gforth Forth Forth eforth  +opt   PFE Forth  TILE
11216: sieve     1.00  1.58  1.30   1.58  0.97  1.80  3.63  9.79
11217: bubble    1.00  1.55  1.67   1.75  1.04  1.78        4.59
11218: matmul    1.00  1.67  1.53   1.66  0.84  1.79        4.63
11219: fib       1.00  1.75  1.53   1.40  0.99  1.99  3.43  4.93
11220: @end example
11221: 
11222: You may be quite surprised by the good performance of Gforth when
11223: compared with systems written in assembly language. One important reason
11224: for the disappointing performance of these other systems is probably
11225: that they are not written optimally for the 486 (e.g., they use the
11226: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
11227: but costly method for relocating the Forth image: like @code{cforth}, it
11228: computes the actual addresses at run time, resulting in two address
11229: computations per @code{NEXT} (@pxref{Image File Background}).
11230: 
11231: Only Eforth with the peephole optimizer performs comparable to
11232: Gforth. The speedups achieved with peephole optimization of threaded
11233: code are quite remarkable. Adding a peephole optimizer to Gforth should
11234: cause similar speedups.
11235: 
11236: The speedup of Gforth over PFE, ThisForth and TILE can be easily
11237: explained with the self-imposed restriction of the latter systems to
11238: standard C, which makes efficient threading impossible (however, the
11239: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
11240: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
11241: Moreover, current C compilers have a hard time optimizing other aspects
11242: of the ThisForth and the TILE source.
11243: 
11244: The performance of Gforth on 386 architecture processors varies widely
11245: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
11246: allocate any of the virtual machine registers into real machine
11247: registers by itself and would not work correctly with explicit register
11248: declarations, giving a 1.5 times slower engine (on a 486DX2/66 running
11249: the Sieve) than the one measured above.
11250: 
11251: Note that there have been several releases of Win32Forth since the
11252: release presented here, so the results presented above may have little
11253: predictive value for the performance of Win32Forth today (results for
11254: the current release on an i486DX2/66 are welcome).
11255: 
11256: @cindex @file{Benchres}
11257: In @cite{Translating Forth to Efficient C} by M. Anton Ertl and Martin
11258: Maierhofer (presented at EuroForth '95), an indirect threaded version of
11259: Gforth is compared with Win32Forth, NT Forth, PFE, and ThisForth; that
11260: version of Gforth is slower on a 486 than the direct threaded version
11261: used here. The paper available at
11262: @*@url{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz};
11263: it also contains numbers for some native code systems. You can find a
11264: newer version of these measurements at
11265: @url{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
11266: find numbers for Gforth on various machines in @file{Benchres}.
11267: 
11268: @c ******************************************************************
11269: @node Binding to System Library, Cross Compiler, Engine, Top
11270: @chapter Binding to System Library
11271: 
11272: @node Cross Compiler, Bugs, Binding to System Library, Top
11273: @chapter Cross Compiler
11274: 
11275: Cross Compiler
11276: 
11277: @menu
11278: * Using the Cross Compiler::
11279: * How the Cross Compiler Works::
11280: @end menu
11281: 
11282: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
11283: @section Using the Cross Compiler
11284: 
11285: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
11286: @section How the Cross Compiler Works
11287: 
11288: @node Bugs, Origin, Cross Compiler, Top
11289: @appendix Bugs
11290: @cindex bug reporting
11291: 
11292: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
11293: 
11294: If you find a bug, please send a bug report to
11295: @email{bug-gforth@@gnu.org}. A bug report should include this
11296: information:
11297: 
11298: @itemize @bullet
11299: @item
11300: The Gforth version used (it is announced at the start of an
11301: interactive Gforth session).
11302: @item
11303: The machine and operating system (on Unix
11304: systems @code{uname -a} will report this information).
11305: @item
11306: The installation options (send the file @file{config.status}).
11307: @item
11308: A complete list of changes (if any) you (or your installer) have made to the
11309: Gforth sources.
11310: @item
11311: A program (or a sequence of keyboard commands) that reproduces the bug.
11312: @item
11313: A description of what you think constitutes the buggy behaviour.
11314: @end itemize
11315: 
11316: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
11317: to Report Bugs, gcc.info, GNU C Manual}.
11318: 
11319: 
11320: @node Origin, Forth-related information, Bugs, Top
11321: @appendix Authors and Ancestors of Gforth
11322: 
11323: @section Authors and Contributors
11324: @cindex authors of Gforth
11325: @cindex contributors to Gforth
11326: 
11327: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
11328: Ertl. The third major author was Jens Wilke.  Lennart Benschop (who was
11329: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
11330: with their continuous feedback. Lennart Benshop contributed
11331: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
11332: support for calling C libraries. Helpful comments also came from Paul
11333: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
11334: Wavrik, Barrie Stott, Marc de Groot, and Jorge Acerada. Since the
11335: release of Gforth-0.2.1 there were also helpful comments from many
11336: others; thank you all, sorry for not listing you here (but digging
11337: through my mailbox to extract your names is on my to-do list). Since the
11338: release of Gforth-0.4.0 Neal Crook worked on the manual.
11339: 
11340: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
11341: and autoconf, among others), and to the creators of the Internet: Gforth
11342: was developed across the Internet, and its authors did not meet
11343: physically for the first 4 years of development.
11344: 
11345: @section Pedigree
11346: @cindex pedigree of Gforth
11347: 
11348: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
11349: Dirk Zoller) will cross-fertilize each other. Of course, a significant
11350: part of the design of Gforth was prescribed by ANS Forth.
11351: 
11352: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
11353: 32 bit native code version of VolksForth for the Atari ST, written
11354: mostly by Dietrich Weineck.
11355: 
11356: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
11357: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
11358: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
11359: 
11360: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
11361: Forth-83 standard. !! Pedigree? When?
11362: 
11363: A team led by Bill Ragsdale implemented fig-Forth on many processors in
11364: 1979. Robert Selzer and Bill Ragsdale developed the original
11365: implementation of fig-Forth for the 6502 based on microForth.
11366: 
11367: The principal architect of microForth was Dean Sanderson. microForth was
11368: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
11369: the 1802, and subsequently implemented on the 8080, the 6800 and the
11370: Z80.
11371: 
11372: All earlier Forth systems were custom-made, usually by Charles Moore,
11373: who discovered (as he puts it) Forth during the late 60s. The first full
11374: Forth existed in 1971.
11375: 
11376: A part of the information in this section comes from @cite{The Evolution
11377: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
11378: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
11379: Notices 28(3), 1993.  You can find more historical and genealogical
11380: information about Forth there.
11381: 
11382: @node Forth-related information, Word Index, Origin, Top
11383: @appendix Other Forth-related information
11384: @cindex Forth-related information
11385: 
11386: @menu
11387: * Internet resources::
11388: * Books::
11389: * The Forth Interest Group::
11390: * Conferences::
11391: @end menu
11392: 
11393: 
11394: @node Internet resources, Books, Forth-related information, Forth-related information
11395: @section Internet resources
11396: @cindex internet resources
11397: 
11398: @cindex comp.lang.forth
11399: @cindex frequently asked questions
11400: There is an active newsgroup (comp.lang.forth) discussing Forth and
11401: Forth-related issues. A frequently-asked-questions (FAQ) list
11402: is posted to the newsgroup regulary, and archived at these sites:
11403: 
11404: @itemize @bullet
11405: @item
11406: @url{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
11407: @item
11408: @url{ftp://ftp.forth.org/pub/Forth/FAQ/}
11409: @end itemize
11410: 
11411: The FAQ list should be considered mandatory reading before posting to
11412: the newsgroup.
11413: 
11414: Here are some other web sites holding Forth-related material:
11415: 
11416: @itemize @bullet
11417: @item
11418: @url{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
11419: @item
11420: @url{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
11421: @item
11422: @url{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
11423: @item
11424: @url{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
11425: Research page, including links to the Journal of Forth Application and
11426: Research (JFAR) and a searchable Forth bibliography.
11427: @end itemize
11428: 
11429: 
11430: @node Books, The Forth Interest Group, Internet resources, Forth-related information
11431: @section Books
11432: @cindex books on Forth
11433: 
11434: As the Standard is relatively new, there are not many books out yet. It
11435: is not recommended to learn Forth by using Gforth and a book that is not
11436: written for ANS Forth, as you will not know your mistakes from the
11437: deviations of the book. However, books based on the Forth-83 standard
11438: should be ok, because ANS Forth is primarily an extension of Forth-83.
11439: 
11440: @cindex standard document for ANS Forth
11441: @cindex ANS Forth document
11442: The definite reference if you want to write ANS Forth programs is, of
11443: course, the ANS Forth document. It is available in printed form from the
11444: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
11445: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
11446: $200. You can also get it from Global Engineering Documents (Tel.: USA
11447: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
11448: 
11449: @cite{dpANS6}, the last draft of the standard, which was then submitted
11450: to ANSI for publication is available electronically and for free in some
11451: MS Word format, and it has been converted to HTML
11452: (@url{http://www.taygeta.com/forth/dpans.html}; this is my favourite
11453: format); this HTML version also includes the answers to Requests for
11454: Interpretation (RFIs). Some pointers to these versions can be found
11455: through @*@url{http://www.complang.tuwien.ac.at/projects/forth.html}.
11456: 
11457: @cindex introductory book on Forth
11458: @cindex book on Forth, introductory
11459: @cindex Woehr, Jack: @cite{Forth: The New Model}
11460: @cindex @cite{Forth: The new model} (book)
11461: @cite{Forth: The New Model} by Jack Woehr (Prentice-Hall, 1993) is an
11462: introductory book based on a draft version of the standard. It does not
11463: cover the whole standard. It also contains interesting background
11464: information (Jack Woehr was in the ANS Forth Technical Committee). It is
11465: not appropriate for complete newbies, but programmers experienced in
11466: other languages should find it ok.
11467: 
11468: @cindex Conklin, Edward K., and Elizabeth Rather: @cite{Forth Programmer's Handbook}
11469: @cindex Rather, Elizabeth and Edward K. Conklin: @cite{Forth Programmer's Handbook}
11470: @cindex @cite{Forth Programmer's Handbook} (book)
11471: @cite{Forth Programmer's Handbook} by Edward K. Conklin, Elizabeth
11472: D. Rather and the technical staff of Forth, Inc. (Forth, Inc., 1997;
11473: ISBN 0-9662156-0-5) contains little introductory material. The majority
11474: of the book is similar to @ref{Words}, but the book covers most of the
11475: standard words and some non-standard words (whereas this manual is
11476: quite incomplete). In addition, the book contains a chapter on
11477: programming style. The major drawback of this book is that it usually
11478: does not identify what is standard and what is specific to the Forth
11479: system described in the book (probably one of Forth, Inc.'s systems).
11480: Fortunately, many of the non-standard programming practices described in
11481: the book work in Gforth, too.  Still, this drawback makes the book
11482: hardly more useful than a pre-ANS book.
11483: 
11484: @node The Forth Interest Group, Conferences, Books, Forth-related information
11485: @section The Forth Interest Group
11486: @cindex Forth interest group (FIG)
11487: 
11488: The Forth Interest Group (FIG) is a world-wide, non-profit,
11489: member-supported organisation. It publishes a regular magazine,
11490: @var{FORTH Dimensions}, and offers other benefits of membership. You can
11491: contact the FIG through their office email address:
11492: @email{office@@forth.org} or by visiting their web site at
11493: @url{http://www.forth.org/}. This web site also includes links to FIG
11494: chapters in other countries and American cities
11495: (@url{http://www.forth.org/chapters.html}).
11496: 
11497: @node Conferences, , The Forth Interest Group, Forth-related information
11498: @section Conferences
11499: @cindex Conferences
11500: 
11501: There are several regular conferences related to Forth. They are all
11502: well-publicised in @var{FORTH Dimensions} and on the comp.lang.forth
11503: news group:
11504: 
11505: @itemize @bullet
11506: @item
11507: FORML -- the Forth modification laboratory convenes every year near
11508: Monterey, California.
11509: @item
11510: The Rochester Forth Conference -- an annual conference traditionally
11511: held in Rochester, New York.
11512: @item
11513: EuroForth -- this European conference takes place annually.
11514: @end itemize
11515: 
11516: 
11517: @node Word Index, Concept Index, Forth-related information, Top
11518: @unnumbered Word Index
11519: 
11520: This index is a list of Forth words that have ``glossary'' entries
11521: within this manual. Each word is listed with its stack effect and
11522: wordset.
11523: 
11524: @printindex fn
11525: 
11526: @node Concept Index,  , Word Index, Top
11527: @unnumbered Concept and Word Index
11528: 
11529: Not all entries listed in this index are present verbatim in the
11530: text. This index also duplicates, in abbreviated form, all of the words
11531: listed in the Word Index (only the names are listed for the words here).
11532: 
11533: @printindex cp
11534: 
11535: @contents
11536: @bye
11537: 

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