File:  [gforth] / gforth / doc / gforth.ds
Revision 1.45: download - view: text, annotated - select for diffs
Fri Dec 3 18:21:03 1999 UTC (24 years, 4 months ago) by crook
Branches: MAIN
CVS tags: HEAD
Fix minor typos in manual. Added chapter 13 to .cvsignore. Fixed incorrect
comments in makedoc.fs and added a couple of factors to the code.

    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 05-Jun-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: @node Top, License, (dir), (dir)
  126: @ifinfo
  127: Gforth is a free implementation of ANS Forth available on many
  128: personal machines. This manual corresponds to version @value{VERSION}.
  129: @end ifinfo
  130: 
  131: @menu
  132: * License::                     The GPL
  133: * Goals::                       About the Gforth Project
  134: * Gforth Environment::          Starting (and exiting) Gforth
  135: * Introduction::                An introduction to ANS Forth
  136: * Words::                       Forth words available in Gforth
  137: * Error messages::              How to interpret them
  138: * Tools::                       Programming tools
  139: * ANS conformance::             Implementation-defined options etc.
  140: * Model::                       The abstract machine of Gforth
  141: * Integrating Gforth::          Forth as scripting language for applications
  142: * Emacs and Gforth::            The Gforth Mode
  143: * Image Files::                 @code{.fi} files contain compiled code
  144: * Engine::                      The inner interpreter and the primitives
  145: * Binding to System Library::   
  146: * Cross Compiler::              The Cross Compiler
  147: * Bugs::                        How to report them
  148: * Origin::                      Authors and ancestors of Gforth
  149: * Forth-related information::   Books and places to look on the WWW
  150: * Word Index::                  An item for each Forth word
  151: * Name Index::                  Forth words, only names listed
  152: * Concept Index::               A menu covering many topics
  153: 
  154: @detailmenu
  155:  --- The Detailed Node Listing ---
  156: 
  157: Goals of Gforth
  158: 
  159: * Gforth Extensions Sinful?::
  160: 
  161: Gforth Environment
  162: 
  163: * Invoking Gforth::             Getting in
  164: * Leaving Gforth::              Getting out
  165: * Command-line editing::        
  166: * Upper and lower case::
  167: * Environment variables::       ..that affect how Gforth starts up
  168: * Gforth Files::                What gets installed and where
  169: 
  170: An Introduction to ANS Forth
  171: 
  172: * Introducing the Text Interpreter::
  173: * Stacks and Postfix notation::
  174: * Your first definition::
  175: * How does that work?::
  176: * Forth is written in Forth::
  177: * Review - elements of a Forth system::
  178: * Where to go next::
  179: * Exercises::
  180: 
  181: Forth Words
  182: 
  183: * Notation::                    
  184: * Comments::
  185: * Boolean Flags::
  186: * Arithmetic::                  
  187: * Stack Manipulation::          
  188: * Memory::                      
  189: * Control Structures::          
  190: * Defining Words::              
  191: * The Text Interpreter::
  192: * Tokens for Words::            
  193: * Word Lists::                   
  194: * Environmental Queries::
  195: * Files::                       
  196: * Blocks::                      
  197: * Other I/O::                   
  198: * Programming Tools::           
  199: * Assembler and Code Words::    
  200: * Threading Words::             
  201: * Locals::                      
  202: * Structures::                  
  203: * Object-oriented Forth::       
  204: * Passing Commands to the OS::
  205: * Miscellaneous Words::
  206: 
  207: Arithmetic
  208: 
  209: * Single precision::            
  210: * Bitwise operations::          
  211: * Double precision::            Double-cell integer arithmetic
  212: * Numeric comparison::
  213: * Mixed precision::             Operations with single and double-cell integers
  214: * Floating Point::              
  215: 
  216: Stack Manipulation
  217: 
  218: * Data stack::                  
  219: * Floating point stack::        
  220: * Return stack::                
  221: * Locals stack::                
  222: * Stack pointer manipulation::  
  223: 
  224: Memory
  225: 
  226: * Memory model::                
  227: * Dictionary allocation::       
  228: * Heap Allocation::             
  229: * Memory Access::               
  230: * Address arithmetic::          
  231: * Memory Blocks::               
  232: 
  233: Control Structures
  234: 
  235: * Selection::                   IF ... ELSE ... ENDIF
  236: * Simple Loops::                BEGIN ...
  237: * Counted Loops::               DO
  238: * Arbitrary control structures::
  239: * Calls and returns::
  240: * Exception Handling::          
  241: 
  242: Defining Words
  243: 
  244: * CREATE::
  245: * Variables::                   Variables and user variables
  246: * Constants::
  247: * Values::                      Initialised variables
  248: * Colon Definitions::
  249: * Anonymous Definitions::       Definitions without names
  250: * User-defined Defining Words::
  251: * Deferred words::              Allow forward references
  252: * Aliases::
  253: * Supplying names::
  254: * Interpretation and Compilation Semantics::
  255: * Combined words::
  256: 
  257: The Text Interpreter
  258: 
  259: * Input Sources::
  260: * Number Conversion::
  261: * Interpret/Compile states::
  262: * Literals::
  263: * Interpreter Directives::
  264: 
  265: Word Lists
  266: 
  267: * Why use word lists?::
  268: * Word list examples::
  269: 
  270: Files
  271: 
  272: * Forth source files::
  273: * General files::         
  274: * Search Paths::                 
  275: * Forth Search Paths::    
  276: * General Search Paths::        
  277: 
  278: Other I/O
  279: 
  280: * Simple numeric output::       Predefined formats
  281: * Formatted numeric output::    Formatted (pictured) output
  282: * String Formats::              How Forth stores strings in memory
  283: * Displaying characters and strings:: Other stuff
  284: * Input::                       Input
  285: 
  286: Programming Tools
  287: 
  288: * Debugging::                   Simple and quick.
  289: * Assertions::                  Making your programs self-checking.
  290: * Singlestep Debugger::		Executing your program word by word.
  291: 
  292: Locals
  293: 
  294: * Gforth locals::               
  295: * ANS Forth locals::            
  296: 
  297: Gforth locals
  298: 
  299: * Where are locals visible by name?::  
  300: * How long do locals live?::    
  301: * Programming Style::           
  302: * Implementation::              
  303: 
  304: Structures
  305: 
  306: * Why explicit structure support?::  
  307: * Structure Usage::             
  308: * Structure Naming Convention::  
  309: * Structure Implementation::    
  310: * Structure Glossary::          
  311: 
  312: Object-oriented Forth
  313: 
  314: * Why object-oriented programming?::
  315: * Object-Oriented Terminology::
  316: * Objects::
  317: * OOF::
  318: * Mini-OOF::
  319: * Comparison with other object models::  
  320: 
  321: The @file{objects.fs} model
  322: 
  323: * Properties of the Objects model::  
  324: * Basic Objects Usage::         
  325: * The Objects base class::      
  326: * Creating objects::            
  327: * Object-Oriented Programming Style::  
  328: * Class Binding::               
  329: * Method conveniences::         
  330: * Classes and Scoping::         
  331: * Dividing classes::            
  332: * Object Interfaces::           
  333: * Objects Implementation::      
  334: * Objects Glossary::            
  335: 
  336: The @file{oof.fs} model
  337: 
  338: * Properties of the OOF model::
  339: * Basic OOF Usage::
  340: * The OOF base class::
  341: * Class Declaration::
  342: * Class Implementation::
  343: 
  344: The @file{mini-oof.fs} model
  345: 
  346: * Basic Mini-OOF Usage::
  347: * Mini-OOF Example::
  348: * Mini-OOF Implementation::
  349: 
  350: Tools
  351: 
  352: * ANS Report::                  Report the words used, sorted by wordset.
  353: 
  354: ANS conformance
  355: 
  356: * The Core Words::              
  357: * The optional Block word set::  
  358: * The optional Double Number word set::  
  359: * The optional Exception word set::  
  360: * The optional Facility word set::  
  361: * The optional File-Access word set::  
  362: * The optional Floating-Point word set::  
  363: * The optional Locals word set::  
  364: * The optional Memory-Allocation word set::  
  365: * The optional Programming-Tools word set::  
  366: * The optional Search-Order word set::  
  367: 
  368: The Core Words
  369: 
  370: * core-idef::                   Implementation Defined Options                   
  371: * core-ambcond::                Ambiguous Conditions                
  372: * core-other::                  Other System Documentation                  
  373: 
  374: The optional Block word set
  375: 
  376: * block-idef::                  Implementation Defined Options
  377: * block-ambcond::               Ambiguous Conditions               
  378: * block-other::                 Other System Documentation                 
  379: 
  380: The optional Double Number word set
  381: 
  382: * double-ambcond::              Ambiguous Conditions              
  383: 
  384: The optional Exception word set
  385: 
  386: * exception-idef::              Implementation Defined Options              
  387: 
  388: The optional Facility word set
  389: 
  390: * facility-idef::               Implementation Defined Options               
  391: * facility-ambcond::            Ambiguous Conditions            
  392: 
  393: The optional File-Access word set
  394: 
  395: * file-idef::                   Implementation Defined Options
  396: * file-ambcond::                Ambiguous Conditions                
  397: 
  398: The optional Floating-Point word set
  399: 
  400: * floating-idef::               Implementation Defined Options
  401: * floating-ambcond::            Ambiguous Conditions            
  402: 
  403: The optional Locals word set
  404: 
  405: * locals-idef::                 Implementation Defined Options                 
  406: * locals-ambcond::              Ambiguous Conditions              
  407: 
  408: The optional Memory-Allocation word set
  409: 
  410: * memory-idef::                 Implementation Defined Options                 
  411: 
  412: The optional Programming-Tools word set
  413: 
  414: * programming-idef::            Implementation Defined Options            
  415: * programming-ambcond::         Ambiguous Conditions         
  416: 
  417: The optional Search-Order word set
  418: 
  419: * search-idef::                 Implementation Defined Options                 
  420: * search-ambcond::              Ambiguous Conditions              
  421: 
  422: Image Files
  423: 
  424: * Image Licensing Issues::      Distribution terms for images.
  425: * Image File Background::       Why have image files?
  426: * Non-Relocatable Image Files::   don't always work.
  427: * Data-Relocatable Image Files::  are better.
  428: * Fully Relocatable Image Files:: better yet.
  429: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
  430: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
  431: * Modifying the Startup Sequence::  and turnkey applications.
  432: 
  433: Fully Relocatable Image Files
  434: 
  435: * gforthmi::                    The normal way
  436: * cross.fs::                    The hard way
  437: 
  438: Engine
  439: 
  440: * Portability::                 
  441: * Threading::                   
  442: * Primitives::                  
  443: * Performance::                 
  444: 
  445: Threading
  446: 
  447: * Scheduling::                  
  448: * Direct or Indirect Threaded?::  
  449: * DOES>::                       
  450: 
  451: Primitives
  452: 
  453: * Automatic Generation::        
  454: * TOS Optimization::            
  455: * Produced code::               
  456: 
  457: Cross Compiler
  458: 
  459: * Using the Cross Compiler::
  460: * How the Cross Compiler Works::
  461: 
  462: Other Forth-related information
  463: 
  464: * Internet resources::
  465: * Books::
  466: * The Forth Interest Group::
  467: * Conferences::
  468: 
  469: @end detailmenu
  470: @end menu
  471: 
  472: @node License, Goals, Top, Top
  473: @unnumbered GNU GENERAL PUBLIC LICENSE
  474: @center Version 2, June 1991
  475: 
  476: @display
  477: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
  478: 675 Mass Ave, Cambridge, MA 02139, USA
  479: 
  480: Everyone is permitted to copy and distribute verbatim copies
  481: of this license document, but changing it is not allowed.
  482: @end display
  483: 
  484: @unnumberedsec Preamble
  485: 
  486:   The licenses for most software are designed to take away your
  487: freedom to share and change it.  By contrast, the GNU General Public
  488: License is intended to guarantee your freedom to share and change free
  489: software---to make sure the software is free for all its users.  This
  490: General Public License applies to most of the Free Software
  491: Foundation's software and to any other program whose authors commit to
  492: using it.  (Some other Free Software Foundation software is covered by
  493: the GNU Library General Public License instead.)  You can apply it to
  494: your programs, too.
  495: 
  496:   When we speak of free software, we are referring to freedom, not
  497: price.  Our General Public Licenses are designed to make sure that you
  498: have the freedom to distribute copies of free software (and charge for
  499: this service if you wish), that you receive source code or can get it
  500: if you want it, that you can change the software or use pieces of it
  501: in new free programs; and that you know you can do these things.
  502: 
  503:   To protect your rights, we need to make restrictions that forbid
  504: anyone to deny you these rights or to ask you to surrender the rights.
  505: These restrictions translate to certain responsibilities for you if you
  506: distribute copies of the software, or if you modify it.
  507: 
  508:   For example, if you distribute copies of such a program, whether
  509: gratis or for a fee, you must give the recipients all the rights that
  510: you have.  You must make sure that they, too, receive or can get the
  511: source code.  And you must show them these terms so they know their
  512: rights.
  513: 
  514:   We protect your rights with two steps: (1) copyright the software, and
  515: (2) offer you this license which gives you legal permission to copy,
  516: distribute and/or modify the software.
  517: 
  518:   Also, for each author's protection and ours, we want to make certain
  519: that everyone understands that there is no warranty for this free
  520: software.  If the software is modified by someone else and passed on, we
  521: want its recipients to know that what they have is not the original, so
  522: that any problems introduced by others will not reflect on the original
  523: authors' reputations.
  524: 
  525:   Finally, any free program is threatened constantly by software
  526: patents.  We wish to avoid the danger that redistributors of a free
  527: program will individually obtain patent licenses, in effect making the
  528: program proprietary.  To prevent this, we have made it clear that any
  529: patent must be licensed for everyone's free use or not licensed at all.
  530: 
  531:   The precise terms and conditions for copying, distribution and
  532: modification follow.
  533: 
  534: @iftex
  535: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  536: @end iftex
  537: @ifinfo
  538: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  539: @end ifinfo
  540: 
  541: @enumerate 0
  542: @item
  543: This License applies to any program or other work which contains
  544: a notice placed by the copyright holder saying it may be distributed
  545: under the terms of this General Public License.  The ``Program'', below,
  546: refers to any such program or work, and a ``work based on the Program''
  547: means either the Program or any derivative work under copyright law:
  548: that is to say, a work containing the Program or a portion of it,
  549: either verbatim or with modifications and/or translated into another
  550: language.  (Hereinafter, translation is included without limitation in
  551: the term ``modification''.)  Each licensee is addressed as ``you''.
  552: 
  553: Activities other than copying, distribution and modification are not
  554: covered by this License; they are outside its scope.  The act of
  555: running the Program is not restricted, and the output from the Program
  556: is covered only if its contents constitute a work based on the
  557: Program (independent of having been made by running the Program).
  558: Whether that is true depends on what the Program does.
  559: 
  560: @item
  561: You may copy and distribute verbatim copies of the Program's
  562: source code as you receive it, in any medium, provided that you
  563: conspicuously and appropriately publish on each copy an appropriate
  564: copyright notice and disclaimer of warranty; keep intact all the
  565: notices that refer to this License and to the absence of any warranty;
  566: and give any other recipients of the Program a copy of this License
  567: along with the Program.
  568: 
  569: You may charge a fee for the physical act of transferring a copy, and
  570: you may at your option offer warranty protection in exchange for a fee.
  571: 
  572: @item
  573: You may modify your copy or copies of the Program or any portion
  574: of it, thus forming a work based on the Program, and copy and
  575: distribute such modifications or work under the terms of Section 1
  576: above, provided that you also meet all of these conditions:
  577: 
  578: @enumerate a
  579: @item
  580: You must cause the modified files to carry prominent notices
  581: stating that you changed the files and the date of any change.
  582: 
  583: @item
  584: You must cause any work that you distribute or publish, that in
  585: whole or in part contains or is derived from the Program or any
  586: part thereof, to be licensed as a whole at no charge to all third
  587: parties under the terms of this License.
  588: 
  589: @item
  590: If the modified program normally reads commands interactively
  591: when run, you must cause it, when started running for such
  592: interactive use in the most ordinary way, to print or display an
  593: announcement including an appropriate copyright notice and a
  594: notice that there is no warranty (or else, saying that you provide
  595: a warranty) and that users may redistribute the program under
  596: these conditions, and telling the user how to view a copy of this
  597: License.  (Exception: if the Program itself is interactive but
  598: does not normally print such an announcement, your work based on
  599: the Program is not required to print an announcement.)
  600: @end enumerate
  601: 
  602: These requirements apply to the modified work as a whole.  If
  603: identifiable sections of that work are not derived from the Program,
  604: and can be reasonably considered independent and separate works in
  605: themselves, then this License, and its terms, do not apply to those
  606: sections when you distribute them as separate works.  But when you
  607: distribute the same sections as part of a whole which is a work based
  608: on the Program, the distribution of the whole must be on the terms of
  609: this License, whose permissions for other licensees extend to the
  610: entire whole, and thus to each and every part regardless of who wrote it.
  611: 
  612: Thus, it is not the intent of this section to claim rights or contest
  613: your rights to work written entirely by you; rather, the intent is to
  614: exercise the right to control the distribution of derivative or
  615: collective works based on the Program.
  616: 
  617: In addition, mere aggregation of another work not based on the Program
  618: with the Program (or with a work based on the Program) on a volume of
  619: a storage or distribution medium does not bring the other work under
  620: the scope of this License.
  621: 
  622: @item
  623: You may copy and distribute the Program (or a work based on it,
  624: under Section 2) in object code or executable form under the terms of
  625: Sections 1 and 2 above provided that you also do one of the following:
  626: 
  627: @enumerate a
  628: @item
  629: Accompany it with the complete corresponding machine-readable
  630: source code, which must be distributed under the terms of Sections
  631: 1 and 2 above on a medium customarily used for software interchange; or,
  632: 
  633: @item
  634: Accompany it with a written offer, valid for at least three
  635: years, to give any third party, for a charge no more than your
  636: cost of physically performing source distribution, a complete
  637: machine-readable copy of the corresponding source code, to be
  638: distributed under the terms of Sections 1 and 2 above on a medium
  639: customarily used for software interchange; or,
  640: 
  641: @item
  642: Accompany it with the information you received as to the offer
  643: to distribute corresponding source code.  (This alternative is
  644: allowed only for noncommercial distribution and only if you
  645: received the program in object code or executable form with such
  646: an offer, in accord with Subsection b above.)
  647: @end enumerate
  648: 
  649: The source code for a work means the preferred form of the work for
  650: making modifications to it.  For an executable work, complete source
  651: code means all the source code for all modules it contains, plus any
  652: associated interface definition files, plus the scripts used to
  653: control compilation and installation of the executable.  However, as a
  654: special exception, the source code distributed need not include
  655: anything that is normally distributed (in either source or binary
  656: form) with the major components (compiler, kernel, and so on) of the
  657: operating system on which the executable runs, unless that component
  658: itself accompanies the executable.
  659: 
  660: If distribution of executable or object code is made by offering
  661: access to copy from a designated place, then offering equivalent
  662: access to copy the source code from the same place counts as
  663: distribution of the source code, even though third parties are not
  664: compelled to copy the source along with the object code.
  665: 
  666: @item
  667: You may not copy, modify, sublicense, or distribute the Program
  668: except as expressly provided under this License.  Any attempt
  669: otherwise to copy, modify, sublicense or distribute the Program is
  670: void, and will automatically terminate your rights under this License.
  671: However, parties who have received copies, or rights, from you under
  672: this License will not have their licenses terminated so long as such
  673: parties remain in full compliance.
  674: 
  675: @item
  676: You are not required to accept this License, since you have not
  677: signed it.  However, nothing else grants you permission to modify or
  678: distribute the Program or its derivative works.  These actions are
  679: prohibited by law if you do not accept this License.  Therefore, by
  680: modifying or distributing the Program (or any work based on the
  681: Program), you indicate your acceptance of this License to do so, and
  682: all its terms and conditions for copying, distributing or modifying
  683: the Program or works based on it.
  684: 
  685: @item
  686: Each time you redistribute the Program (or any work based on the
  687: Program), the recipient automatically receives a license from the
  688: original licensor to copy, distribute or modify the Program subject to
  689: these terms and conditions.  You may not impose any further
  690: restrictions on the recipients' exercise of the rights granted herein.
  691: You are not responsible for enforcing compliance by third parties to
  692: this License.
  693: 
  694: @item
  695: If, as a consequence of a court judgment or allegation of patent
  696: infringement or for any other reason (not limited to patent issues),
  697: conditions are imposed on you (whether by court order, agreement or
  698: otherwise) that contradict the conditions of this License, they do not
  699: excuse you from the conditions of this License.  If you cannot
  700: distribute so as to satisfy simultaneously your obligations under this
  701: License and any other pertinent obligations, then as a consequence you
  702: may not distribute the Program at all.  For example, if a patent
  703: license would not permit royalty-free redistribution of the Program by
  704: all those who receive copies directly or indirectly through you, then
  705: the only way you could satisfy both it and this License would be to
  706: refrain entirely from distribution of the Program.
  707: 
  708: If any portion of this section is held invalid or unenforceable under
  709: any particular circumstance, the balance of the section is intended to
  710: apply and the section as a whole is intended to apply in other
  711: circumstances.
  712: 
  713: It is not the purpose of this section to induce you to infringe any
  714: patents or other property right claims or to contest validity of any
  715: such claims; this section has the sole purpose of protecting the
  716: integrity of the free software distribution system, which is
  717: implemented by public license practices.  Many people have made
  718: generous contributions to the wide range of software distributed
  719: through that system in reliance on consistent application of that
  720: system; it is up to the author/donor to decide if he or she is willing
  721: to distribute software through any other system and a licensee cannot
  722: impose that choice.
  723: 
  724: This section is intended to make thoroughly clear what is believed to
  725: be a consequence of the rest of this License.
  726: 
  727: @item
  728: If the distribution and/or use of the Program is restricted in
  729: certain countries either by patents or by copyrighted interfaces, the
  730: original copyright holder who places the Program under this License
  731: may add an explicit geographical distribution limitation excluding
  732: those countries, so that distribution is permitted only in or among
  733: countries not thus excluded.  In such case, this License incorporates
  734: the limitation as if written in the body of this License.
  735: 
  736: @item
  737: The Free Software Foundation may publish revised and/or new versions
  738: of the General Public License from time to time.  Such new versions will
  739: be similar in spirit to the present version, but may differ in detail to
  740: address new problems or concerns.
  741: 
  742: Each version is given a distinguishing version number.  If the Program
  743: specifies a version number of this License which applies to it and ``any
  744: later version'', you have the option of following the terms and conditions
  745: either of that version or of any later version published by the Free
  746: Software Foundation.  If the Program does not specify a version number of
  747: this License, you may choose any version ever published by the Free Software
  748: Foundation.
  749: 
  750: @item
  751: If you wish to incorporate parts of the Program into other free
  752: programs whose distribution conditions are different, write to the author
  753: to ask for permission.  For software which is copyrighted by the Free
  754: Software Foundation, write to the Free Software Foundation; we sometimes
  755: make exceptions for this.  Our decision will be guided by the two goals
  756: of preserving the free status of all derivatives of our free software and
  757: of promoting the sharing and reuse of software generally.
  758: 
  759: @iftex
  760: @heading NO WARRANTY
  761: @end iftex
  762: @ifinfo
  763: @center NO WARRANTY
  764: @end ifinfo
  765: 
  766: @item
  767: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
  768: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
  769: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
  770: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
  771: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  772: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
  773: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
  774: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
  775: REPAIR OR CORRECTION.
  776: 
  777: @item
  778: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
  779: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
  780: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
  781: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
  782: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
  783: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
  784: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
  785: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
  786: POSSIBILITY OF SUCH DAMAGES.
  787: @end enumerate
  788: 
  789: @iftex
  790: @heading END OF TERMS AND CONDITIONS
  791: @end iftex
  792: @ifinfo
  793: @center END OF TERMS AND CONDITIONS
  794: @end ifinfo
  795: 
  796: @page
  797: @unnumberedsec How to Apply These Terms to Your New Programs
  798: 
  799:   If you develop a new program, and you want it to be of the greatest
  800: possible use to the public, the best way to achieve this is to make it
  801: free software which everyone can redistribute and change under these terms.
  802: 
  803:   To do so, attach the following notices to the program.  It is safest
  804: to attach them to the start of each source file to most effectively
  805: convey the exclusion of warranty; and each file should have at least
  806: the ``copyright'' line and a pointer to where the full notice is found.
  807: 
  808: @smallexample
  809: @var{one line to give the program's name and a brief idea of what it does.}
  810: Copyright (C) 19@var{yy}  @var{name of author}
  811: 
  812: This program is free software; you can redistribute it and/or modify 
  813: it under the terms of the GNU General Public License as published by 
  814: the Free Software Foundation; either version 2 of the License, or 
  815: (at your option) any later version.
  816: 
  817: This program is distributed in the hope that it will be useful,
  818: but WITHOUT ANY WARRANTY; without even the implied warranty of
  819: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  820: GNU General Public License for more details.
  821: 
  822: You should have received a copy of the GNU General Public License
  823: along with this program; if not, write to the Free Software
  824: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  825: @end smallexample
  826: 
  827: Also add information on how to contact you by electronic and paper mail.
  828: 
  829: If the program is interactive, make it output a short notice like this
  830: when it starts in an interactive mode:
  831: 
  832: @smallexample
  833: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
  834: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
  835: type `show w'.  
  836: This is free software, and you are welcome to redistribute it 
  837: under certain conditions; type `show c' for details.
  838: @end smallexample
  839: 
  840: The hypothetical commands @samp{show w} and @samp{show c} should show
  841: the appropriate parts of the General Public License.  Of course, the
  842: commands you use may be called something other than @samp{show w} and
  843: @samp{show c}; they could even be mouse-clicks or menu items---whatever
  844: suits your program.
  845: 
  846: You should also get your employer (if you work as a programmer) or your
  847: school, if any, to sign a ``copyright disclaimer'' for the program, if
  848: necessary.  Here is a sample; alter the names:
  849: 
  850: @smallexample
  851: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  852: `Gnomovision' (which makes passes at compilers) written by James Hacker.
  853: 
  854: @var{signature of Ty Coon}, 1 April 1989
  855: Ty Coon, President of Vice
  856: @end smallexample
  857: 
  858: This General Public License does not permit incorporating your program into
  859: proprietary programs.  If your program is a subroutine library, you may
  860: consider it more useful to permit linking proprietary applications with the
  861: library.  If this is what you want to do, use the GNU Library General
  862: Public License instead of this License.
  863: 
  864: @iftex
  865: @unnumbered Preface
  866: @cindex Preface
  867: This manual documents Gforth. Some introductory material is provided for
  868: readers who are unfamiliar with Forth or who are migrating to Gforth
  869: from other Forth compilers. However, this manual is primarily a
  870: reference manual.
  871: @end iftex
  872: 
  873: @comment TODO much more blurb here.
  874: 
  875: @c ******************************************************************
  876: @node Goals, Gforth Environment, License, Top
  877: @comment node-name,     next,           previous, up
  878: @chapter Goals of Gforth
  879: @cindex goals of the Gforth project
  880: The goal of the Gforth Project is to develop a standard model for
  881: ANS Forth. This can be split into several subgoals:
  882: 
  883: @itemize @bullet
  884: @item
  885: Gforth should conform to the ANS Forth Standard.
  886: @item
  887: It should be a model, i.e. it should define all the
  888: implementation-dependent things.
  889: @item
  890: It should become standard, i.e. widely accepted and used. This goal
  891: is the most difficult one.
  892: @end itemize
  893: 
  894: To achieve these goals Gforth should be
  895: @itemize @bullet
  896: @item
  897: Similar to previous models (fig-Forth, F83)
  898: @item
  899: Powerful. It should provide for all the things that are considered
  900: necessary today and even some that are not yet considered necessary.
  901: @item
  902: Efficient. It should not get the reputation of being exceptionally
  903: slow.
  904: @item
  905: Free.
  906: @item
  907: Available on many machines/easy to port.
  908: @end itemize
  909: 
  910: Have we achieved these goals? Gforth conforms to the ANS Forth
  911: standard. It may be considered a model, but we have not yet documented
  912: which parts of the model are stable and which parts we are likely to
  913: change. It certainly has not yet become a de facto standard, but it
  914: appears to be quite popular. It has some similarities to and some
  915: differences from previous models. It has some powerful features, but not
  916: yet everything that we envisioned. We certainly have achieved our
  917: execution speed goals (@pxref{Performance}).  It is free and available
  918: on many machines.
  919: 
  920: @menu
  921: * Gforth Extensions Sinful?::
  922: @end menu
  923: 
  924: @node Gforth Extensions Sinful?, , Goals, Goals
  925: @comment node-name,     next,           previous, up
  926: @section Is it a Sin to use Gforth Extensions?
  927: @cindex Gforth extensions
  928: 
  929: If you've been paying attention, you will have realised that there is an
  930: ANS (American National Standard) for Forth. As you read through the rest
  931: of this manual, you will see documentation for @i{Standard} words, and
  932: documentation for some appealing Gforth @i{extensions}. You might ask
  933: yourself the question: @i{``Given that there is a standard, would I be
  934: committing a sin if I use (non-Standard) Gforth extensions?''}
  935: 
  936: The answer to that question is somewhat pragmatic and somewhat
  937: philosophical. Consider these points:
  938: 
  939: @itemize @bullet
  940: @item
  941: A number of the Gforth extensions can be implemented in ANS Forth using
  942: files provided in the @file{compat/} directory. These are mentioned in
  943: the text in passing.
  944: @item
  945: Forth has a rich historical precedent for programmers taking advantage
  946: of implementation-dependent features of their tools (for example,
  947: relying on a knowledge of the dictionary structure). Sometimes these
  948: techniques are necessary to extract every last bit of performance from
  949: the hardware, sometimes they are just a programming shorthand.
  950: @item
  951: The best way to break the rules is to know what the rules are. To learn
  952: the rules, there is no substitute for studying the text of the Standard
  953: itself. In particular, Appendix A of the Standard (@var{Rationale})
  954: provides a valuable insight into the thought processes of the technical
  955: committee.
  956: @item
  957: The best reason to break a rule is because you have to; because it's
  958: more productive to do that, because it makes your code run fast enough
  959: or because you can see no Standard way to achieve what you want to
  960: achieve.
  961: @end itemize
  962: 
  963: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
  964: analyse your program and determine what non-Standard definitions it
  965: relies upon.
  966: 
  967: 
  968: @c ******************************************************************
  969: @node Gforth Environment, Introduction, Goals, Top
  970: @chapter Gforth Environment
  971: @cindex Gforth environment
  972: 
  973: Note: ultimately, the Gforth man page will be auto-generated from the
  974: material in this chapter.
  975: 
  976: @menu
  977: * Invoking Gforth::             Getting in
  978: * Leaving Gforth::              Getting out
  979: * Command-line editing::        
  980: * Upper and lower case::
  981: * Environment variables::       ..that affect how Gforth starts up
  982: * Gforth Files::                What gets installed and where
  983: @end menu
  984: 
  985: @xref{Image Files} for related information about the creation of images.
  986: 
  987: @comment ----------------------------------------------
  988: @node Invoking Gforth, Leaving Gforth, ,Gforth Environment
  989: @section Invoking Gforth
  990: @cindex invoking Gforth
  991: @cindex running Gforth
  992: @cindex command-line options
  993: @cindex options on the command line
  994: @cindex flags on the command line
  995: 
  996: Gforth is made up of two parts; an executable ``engine'' (named
  997: @file{gforth} or @file{gforth-fast}) and an image file. To start it, you
  998: will usually just say @code{gforth} -- this automatically loads the
  999: default image file @file{gforth.fi}. In many other cases the default
 1000: Gforth image will be invoked like this:
 1001: @example
 1002: gforth [file | -e forth-code] ...
 1003: @end example
 1004: @noindent
 1005: This interprets the contents of the files and the Forth code in the order they
 1006: are given.
 1007: 
 1008: In addition to the @file{gforth} engine, there is also an engine called
 1009: @file{gforth-fast}, which is faster, but gives less informative error
 1010: messages (@pxref{Error messages}).
 1011: 
 1012: In general, the command line looks like this:
 1013: 
 1014: @example
 1015: gforth[-fast] [engine options] [image options]
 1016: @end example
 1017: 
 1018: The engine options must come before the rest of the command
 1019: line. They are:
 1020: 
 1021: @table @code
 1022: @cindex -i, command-line option
 1023: @cindex --image-file, command-line option
 1024: @item --image-file @i{file}
 1025: @itemx -i @i{file}
 1026: Loads the Forth image @i{file} instead of the default
 1027: @file{gforth.fi} (@pxref{Image Files}).
 1028: 
 1029: @cindex --appl-image, command-line option
 1030: @item --appl-image @i{file}
 1031: Loads the image @i{file} and leaves all further command-line arguments
 1032: to the image (instead of processing them as options).  This is useful
 1033: for building executable application images on Unix, built with
 1034: @code{gforthmi --application ...}.
 1035: 
 1036: @cindex --path, command-line option
 1037: @cindex -p, command-line option
 1038: @item --path @i{path}
 1039: @itemx -p @i{path}
 1040: Uses @i{path} for searching the image file and Forth source code files
 1041: instead of the default in the environment variable @code{GFORTHPATH} or
 1042: the path specified at installation time (e.g.,
 1043: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
 1044: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
 1045: 
 1046: @cindex --dictionary-size, command-line option
 1047: @cindex -m, command-line option
 1048: @cindex @i{size} parameters for command-line options
 1049: @cindex size of the dictionary and the stacks
 1050: @item --dictionary-size @i{size}
 1051: @itemx -m @i{size}
 1052: Allocate @i{size} space for the Forth dictionary space instead of
 1053: using the default specified in the image (typically 256K). The
 1054: @i{size} specification for this and subsequent options consists of
 1055: an integer and a unit (e.g.,
 1056: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
 1057: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
 1058: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
 1059: @code{e} is used.
 1060: 
 1061: @cindex --data-stack-size, command-line option
 1062: @cindex -d, command-line option
 1063: @item --data-stack-size @i{size}
 1064: @itemx -d @i{size}
 1065: Allocate @i{size} space for the data stack instead of using the
 1066: default specified in the image (typically 16K).
 1067: 
 1068: @cindex --return-stack-size, command-line option
 1069: @cindex -r, command-line option
 1070: @item --return-stack-size @i{size}
 1071: @itemx -r @i{size}
 1072: Allocate @i{size} space for the return stack instead of using the
 1073: default specified in the image (typically 15K).
 1074: 
 1075: @cindex --fp-stack-size, command-line option
 1076: @cindex -f, command-line option
 1077: @item --fp-stack-size @i{size}
 1078: @itemx -f @i{size}
 1079: Allocate @i{size} space for the floating point stack instead of
 1080: using the default specified in the image (typically 15.5K). In this case
 1081: the unit specifier @code{e} refers to floating point numbers.
 1082: 
 1083: @cindex --locals-stack-size, command-line option
 1084: @cindex -l, command-line option
 1085: @item --locals-stack-size @i{size}
 1086: @itemx -l @i{size}
 1087: Allocate @i{size} space for the locals stack instead of using the
 1088: default specified in the image (typically 14.5K).
 1089: 
 1090: @cindex -h, command-line option
 1091: @cindex --help, command-line option
 1092: @item --help
 1093: @itemx -h
 1094: Print a message about the command-line options
 1095: 
 1096: @cindex -v, command-line option
 1097: @cindex --version, command-line option
 1098: @item --version
 1099: @itemx -v
 1100: Print version and exit
 1101: 
 1102: @cindex --debug, command-line option
 1103: @item --debug
 1104: Print some information useful for debugging on startup.
 1105: 
 1106: @cindex --offset-image, command-line option
 1107: @item --offset-image
 1108: Start the dictionary at a slightly different position than would be used
 1109: otherwise (useful for creating data-relocatable images,
 1110: @pxref{Data-Relocatable Image Files}).
 1111: 
 1112: @cindex --no-offset-im, command-line option
 1113: @item --no-offset-im
 1114: Start the dictionary at the normal position.
 1115: 
 1116: @cindex --clear-dictionary, command-line option
 1117: @item --clear-dictionary
 1118: Initialize all bytes in the dictionary to 0 before loading the image
 1119: (@pxref{Data-Relocatable Image Files}).
 1120: 
 1121: @cindex --die-on-signal, command-line-option
 1122: @item --die-on-signal
 1123: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
 1124: or the segmentation violation SIGSEGV) by translating it into a Forth
 1125: @code{THROW}. With this option, Gforth exits if it receives such a
 1126: signal. This option is useful when the engine and/or the image might be
 1127: severely broken (such that it causes another signal before recovering
 1128: from the first); this option avoids endless loops in such cases.
 1129: @end table
 1130: 
 1131: @cindex loading files at startup
 1132: @cindex executing code on startup
 1133: @cindex batch processing with Gforth
 1134: As explained above, the image-specific command-line arguments for the
 1135: default image @file{gforth.fi} consist of a sequence of filenames and
 1136: @code{-e @var{forth-code}} options that are interpreted in the sequence
 1137: in which they are given. The @code{-e @var{forth-code}} or
 1138: @code{--evaluate @var{forth-code}} option evaluates the Forth
 1139: code. This option takes only one argument; if you want to evaluate more
 1140: Forth words, you have to quote them or use @code{-e} several times. To exit
 1141: after processing the command line (instead of entering interactive mode)
 1142: append @code{-e bye} to the command line.
 1143: 
 1144: @cindex versions, invoking other versions of Gforth
 1145: If you have several versions of Gforth installed, @code{gforth} will
 1146: invoke the version that was installed last. @code{gforth-@i{version}}
 1147: invokes a specific version. If your environment contains the variable
 1148: @code{GFORTHPATH}, you may want to override it by using the
 1149: @code{--path} option.
 1150: 
 1151: Not yet implemented:
 1152: On startup the system first executes the system initialization file
 1153: (unless the option @code{--no-init-file} is given; note that the system
 1154: resulting from using this option may not be ANS Forth conformant). Then
 1155: the user initialization file @file{.gforth.fs} is executed, unless the
 1156: option @code{--no-rc} is given; this file is first searched in @file{.},
 1157: then in @file{~}, then in the normal path (see above).
 1158: 
 1159: 
 1160: 
 1161: @comment ----------------------------------------------
 1162: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
 1163: @section Leaving Gforth
 1164: @cindex Gforth - leaving
 1165: @cindex leaving Gforth
 1166: 
 1167: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
 1168: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
 1169: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
 1170: data are discarded. @xref{Image Files} for ways of saving the state of
 1171: the system before leaving Gforth.
 1172: 
 1173: doc-bye
 1174: 
 1175: 
 1176: @comment ----------------------------------------------
 1177: @node Command-line editing, Upper and lower case,Leaving Gforth,Gforth Environment
 1178: @section Command-line editing
 1179: @cindex command-line editing
 1180: 
 1181: Gforth maintains a history file that records every line that you type to
 1182: the text interpreter. This file is preserved between sessions, and is
 1183: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
 1184: repeatedly you can recall successively older commands from this (or
 1185: previous) session(s). The full list of command-line editing facilities is:
 1186: 
 1187: @itemize @bullet
 1188: @item
 1189: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
 1190: commands from the history buffer.
 1191: @item
 1192: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
 1193: from the history buffer.
 1194: @item
 1195: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
 1196: @item
 1197: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
 1198: @item
 1199: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
 1200: closing up the line.
 1201: @item
 1202: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
 1203: @item
 1204: @kbd{Ctrl-a} to move the cursor to the start of the line.
 1205: @item
 1206: @kbd{Ctrl-e} to move the cursor to the end of the line.
 1207: @item
 1208: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
 1209: line.
 1210: @item
 1211: @key{TAB} to step through all possible full-word completions of the word
 1212: currently being typed.
 1213: @item
 1214: @kbd{Ctrl-d} at the start of the line to terminate Gforth (gracefully,
 1215: using @code{bye}).
 1216: @end itemize
 1217: 
 1218: When editing, displayable characters are inserted to the left of the
 1219: cursor position; the line is always in ``insert'' (as opposed to
 1220: ``overstrike'') mode.
 1221: 
 1222: @cindex history file
 1223: @cindex @file{.gforth-history}
 1224: On Unix systems, the history file is @file{~/.gforth-history} by
 1225: default@footnote{i.e. it is stored in the user's home directory.}. You
 1226: can find out the name and location of your history file using:
 1227: 
 1228: @example 
 1229: history-file type \ Unix-class systems
 1230: 
 1231: history-file type \ Other systems
 1232: history-dir  type
 1233: @end example
 1234: 
 1235: If you enter long definitions by hand, you can use a text editor to
 1236: paste them out of the history file into a Forth source file for reuse at
 1237: a later time.
 1238: 
 1239: Gforth never trims the size of the history file, so you should do this
 1240: periodically, if necessary.
 1241: 
 1242: @comment this is all defined in history.fs
 1243: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
 1244: @comment chosen?
 1245: 
 1246: 
 1247: 
 1248: @comment ----------------------------------------------
 1249: @node Upper and lower case, Environment variables,Command-line editing,Gforth Environment
 1250: @section Upper and lower case
 1251: @cindex case-sensitivity
 1252: @cindex upper and lower case
 1253: 
 1254: Gforth is case-insensitive; you can enter definitions and invoke
 1255: Standard words using upper, lower or mixed case (however,
 1256: @pxref{core-idef, Implementation-defined options, Implementation-defined
 1257: options}).
 1258: 
 1259: ANS Forth only @i{requires} implementations to recognise Standard words
 1260: when they are typed entirely in upper case. Therefore, a Standard
 1261: program must use upper case for all Standard words. You can use whatever
 1262: case you like for words that you define, but in a standard program you
 1263: have to use the words in the same case that you defined them.
 1264: 
 1265: Gforth supports case sensitivity through @code{table}s (case-sensitive
 1266: wordlists, @pxref{Word Lists}).
 1267: 
 1268: Two people have asked how to convert Gforth to case sensitivity; while
 1269: we think this is a bad idea, you can change all wordlists into tables
 1270: like this:
 1271: 
 1272: @example
 1273: ' table-find forth-wordlist wordlist-map @ !
 1274: @end example
 1275: 
 1276: Note that you now have to type the predefined words in the same case
 1277: that we defined them, which are varying.  You may want to convert them
 1278: to your favourite case before doing this operation (I won't explain how,
 1279: because if you are even contemplating to do this, you'd better have
 1280: enough knowledge of Forth systems to know this already).
 1281: 
 1282: @comment ----------------------------------------------
 1283: @node Environment variables, Gforth Files, Upper and lower case,Gforth Environment
 1284: @section Environment variables
 1285: @cindex environment variables
 1286: 
 1287: Gforth uses these environment variables:
 1288: 
 1289: @itemize @bullet
 1290: @item
 1291: @cindex @code{GFORTHHIST} -- environment variable
 1292: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
 1293: open/create the history file, @file{.gforth-history}. Default:
 1294: @code{$HOME}.
 1295: 
 1296: @item
 1297: @cindex @code{GFORTHPATH} -- environment variable
 1298: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
 1299: for Forth source-code files.
 1300: 
 1301: @item
 1302: @cindex @code{GFORTH} -- environment variable
 1303: @code{GFORTH} -- used by @file{gforthmi} @xref{gforthmi}.
 1304: 
 1305: @item
 1306: @cindex @code{GFORTHD} -- environment variable
 1307: @code{GFORTHD} -- used by @file{gforthmi} @xref{gforthmi}.
 1308: 
 1309: @item
 1310: @cindex @code{TMP}, @code{TEMP} - environment variable
 1311: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
 1312: location for the history file.
 1313: @end itemize
 1314: 
 1315: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
 1316: @comment mentioning these.
 1317: 
 1318: All the Gforth environment variables default to sensible values if they
 1319: are not set.
 1320: 
 1321: 
 1322: @comment ----------------------------------------------
 1323: @node Gforth Files, ,Environment variables,Gforth Environment
 1324: @section Gforth files
 1325: @cindex Gforth files
 1326: 
 1327: When you install Gforth on a Unix system, it installs files in these
 1328: locations by default:
 1329: 
 1330: @itemize @bullet
 1331: @item
 1332: @file{/usr/local/bin/gforth}
 1333: @item
 1334: @file{/usr/local/bin/gforthmi}
 1335: @item
 1336: @file{/usr/local/man/man1/gforth.1} - man page.
 1337: @item
 1338: @file{/usr/local/info} - the Info version of this manual.
 1339: @item
 1340: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
 1341: @item
 1342: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
 1343: @item
 1344: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
 1345: @item
 1346: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
 1347: @end itemize
 1348: 
 1349: You can select different places for installation by using
 1350: @code{configure} options (listed with @code{configure --help}).
 1351: 
 1352: @c ******************************************************************
 1353: @node Introduction, Words, Gforth Environment, Top
 1354: @comment node-name,     next,           previous, up
 1355: @chapter An Introduction to ANS Forth
 1356: @cindex Forth - an introduction
 1357: 
 1358: The primary purpose of this manual is to document Gforth. However, since
 1359: Forth is not a widely-known language and there is a lack of up-to-date
 1360: teaching material, it seems worthwhile to provide some introductory
 1361: material. @xref{Forth-related information} for other sources of Forth-related
 1362: information.
 1363: 
 1364: The examples in this section should work on any ANS Forth; the
 1365: output shown was produced using Gforth. Each example attempts to
 1366: reproduce the exact output that Gforth produces. If you try out the
 1367: examples (and you should), what you should type is shown @kbd{like this}
 1368: and Gforth's response is shown @code{like this}. The single exception is
 1369: that, where the example shows @key{RET} it means that you should
 1370: press the ``carriage return'' key. Unfortunately, some output formats for
 1371: this manual cannot show the difference between @kbd{this} and
 1372: @code{this} which will make trying out the examples harder (but not
 1373: impossible).
 1374: 
 1375: Forth is an unusual language. It provides an interactive development
 1376: environment which includes both an interpreter and compiler. Forth
 1377: programming style encourages you to break a problem down into many
 1378: @cindex factoring
 1379: small fragments (@dfn{factoring}), and then to develop and test each
 1380: fragment interactively. Forth advocates assert that breaking the
 1381: edit-compile-test cycle used by conventional programming languages can
 1382: lead to great productivity improvements.
 1383: 
 1384: @menu
 1385: * Introducing the Text Interpreter::
 1386: * Stacks and Postfix notation::
 1387: * Your first definition::
 1388: * How does that work?::
 1389: * Forth is written in Forth::
 1390: * Review - elements of a Forth system::
 1391: * Where to go next::
 1392: * Exercises::
 1393: @end menu
 1394: 
 1395: @comment ----------------------------------------------
 1396: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
 1397: @section Introducing the Text Interpreter
 1398: @cindex text interpreter
 1399: @cindex outer interpreter
 1400: 
 1401: @c IMO this is too detailed and the pace is too slow for
 1402: @c an introduction.  If you know German, take a look at
 1403: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
 1404: @c to see how I do it - anton 
 1405: 
 1406: @c nac-> Where I have accepted your comments 100% and modified the text
 1407: @c accordingly, I have deleted your comments. Elsewhere I have added a
 1408: @c response like this to attempt to rationalise what I have done. Of
 1409: @c course, this is a very clumsy mechanism for something that would be
 1410: @c done far more efficiently over a beer. Please delete any dialogue
 1411: @c you consider closed.
 1412: 
 1413: When you invoke the Forth image, you will see a startup banner printed
 1414: and nothing else (if you have Gforth installed on your system, try
 1415: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
 1416: its command line interpreter, which is called the @dfn{Text Interpreter}
 1417: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
 1418: about the text interpreter as you read through this chapter, but
 1419: @pxref{The Text Interpreter} for more detail).
 1420: 
 1421: Although it's not obvious, Forth is actually waiting for your
 1422: input. Type a number and press the @key{RET} key:
 1423: 
 1424: @example
 1425: @kbd{45@key{RET}}  ok
 1426: @end example
 1427: 
 1428: Rather than give you a prompt to invite you to input something, the text
 1429: interpreter prints a status message @i{after} it has processed a line
 1430: of input. The status message in this case (``@code{ ok}'' followed by
 1431: carriage-return) indicates that the text interpreter was able to process
 1432: all of your input successfully. Now type something illegal:
 1433: 
 1434: @example
 1435: @kbd{qwer341@key{RET}}
 1436: :1: Undefined word
 1437: qwer341
 1438: ^^^^^^^
 1439: $400D2BA8 Bounce
 1440: $400DBDA8 no.extensions
 1441: @end example
 1442: 
 1443: The exact text, other than the ``Undefined word'' may differ slightly on
 1444: your system, but the effect is the same; when the text interpreter
 1445: detects an error, it discards any remaining text on a line, resets
 1446: certain internal state and prints an error message. @xref{Error
 1447: messages} for a detailed description of error messages.
 1448: 
 1449: The text interpreter waits for you to press carriage-return, and then
 1450: processes your input line. Starting at the beginning of the line, it
 1451: breaks the line into groups of characters separated by spaces. For each
 1452: group of characters in turn, it makes two attempts to do something:
 1453: 
 1454: @itemize @bullet
 1455: @item
 1456: @cindex name dictionary
 1457: It tries to treat it as a command. It does this by searching a @dfn{name
 1458: dictionary}. If the group of characters matches an entry in the name
 1459: dictionary, the name dictionary provides the text interpreter with
 1460: information that allows the text interpreter perform some actions. In
 1461: Forth jargon, we say that the group
 1462: @cindex word
 1463: @cindex definition
 1464: @cindex execution token
 1465: @cindex xt
 1466: of characters names a @dfn{word}, that the dictionary search returns an
 1467: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
 1468: word, and that the text interpreter executes the xt. Often, the terms
 1469: @dfn{word} and @dfn{definition} are used interchangeably.
 1470: @item
 1471: If the text interpreter fails to find a match in the name dictionary, it
 1472: tries to treat the group of characters as a number in the current number
 1473: base (when you start up Forth, the current number base is base 10). If
 1474: the group of characters legitimately represents a number, the text
 1475: interpreter pushes the number onto a stack (we'll learn more about that
 1476: in the next section).
 1477: @end itemize
 1478: 
 1479: If the text interpreter is unable to do either of these things with any
 1480: group of characters, it discards the group of characters and the rest of
 1481: the line, then prints an error message. If the text interpreter reaches
 1482: the end of the line without error, it prints the status message ``@code{ ok}''
 1483: followed by carriage-return.
 1484: 
 1485: This is the simplest command we can give to the text interpreter:
 1486: 
 1487: @example
 1488: @key{RET}  ok
 1489: @end example
 1490: 
 1491: The text interpreter did everything we asked it to do (nothing) without
 1492: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
 1493: command:
 1494: 
 1495: @example
 1496: @kbd{12 dup fred dup@key{RET}}
 1497: :1: Undefined word
 1498: 12 dup fred dup
 1499:        ^^^^
 1500: $400D2BA8 Bounce
 1501: $400DBDA8 no.extensions
 1502: @end example
 1503: 
 1504: When you press the carriage-return key, the text interpreter starts to
 1505: work its way along the line:
 1506: 
 1507: @itemize @bullet
 1508: @item
 1509: When it gets to the space after the @code{2}, it takes the group of
 1510: characters @code{12} and looks them up in the name
 1511: dictionary@footnote{We can't tell if it found them or not, but assume
 1512: for now that it did not}. There is no match for this group of characters
 1513: in the name dictionary, so it tries to treat them as a number. It is
 1514: able to do this successfully, so it puts the number, 12, ``on the stack''
 1515: (whatever that means).
 1516: @item
 1517: The text interpreter resumes scanning the line and gets the next group
 1518: of characters, @code{dup}. It looks it up in the name dictionary and
 1519: (you'll have to take my word for this) finds it, and executes the word
 1520: @code{dup} (whatever that means).
 1521: @item
 1522: Once again, the text interpreter resumes scanning the line and gets the
 1523: group of characters @code{fred}. It looks them up in the name
 1524: dictionary, but can't find them. It tries to treat them as a number, but
 1525: they don't represent any legal number.
 1526: @end itemize
 1527: 
 1528: At this point, the text interpreter gives up and prints an error
 1529: message. The error message shows exactly how far the text interpreter
 1530: got in processing the line. In particular, it shows that the text
 1531: interpreter made no attempt to do anything with the final character
 1532: group, @code{dup}, even though we have good reason to believe that the
 1533: text interpreter would have no problem looking that word up and
 1534: executing it a second time.
 1535: 
 1536: 
 1537: @comment ----------------------------------------------
 1538: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
 1539: @section Stacks, postfix notation and parameter passing
 1540: @cindex text interpreter
 1541: @cindex outer interpreter
 1542: 
 1543: In procedural programming languages (like C and Pascal), the
 1544: building-block of programs is the @dfn{function} or @dfn{procedure}. These
 1545: functions or procedures are called with @dfn{explicit parameters}. For
 1546: example, in C we might write:
 1547: 
 1548: @example
 1549: total = total + new_volume(length,height,depth);
 1550: @end example
 1551: 
 1552: @noindent
 1553: where new_volume is a function-call to another piece of code, and total,
 1554: length, height and depth are all variables. length, height and depth are
 1555: parameters to the function-call.
 1556: 
 1557: In Forth, the equivalent of the function or procedure is the
 1558: @dfn{definition} and parameters are implicitly passed between
 1559: definitions using a shared stack that is visible to the
 1560: programmer. Although Forth does support variables, the existence of the
 1561: stack means that they are used far less often than in most other
 1562: programming languages. When the text interpreter encounters a number, it
 1563: will place (@dfn{push}) it on the stack. There are several stacks (the
 1564: actual number is implementation-dependent ...) and the particular stack
 1565: used for any operation is implied unambiguously by the operation being
 1566: performed. The stack used for all integer operations is called the @dfn{data
 1567: stack} and, since this is the stack used most commonly, references to
 1568: ``the data stack'' are often abbreviated to ``the stack''.
 1569: 
 1570: The stacks have a last-in, first-out (LIFO) organisation. If you type:
 1571: 
 1572: @example
 1573: @kbd{1 2 3@key{RET}}  ok
 1574: @end example
 1575: 
 1576: Then this instructs the text interpreter to placed three numbers on the
 1577: (data) stack. An analogy for the behaviour of the stack is to take a
 1578: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
 1579: the table. The 3 was the last card onto the pile (``last-in'') and if
 1580: you take a card off the pile then, unless you're prepared to fiddle a
 1581: bit, the card that you take off will be the 3 (``first-out''). The
 1582: number that will be first-out of the stack is called the @dfn{top of
 1583: stack}, which
 1584: @cindex TOS definition
 1585: is often abbreviated to @dfn{TOS}.
 1586: 
 1587: To understand how parameters are passed in Forth, consider the
 1588: behaviour of the definition @code{+} (pronounced ``plus''). You will not
 1589: be surprised to learn that this definition performs addition. More
 1590: precisely, it adds two number together and produces a result. Where does
 1591: it get the two numbers from? It takes the top two numbers off the
 1592: stack. Where does it place the result? On the stack. You can act-out the
 1593: behaviour of @code{+} with your playing cards like this:
 1594: 
 1595: @itemize @bullet
 1596: @item
 1597: Pick up two cards from the stack on the table
 1598: @item
 1599: Stare at them intently and ask yourself ``what @i{is} the sum of these two
 1600: numbers''
 1601: @item
 1602: Decide that the answer is 5
 1603: @item
 1604: Shuffle the two cards back into the pack and find a 5
 1605: @item
 1606: Put a 5 on the remaining ace that's on the table.
 1607: @end itemize
 1608: 
 1609: If you don't have a pack of cards handy but you do have Forth running,
 1610: you can use the definition @code{.s} to show the current state of the stack,
 1611: without affecting the stack. Type:
 1612: 
 1613: @example
 1614: @kbd{clearstack 1 2 3@key{RET}} ok
 1615: @kbd{.s@key{RET}} <3> 1 2 3  ok
 1616: @end example
 1617: 
 1618: The text interpreter looks up the word @code{clearstack} and executes
 1619: it; it tidies up the stack and removes any entries that may have been
 1620: left on it by earlier examples. The text interpreter pushes each of the
 1621: three numbers in turn onto the stack. Finally, the text interpreter
 1622: looks up the word @code{.s} and executes it. The effect of executing
 1623: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
 1624: followed by a list of all the items on the stack; the item on the far
 1625: right-hand side is the TOS.
 1626: 
 1627: You can now type:
 1628: 
 1629: @example
 1630: @kbd{+ .s@key{RET}} <2> 1 5  ok
 1631: @end example
 1632: 
 1633: @noindent
 1634: which is correct; there are now 2 items on the stack and the result of
 1635: the addition is 5.
 1636: 
 1637: If you're playing with cards, try doing a second addition: pick up the
 1638: two cards, work out that their sum is 6, shuffle them into the pack,
 1639: look for a 6 and place that on the table. You now have just one item on
 1640: the stack. What happens if you try to do a third addition? Pick up the
 1641: first card, pick up the second card -- ah! There is no second card. This
 1642: is called a @dfn{stack underflow} and consitutes an error. If you try to
 1643: do the same thing with Forth it will report an error (probably a Stack
 1644: Underflow or an Invalid Memory Address error).
 1645: 
 1646: The opposite situation to a stack underflow is a @dfn{stack overflow},
 1647: which simply accepts that there is a finite amount of storage space
 1648: reserved for the stack. To stretch the playing card analogy, if you had
 1649: enough packs of cards and you piled the cards up on the table, you would
 1650: eventually be unable to add another card; you'd hit the ceiling. Gforth
 1651: allows you to set the maximum size of the stacks. In general, the only
 1652: time that you will get a stack overflow is because a definition has a
 1653: bug in it and is generating data on the stack uncontrollably.
 1654: 
 1655: There's one final use for the playing card analogy. If you model your
 1656: stack using a pack of playing cards, the maximum number of items on
 1657: your stack will be 52 (I assume you didn't use the Joker). The maximum
 1658: @i{value} of any item on the stack is 13 (the King). In fact, the only
 1659: possible numbers are positive integer numbers 1 through 13; you can't
 1660: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
 1661: think about some of the cards, you can accommodate different
 1662: numbers. For example, you could think of the Jack as representing 0,
 1663: the Queen as representing -1 and the King as representing -2. Your
 1664: @i{range} remains unchanged (you can still only represent a total of 13
 1665: numbers) but the numbers that you can represent are -2 through 10.
 1666: 
 1667: In that analogy, the limit was the amount of information that a single
 1668: stack entry could hold, and Forth has a similar limit. In Forth, the
 1669: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
 1670: implementation dependent and affects the maximum value that a stack
 1671: entry can hold. A Standard Forth provides a cell size of at least
 1672: 16-bits, and most desktop systems use a cell size of 32-bits.
 1673: 
 1674: Forth does not do any type checking for you, so you are free to
 1675: manipulate and combine stack items in any way you wish. A convenient way
 1676: of treating stack items is as 2's complement signed integers, and that
 1677: is what Standard words like @code{+} do. Therefore you can type:
 1678: 
 1679: @example
 1680: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
 1681: @end example
 1682: 
 1683: If you use numbers and definitions like @code{+} in order to turn Forth
 1684: into a great big pocket calculator, you will realise that it's rather
 1685: different from a normal calculator. Rather than typing 2 + 3 = you had
 1686: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
 1687: result). The terminology used to describe this difference is to say that
 1688: your calculator uses @dfn{Infix Notation} (parameters and operators are
 1689: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
 1690: operators are separate), also called @dfn{Reverse Polish Notation}.
 1691: 
 1692: Whilst postfix notation might look confusing to begin with, it has
 1693: several important advantages:
 1694: 
 1695: @itemize @bullet
 1696: @item
 1697: it is unambiguous
 1698: @item
 1699: it is more concise
 1700: @item
 1701: it fits naturally with a stack-based system
 1702: @end itemize
 1703: 
 1704: To examine these claims in more detail, consider these sums:
 1705: 
 1706: @example
 1707: 6 + 5 * 4 =
 1708: 4 * 5 + 6 =
 1709: @end example
 1710: 
 1711: If you're just learning maths or your maths is very rusty, you will
 1712: probably come up with the answer 44 for the first and 26 for the
 1713: second. If you are a bit of a whizz at maths you will remember the
 1714: @i{convention} that multiplication takes precendence over addition, and
 1715: you'd come up with the answer 26 both times. To explain the answer 26
 1716: to someone who got the answer 44, you'd probably rewrite the first sum
 1717: like this:
 1718: 
 1719: @example
 1720: 6 + (5 * 4) =
 1721: @end example
 1722: 
 1723: If what you really wanted was to perform the addition before the
 1724: multiplication, you would have to use parentheses to force it.
 1725: 
 1726: If you did the first two sums on a pocket calculator you would probably
 1727: get the right answers, unless you were very cautious and entered them using
 1728: these keystroke sequences:
 1729: 
 1730: 6 + 5 = * 4 =
 1731: 4 * 5 = + 6 =
 1732: 
 1733: Postfix notation is unambiguous because the order that the operators
 1734: are applied is always explicit; that also means that parentheses are
 1735: never required. The operators are @i{active} (the act of quoting the
 1736: operator makes the operation occur) which removes the need for ``=''.
 1737: 
 1738: The sum 6 + 5 * 4 can be written (in postfix notation) in two
 1739: equivalent ways:
 1740: 
 1741: @example
 1742: 6 5 4 * +      or:
 1743: 5 4 * 6 +
 1744: @end example
 1745: 
 1746: An important thing that you should notice about this notation is that
 1747: the @i{order} of the numbers does not change; if you want to subtract
 1748: 2 from 10 you type @code{10 2 -}.
 1749: 
 1750: The reason that Forth uses postfix notation is very simple to explain: it
 1751: makes the implementation extremely simple, and it follows naturally from
 1752: using the stack as a mechanism for passing parameters. Another way of
 1753: thinking about this is to realise that all Forth definitions are
 1754: @i{active}; they execute as they are encountered by the text
 1755: interpreter. The result of this is that the syntax of Forth is trivially
 1756: simple.
 1757: 
 1758: 
 1759: 
 1760: @comment ----------------------------------------------
 1761: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
 1762: @section Your first Forth definition
 1763: @cindex first definition
 1764: 
 1765: Until now, the examples we've seen have been trivial; we've just been
 1766: using Forth as a bigger-than-pocket calculator. Also, each calculation
 1767: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
 1768: again@footnote{That's not quite true. If you press the up-arrow key on
 1769: your keyboard you should be able to scroll back to any earlier command,
 1770: edit it and re-enter it.} In this section we'll see how to add new
 1771: words to Forth's vocabulary.
 1772: 
 1773: The easiest way to create a new word is to use a @dfn{colon
 1774: definition}. We'll define a few and try them out before worrying too
 1775: much about how they work. Try typing in these examples; be careful to
 1776: copy the spaces accurately:
 1777: 
 1778: @example
 1779: : add-two 2 + . ;
 1780: : greet ." Hello and welcome" ;
 1781: : demo 5 add-two ;
 1782: @end example
 1783: 
 1784: @noindent
 1785: Now try them out:
 1786: 
 1787: @example
 1788: @kbd{greet@key{RET}} Hello and welcome  ok
 1789: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
 1790: @kbd{4 add-two@key{RET}} 6  ok
 1791: @kbd{demo@key{RET}} 7  ok
 1792: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
 1793: @end example
 1794: 
 1795: The first new thing that we've introduced here is the pair of words
 1796: @code{:} and @code{;}. These are used to start and terminate a new
 1797: definition, respectively. The first word after the @code{:} is the name
 1798: for the new definition.
 1799: 
 1800: As you can see from the examples, a definition is built up of words that
 1801: have already been defined; Forth makes no distinction between
 1802: definitions that existed when you started the system up, and those that
 1803: you define yourself.
 1804: 
 1805: The examples also introduce the words @code{.} (dot), @code{."}
 1806: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
 1807: the stack and displays it. It's like @code{.s} except that it only
 1808: displays the top item of the stack and it is destructive; after it has
 1809: executed, the number is no longer on the stack. There is always one
 1810: space printed after the number, and no spaces before it. Dot-quote
 1811: defines a string (a sequence of characters) that will be printed when
 1812: the word is executed. The string can contain any printable characters
 1813: except @code{"}. A @code{"} has a special function; it is not a Forth
 1814: word but it acts as a delimiter (the way that delimiters work is
 1815: described in the next section). Finally, @code{dup} duplicates the value
 1816: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
 1817: 
 1818: We already know that the text interpreter searches through the
 1819: dictionary to locate names. If you've followed the examples earlier, you
 1820: will already have a definition called @code{add-two}. Lets try modifying
 1821: it by typing in a new definition:
 1822: 
 1823: @example
 1824: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
 1825: @end example
 1826: 
 1827: Forth recognised that we were defining a word that already exists, and
 1828: printed a message to warn us of that fact. Let's try out the new
 1829: definition:
 1830: 
 1831: @example
 1832: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
 1833: @end example
 1834: 
 1835: @noindent
 1836: All that we've actually done here, though, is to create a new
 1837: definition, with a particular name. The fact that there was already a
 1838: definition with the same name did not make any difference to the way
 1839: that the new definition was created (except that Forth printed a warning
 1840: message). The old definition of add-two still exists (try @code{demo}
 1841: again to see that this is true). Any new definition will use the new
 1842: definition of @code{add-two}, but old definitions continue to use the
 1843: version that already existed at the time that they were @code{compiled}.
 1844: 
 1845: Before you go on to the next section, try defining and redefining some
 1846: words of your own.
 1847: 
 1848: @comment ----------------------------------------------
 1849: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
 1850: @section How does that work?
 1851: @cindex parsing words
 1852: 
 1853: @c That's pretty deep (IMO way too deep) for an introduction. - anton
 1854: 
 1855: @c Is it a good idea to talk about the interpretation semantics of a
 1856: @c number? We don't have an xt to go along with it. - anton
 1857: 
 1858: @c Now that I have eliminated execution semantics, I wonder if it would not
 1859: @c be better to keep them (or add run-time semantics), to make it easier to
 1860: @c explain what compilation semantics usually does. - anton
 1861: 
 1862: @c nac-> I removed the term ``default compilation sematics'' from the
 1863: @c introductory chapter. Removing ``execution semantics'' was making
 1864: @c everything simpler to explain, then I think the use of this term made
 1865: @c everything more complex again. I replaced it with ``default
 1866: @c semantics'' (which is used elsewhere in the manual) by which I mean
 1867: @c ``a definition that has neither the immediate nor the compile-only
 1868: @c flag set''. I reworded big chunks of the ``how does that work''
 1869: @c section (and, unusually for me, I think I even made it shorter!).  See
 1870: @c what you think -- I know I have not addressed your primary concern
 1871: @c that it is too heavy-going for an introduction. From what I understood
 1872: @c of your course notes it looks as though they might be a good framework. 
 1873: @c Things that I've tried to capture here are some things that came as a
 1874: @c great revelation here when I first understood them. Also, I like the
 1875: @c fact that a very simple code example shows up almost all of the issues
 1876: @c that you need to understand to see how Forth works. That's unique and
 1877: @c worthwhile to emphasise.
 1878: 
 1879: Now we're going to take another look at the definition of @code{add-two}
 1880: from the previous section. From our knowledge of the way that the text
 1881: interpreter works, we would have expected this result when we tried to
 1882: define @code{add-two}:
 1883: 
 1884: @example
 1885: @kbd{: add-two 2 + . ;@key{RET}}
 1886:   ^^^^^^^
 1887: Error: Undefined word
 1888: @end example
 1889: 
 1890: The reason that this didn't happen is bound up in the way that @code{:}
 1891: works. The word @code{:} does two special things. The first special
 1892: thing that it does prevents the text interpreter from ever seeing the
 1893: characters @code{add-two}. The text interpreter uses a variable called
 1894: @cindex modifying >IN
 1895: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
 1896: input line. When it encounters the word @code{:} it behaves in exactly
 1897: the same way as it does for any other word; it looks it up in the name
 1898: dictionary, finds its xt and executes it. When @code{:} executes, it
 1899: looks at the input buffer, finds the word @code{add-two} and advances the
 1900: value of @code{>IN} to point past it. It then does some other stuff
 1901: associated with creating the new definition (including creating an entry
 1902: for @code{add-two} in the name dictionary). When the execution of @code{:}
 1903: completes, control returns to the text interpreter, which is oblivious
 1904: to the fact that it has been tricked into ignoring part of the input
 1905: line.
 1906: 
 1907: @cindex parsing words
 1908: Words like @code{:} -- words that advance the value of @code{>IN} and so
 1909: prevent the text interpreter from acting on the whole of the input line
 1910: -- are called @dfn{parsing words}.
 1911: 
 1912: @cindex @code{state} - effect on the text interpreter
 1913: @cindex text interpreter - effect of state
 1914: The second special thing that @code{:} does is change the value of a
 1915: variable called @code{state}, which affects the way that the text
 1916: interpreter behaves. When Gforth starts up, @code{state} has the value
 1917: 0, and the text interpreter is said to be @dfn{interpreting}. During a
 1918: colon definition (started with @code{:}), @code{state} is set to -1 and
 1919: the text interpreter is said to be @dfn{compiling}.
 1920: 
 1921: In this example, the text interpreter is compiling when it processes the
 1922: string ``@code{2 + . ;}''. It still breaks the string down into
 1923: character sequences in the same way. However, instead of pushing the
 1924: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
 1925: into the definition of @code{add-two} that will make the number @code{2} get
 1926: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
 1927: the behaviours of @code{+} and @code{.} are also compiled into the
 1928: definition.
 1929: 
 1930: One category of words don't get compiled. These so-called @dfn{immediate
 1931: words} get executed (performed @i{now}) regardless of whether the text
 1932: interpreter is interpreting or compiling. The word @code{;} is an
 1933: immediate word. Rather than being compiled into the definition, it
 1934: executes. Its effect is to terminate the current definition, which
 1935: includes changing the value of @code{state} back to 0.
 1936: 
 1937: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
 1938: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
 1939: definition.
 1940: 
 1941: In Forth, every word or number can be described in terms of two
 1942: properties:
 1943: 
 1944: @itemize @bullet
 1945: @item
 1946: @cindex interpretation semantics
 1947: Its @dfn{interpretation semantics} describe how it will behave when the
 1948: text interpreter encounters it in @dfn{interpret} state. The
 1949: interpretation semantics of a word are represented by an @dfn{execution
 1950: token}.
 1951: @item
 1952: @cindex compilation semantics
 1953: Its @dfn{compilation semantics} describe how it will behave when the
 1954: text interpreter encounters it in @dfn{compile} state. The compilation
 1955: semantics of a word are represented in an implementation-dependent way;
 1956: Gforth uses a @dfn{compilation token}.
 1957: @end itemize
 1958: 
 1959: @noindent
 1960: Numbers are always treated in a fixed way:
 1961: 
 1962: @itemize @bullet
 1963: @item
 1964: When the number is @dfn{interpreted}, its behaviour is to push the
 1965: number onto the stack.
 1966: @item
 1967: When the number is @dfn{compiled}, a piece of code is appended to the
 1968: current definition that pushes the number when it runs. (In other words,
 1969: the compilation semantics of a number are to postpone its interpretation
 1970: semantics until the run-time of the definition that it is being compiled
 1971: into.)
 1972: @end itemize
 1973: 
 1974: Words don't behave in such a regular way, but most have @i{default
 1975: semantics} which means that they behave like this:
 1976: 
 1977: @itemize @bullet
 1978: @item
 1979: The @dfn{interpretation semantics} of the word are to do something useful.
 1980: @item
 1981: The @dfn{compilation semantics} of the word are to append its
 1982: @dfn{interpretation semantics} to the current definition (so that its
 1983: run-time behaviour is to do something useful).
 1984: @end itemize
 1985: 
 1986: @cindex immediate words
 1987: The actual behaviour of any particular word can be controlled by using
 1988: the words @code{immediate} and @code{compile-only} when the word is
 1989: defined. These words set flags in the name dictionary entry of the most
 1990: recently defined word, and these flags are retrieved by the text
 1991: interpreter when it finds the word in the name dictionary.
 1992: 
 1993: A word that is marked as @dfn{immediate} has compilation semantics that
 1994: are identical to its interpretation semantics. In other words, it
 1995: behaves like this:
 1996: 
 1997: @itemize @bullet
 1998: @item
 1999: The @dfn{interpretation semantics} of the word are to do something useful.
 2000: @item
 2001: The @dfn{compilation semantics} of the word are to do something useful
 2002: (and actually the same thing); i.e., it is executed during compilation.
 2003: @end itemize
 2004: 
 2005: Marking a word as @dfn{compile-only} prohibits the text interpreter from
 2006: performing the interpretation semantics of the word directly; an attempt
 2007: to do so will generate an error. It is never necessary to use
 2008: @code{compile-only} (and it is not even part of ANS Forth, though it is
 2009: provided by many implementations) but it is good etiquette to apply it
 2010: to a word that will not behave correctly (and might have unexpected
 2011: side-effects) in interpret state. For example, it is only legal to use
 2012: the conditional word @code{IF} within a definition. If you forget this
 2013: and try to use it elsewhere, the fact that (in Gforth) it is marked as
 2014: @code{compile-only} allows the text interpreter to generate a helpful
 2015: error message rather than subjecting you to the consequences of your
 2016: folly.
 2017: 
 2018: This example shows the difference between an immediate and a
 2019: non-immediate word:
 2020: 
 2021: @example
 2022: : show-state state @@ . ;
 2023: : show-state-now show-state ; immediate
 2024: : word1 show-state ;
 2025: : word2 show-state-now ;
 2026: @end example
 2027: 
 2028: The word @code{immediate} after the definition of @code{show-state-now}
 2029: makes that word an immediate word. These definitions introduce a new
 2030: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
 2031: variable, and leaves it on the stack. Therefore, the behaviour of
 2032: @code{show-state} is to print a number that represents the current value
 2033: of @code{state}.
 2034: 
 2035: When you execute @code{word1}, it prints the number 0, indicating that
 2036: the system is interpreting. When the text interpreter compiled the
 2037: definition of @code{word1}, it encountered @code{show-state} whose
 2038: compilation semantics are to append its interpretation semantics to the
 2039: current definition. When you execute @code{word1}, it performs the
 2040: interpretation semantics of @code{show-state}.  At the time that @code{word1}
 2041: (and therefore @code{show-state}) are executed, the system is
 2042: interpreting.
 2043: 
 2044: When you pressed @key{RET} after entering the definition of @code{word2},
 2045: you should have seen the number -1 printed, followed by ``@code{
 2046: ok}''. When the text interpreter compiled the definition of
 2047: @code{word2}, it encountered @code{show-state-now}, an immediate word,
 2048: whose compilation semantics are therefore to perform its interpretation
 2049: semantics. It is executed straight away (even before the text
 2050: interpreter has moved on to process another group of characters; the
 2051: @code{;} in this example). The effect of executing it are to display the
 2052: value of @code{state} @i{at the time that the definition of}
 2053: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
 2054: system is compiling at this time. If you execute @code{word2} it does
 2055: nothing at all.
 2056: 
 2057: @cindex @code{."}, how it works
 2058: Before leaving the subject of immediate words, consider the behaviour of
 2059: @code{."} in the definition of @code{greet}, in the previous
 2060: section. This word is both a parsing word and an immediate word. Notice
 2061: that there is a space between @code{."} and the start of the text
 2062: @code{Hello and welcome}, but that there is no space between the last
 2063: letter of @code{welcome} and the @code{"} character. The reason for this
 2064: is that @code{."} is a Forth word; it must have a space after it so that
 2065: the text interpreter can identify it. The @code{"} is not a Forth word;
 2066: it is a @dfn{delimiter}. The examples earlier show that, when the string
 2067: is displayed, there is neither a space before the @code{H} nor after the
 2068: @code{e}. Since @code{."} is an immediate word, it executes at the time
 2069: that @code{greet} is defined. When it executes, its behaviour is to
 2070: search forward in the input line looking for the delimiter. When it
 2071: finds the delimiter, it updates @code{>IN} to point past the
 2072: delimiter. It also compiles some magic code into the definition of
 2073: @code{greet}; the xt of a run-time routine that prints a text string. It
 2074: compiles the string @code{Hello and welcome} into memory so that it is
 2075: available to be printed later. When the text interpreter gains control,
 2076: the next word it finds in the input stream is @code{;} and so it
 2077: terminates the definition of @code{greet}.
 2078: 
 2079: 
 2080: @comment ----------------------------------------------
 2081: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
 2082: @section Forth is written in Forth
 2083: @cindex structure of Forth programs
 2084: 
 2085: When you start up a Forth compiler, a large number of definitions
 2086: already exist. In Forth, you develop a new application using bottom-up
 2087: programming techniques to create new definitions that are defined in
 2088: terms of existing definitions. As you create each definition you can
 2089: test and debug it interactively.
 2090: 
 2091: If you have tried out the examples in this section, you will probably
 2092: have typed them in by hand; when you leave Gforth, your definitions will
 2093: be lost. You can avoid this by using a text editor to enter Forth source
 2094: code into a file, and then loading code from the file using
 2095: @code{include} (@xref{Forth source files}). A Forth source file is
 2096: processed by the text interpreter, just as though you had typed it in by
 2097: hand@footnote{Actually, there are some subtle differences -- see
 2098: @ref{The Text Interpreter}.}.
 2099: 
 2100: Gforth also supports the traditional Forth alternative to using text
 2101: files for program entry (@xref{Blocks}).
 2102: 
 2103: In common with many, if not most, Forth compilers, most of Gforth is
 2104: actually written in Forth. All of the @file{.fs} files in the
 2105: installation directory@footnote{For example,
 2106: @file{/usr/local/share/gforth...}} are Forth source files, which you can
 2107: study to see examples of Forth programming.
 2108: 
 2109: Gforth maintains a history file that records every line that you type to
 2110: the text interpreter. This file is preserved between sessions, and is
 2111: used to provide a command-line recall facility. If you enter long
 2112: definitions by hand, you can use a text editor to paste them out of the
 2113: history file into a Forth source file for reuse at a later time
 2114: (@pxref{Command-line editing} for more information).
 2115: 
 2116: 
 2117: @comment ----------------------------------------------
 2118: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
 2119: @section Review - elements of a Forth system
 2120: @cindex elements of a Forth system
 2121: 
 2122: To summarise this chapter:
 2123: 
 2124: @itemize @bullet
 2125: @item
 2126: Forth programs use @dfn{factoring} to break a problem down into small
 2127: fragments called @dfn{words} or @dfn{definitions}.
 2128: @item
 2129: Forth program development is an interactive process.
 2130: @item
 2131: The main command loop that accepts input, and controls both
 2132: interpretation and compilation, is called the @dfn{text interpreter}
 2133: (also known as the @dfn{outer interpreter}).
 2134: @item
 2135: Forth has a very simple syntax, consisting of words and numbers
 2136: separated by spaces or carriage-return characters. Any additional syntax
 2137: is imposed by @dfn{parsing words}.
 2138: @item
 2139: Forth uses a stack to pass parameters between words. As a result, it
 2140: uses postfix notation.
 2141: @item
 2142: To use a word that has previously been defined, the text interpreter
 2143: searches for the word in the @dfn{name dictionary}.
 2144: @item
 2145: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
 2146: @item
 2147: The text interpreter uses the value of @code{state} to select between
 2148: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
 2149: semantics} of a word that it encounters.
 2150: @item
 2151: The relationship between the @dfn{interpretation semantics} and
 2152: @dfn{compilation semantics} for a word
 2153: depend upon the way in which the word was defined (for example, whether
 2154: it is an @dfn{immediate} word).
 2155: @item
 2156: Forth definitions can be implemented in Forth (called @dfn{high-level
 2157: definitions}) or in some other way (usually a lower-level language and
 2158: as a result often called @dfn{low-level definitions}, @dfn{code
 2159: definitions} or @dfn{primitives}).
 2160: @item
 2161: Many Forth systems are implemented mainly in Forth.
 2162: @end itemize
 2163: 
 2164: 
 2165: @comment ----------------------------------------------
 2166: @node Where to go next,Exercises,Review - elements of a Forth system, Introduction
 2167: @section Where To Go Next
 2168: @cindex where to go next
 2169: 
 2170: Amazing as it may seem, if you have read (and understood) this far, you
 2171: know almost all the fundamentals about the inner workings of a Forth
 2172: system. You certainly know enough to be able to read and understand the
 2173: rest of this manual and the ANS Forth document, to learn more about the
 2174: facilities that Forth in general and Gforth in particular provide. Even
 2175: scarier, you know almost enough to implement your own Forth system.
 2176: However, that's not a good idea just yet... better to try writing some
 2177: programs in Gforth.
 2178: 
 2179: Forth has such a rich vocabulary that it can be hard to know where to
 2180: start in learning it. This section suggests a few sets of words that are
 2181: enough to write small but useful programs. Use the word index in this
 2182: document to learn more about each word, then try it out and try to write
 2183: small definitions using it. Start by experimenting with these words:
 2184: 
 2185: @itemize @bullet
 2186: @item
 2187: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
 2188: @item
 2189: Comparison: @code{MIN MAX =}
 2190: @item
 2191: Logic: @code{AND OR XOR NOT}
 2192: @item
 2193: Stack manipulation: @code{DUP DROP SWAP OVER}
 2194: @item
 2195: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
 2196: @item
 2197: Input/Output: @code{. ." EMIT CR KEY}
 2198: @item
 2199: Defining words: @code{: ; CREATE}
 2200: @item
 2201: Memory allocation words: @code{ALLOT ,}
 2202: @item
 2203: Tools: @code{SEE WORDS .S MARKER}
 2204: @end itemize
 2205: 
 2206: When you have mastered those, go on to:
 2207: 
 2208: @itemize @bullet
 2209: @item
 2210: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
 2211: @item
 2212: Memory access: @code{@@ !}
 2213: @end itemize
 2214: 
 2215: When you have mastered these, there's nothing for it but to read through
 2216: the whole of this manual and find out what you've missed.
 2217: 
 2218: @comment ----------------------------------------------
 2219: @node Exercises, ,Where to go next, Introduction
 2220: @section Exercises
 2221: @cindex exercises
 2222: 
 2223: TODO: provide a set of programming excercises linked into the stuff done
 2224: already and into other sections of the manual. Provide solutions to all
 2225: the exercises in a .fs file in the distribution.
 2226: 
 2227: @c Get some inspiration from Starting Forth and Kelly&Spies.
 2228: 
 2229: @c excercises:
 2230: @c 1. take inches and convert to feet and inches.
 2231: @c 2. take temperature and convert from fahrenheight to celcius;
 2232: @c    may need to care about symmetric vs floored??
 2233: @c 3. take input line and do character substitution
 2234: @c    to encipher or decipher
 2235: @c 4. as above but work on a file for in and out
 2236: @c 5. take input line and convert to pig-latin 
 2237: @c
 2238: @c thing of sets of things to exercise then come up with
 2239: @c problems that need those things.
 2240: 
 2241: 
 2242: @c ******************************************************************
 2243: @node Words, Error messages, Introduction, Top
 2244: @chapter Forth Words
 2245: @cindex words
 2246: 
 2247: @menu
 2248: * Notation::                    
 2249: * Comments::
 2250: * Boolean Flags::
 2251: * Arithmetic::                  
 2252: * Stack Manipulation::          
 2253: * Memory::                      
 2254: * Control Structures::          
 2255: * Defining Words::              
 2256: * The Text Interpreter::
 2257: * Tokens for Words::            
 2258: * Word Lists::                   
 2259: * Environmental Queries::
 2260: * Files::                       
 2261: * Blocks::                      
 2262: * Other I/O::                   
 2263: * Programming Tools::           
 2264: * Assembler and Code Words::    
 2265: * Threading Words::             
 2266: * Locals::                      
 2267: * Structures::                  
 2268: * Object-oriented Forth::       
 2269: * Passing Commands to the OS::
 2270: * Miscellaneous Words::
 2271: @end menu
 2272: 
 2273: @node Notation, Comments, Words, Words
 2274: @section Notation
 2275: @cindex notation of glossary entries
 2276: @cindex format of glossary entries
 2277: @cindex glossary notation format
 2278: @cindex word glossary entry format
 2279: 
 2280: The Forth words are described in this section in the glossary notation
 2281: that has become a de-facto standard for Forth texts, i.e.,
 2282: 
 2283: @format
 2284: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
 2285: @end format
 2286: @i{Description}
 2287: 
 2288: @table @var
 2289: @item word
 2290: The name of the word.
 2291: 
 2292: @item Stack effect
 2293: @cindex stack effect
 2294: The stack effect is written in the notation @code{@i{before} --
 2295: @i{after}}, where @i{before} and @i{after} describe the top of
 2296: stack entries before and after the execution of the word. The rest of
 2297: the stack is not touched by the word. The top of stack is rightmost,
 2298: i.e., a stack sequence is written as it is typed in. Note that Gforth
 2299: uses a separate floating point stack, but a unified stack
 2300: notation. Also, return stack effects are not shown in @i{stack
 2301: effect}, but in @i{Description}. The name of a stack item describes
 2302: the type and/or the function of the item. See below for a discussion of
 2303: the types.
 2304: 
 2305: All words have two stack effects: A compile-time stack effect and a
 2306: run-time stack effect. The compile-time stack-effect of most words is
 2307: @i{ -- }. If the compile-time stack-effect of a word deviates from
 2308: this standard behaviour, or the word does other unusual things at
 2309: compile time, both stack effects are shown; otherwise only the run-time
 2310: stack effect is shown.
 2311: 
 2312: @cindex pronounciation of words
 2313: @item pronunciation
 2314: How the word is pronounced.
 2315: 
 2316: @cindex wordset
 2317: @item wordset
 2318: The ANS Forth standard is divided into several word sets. A standard
 2319: system need not support all of them. Therefore, in theory, the fewer
 2320: word sets your program uses the more portable it will be. However, we
 2321: suspect that most ANS Forth systems on personal machines will feature
 2322: all word sets. Words that are not defined in ANS Forth have
 2323: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
 2324: describes words that will work in future releases of Gforth;
 2325: @code{gforth-internal} words are more volatile. Environmental query
 2326: strings are also displayed like words; you can recognize them by the
 2327: @code{environment} in the word set field.
 2328: 
 2329: @item Description
 2330: A description of the behaviour of the word.
 2331: @end table
 2332: 
 2333: @cindex types of stack items
 2334: @cindex stack item types
 2335: The type of a stack item is specified by the character(s) the name
 2336: starts with:
 2337: 
 2338: @table @code
 2339: @item f
 2340: @cindex @code{f}, stack item type
 2341: Boolean flags, i.e. @code{false} or @code{true}.
 2342: @item c
 2343: @cindex @code{c}, stack item type
 2344: Char
 2345: @item w
 2346: @cindex @code{w}, stack item type
 2347: Cell, can contain an integer or an address
 2348: @item n
 2349: @cindex @code{n}, stack item type
 2350: signed integer
 2351: @item u
 2352: @cindex @code{u}, stack item type
 2353: unsigned integer
 2354: @item d
 2355: @cindex @code{d}, stack item type
 2356: double sized signed integer
 2357: @item ud
 2358: @cindex @code{ud}, stack item type
 2359: double sized unsigned integer
 2360: @item r
 2361: @cindex @code{r}, stack item type
 2362: Float (on the FP stack)
 2363: @item a-
 2364: @cindex @code{a_}, stack item type
 2365: Cell-aligned address
 2366: @item c-
 2367: @cindex @code{c_}, stack item type
 2368: Char-aligned address (note that a Char may have two bytes in Windows NT)
 2369: @item f-
 2370: @cindex @code{f_}, stack item type
 2371: Float-aligned address
 2372: @item df-
 2373: @cindex @code{df_}, stack item type
 2374: Address aligned for IEEE double precision float
 2375: @item sf-
 2376: @cindex @code{sf_}, stack item type
 2377: Address aligned for IEEE single precision float
 2378: @item xt
 2379: @cindex @code{xt}, stack item type
 2380: Execution token, same size as Cell
 2381: @item wid
 2382: @cindex @code{wid}, stack item type
 2383: Word list ID, same size as Cell
 2384: @item f83name
 2385: @cindex @code{f83name}, stack item type
 2386: Pointer to a name structure
 2387: @item "
 2388: @cindex @code{"}, stack item type
 2389: string in the input stream (not on the stack). The terminating character
 2390: is a blank by default. If it is not a blank, it is shown in @code{<>}
 2391: quotes.
 2392: @end table
 2393: 
 2394: @node Comments, Boolean Flags, Notation, Words
 2395: @section Comments
 2396: @cindex comments
 2397: 
 2398: Forth supports two styles of comment; the traditional @i{in-line} comment,
 2399: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
 2400: 
 2401: 
 2402: doc-(
 2403: doc-\
 2404: doc-\G
 2405: 
 2406: 
 2407: @node Boolean Flags, Arithmetic, Comments, Words
 2408: @section Boolean Flags
 2409: @cindex Boolean flags
 2410: 
 2411: A Boolean flag is cell-sized. A cell with all bits clear represents the
 2412: flag @code{false} and a flag with all bits set represents the flag
 2413: @code{true}. Words that check a flag (for example, @code{IF}) will treat
 2414: a cell that has @i{any} bit set as @code{true}.
 2415: 
 2416: 
 2417: doc-true
 2418: doc-false
 2419: doc-on
 2420: doc-off
 2421: 
 2422: 
 2423: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
 2424: @section Arithmetic
 2425: @cindex arithmetic words
 2426: 
 2427: @cindex division with potentially negative operands
 2428: Forth arithmetic is not checked, i.e., you will not hear about integer
 2429: overflow on addition or multiplication, you may hear about division by
 2430: zero if you are lucky. The operator is written after the operands, but
 2431: the operands are still in the original order. I.e., the infix @code{2-1}
 2432: corresponds to @code{2 1 -}. Forth offers a variety of division
 2433: operators. If you perform division with potentially negative operands,
 2434: you do not want to use @code{/} or @code{/mod} with its undefined
 2435: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
 2436: former, @pxref{Mixed precision}).
 2437: @comment TODO discuss the different division forms and the std approach
 2438: 
 2439: @menu
 2440: * Single precision::            
 2441: * Bitwise operations::          
 2442: * Double precision::            Double-cell integer arithmetic
 2443: * Numeric comparison::
 2444: * Mixed precision::             Operations with single and double-cell integers
 2445: * Floating Point::              
 2446: @end menu
 2447: 
 2448: @node Single precision, Bitwise operations, Arithmetic, Arithmetic
 2449: @subsection Single precision
 2450: @cindex single precision arithmetic words
 2451: 
 2452: By default, numbers in Forth are single-precision integers that are 1
 2453: cell in size. They can be signed or unsigned, depending upon how you
 2454: treat them. @xref{Number Conversion} for the rules used by the text
 2455: interpreter for recognising single-precision integers.
 2456: 
 2457: 
 2458: doc-+
 2459: doc-1+
 2460: doc--
 2461: doc-1-
 2462: doc-*
 2463: doc-/
 2464: doc-mod
 2465: doc-/mod
 2466: doc-negate
 2467: doc-abs
 2468: doc-min
 2469: doc-max
 2470: doc-d>s
 2471: doc-floored
 2472: 
 2473: 
 2474: @node Bitwise operations, Double precision, Single precision, Arithmetic
 2475: @subsection Bitwise operations
 2476: @cindex bitwise operation words
 2477: 
 2478: 
 2479: doc-and
 2480: doc-or
 2481: doc-xor
 2482: doc-invert
 2483: doc-lshift
 2484: doc-rshift
 2485: doc-2*
 2486: doc-d2*
 2487: doc-2/
 2488: doc-d2/
 2489: 
 2490: 
 2491: @node Double precision, Numeric comparison, Bitwise operations, Arithmetic
 2492: @subsection Double precision
 2493: @cindex double precision arithmetic words
 2494: 
 2495: @xref{Number Conversion} for the rules used by the text interpreter for
 2496: recognising double-precision integers.
 2497: 
 2498: A double precision number is represented by a cell pair, with the most
 2499: significant cell at the TOS. It is trivial to convert an unsigned
 2500: single to an (unsigned) double; simply push a @code{0} onto the
 2501: TOS. Since numbers are represented by Gforth using 2's complement
 2502: arithmetic, converting a signed single to a (signed) double requires
 2503: sign-extension across the most significant cell. This can be achieved
 2504: using @code{s>d}. The moral of the story is that you cannot convert a
 2505: number without knowing whether it represents an unsigned or a
 2506: signed number.
 2507: 
 2508: 
 2509: doc-s>d
 2510: doc-d+
 2511: doc-d-
 2512: doc-dnegate
 2513: doc-dabs
 2514: doc-dmin
 2515: doc-dmax
 2516: 
 2517: 
 2518: @node Numeric comparison, Mixed precision, Double precision, Arithmetic
 2519: @subsection Numeric comparison
 2520: @cindex numeric comparison words
 2521: 
 2522: 
 2523: doc-<
 2524: doc-<=
 2525: doc-<>
 2526: doc-=
 2527: doc->
 2528: doc->=
 2529: 
 2530: doc-0<
 2531: doc-0<=
 2532: doc-0<>
 2533: doc-0=
 2534: doc-0>
 2535: doc-0>=
 2536: 
 2537: doc-u<
 2538: doc-u<=
 2539: @c u<> and u= exist but are the same as <> and =
 2540: @c doc-u<>
 2541: @c doc-u=
 2542: doc-u>
 2543: doc-u>=
 2544: 
 2545: doc-within
 2546: 
 2547: doc-d<
 2548: doc-d<=
 2549: doc-d<>
 2550: doc-d=
 2551: doc-d>
 2552: doc-d>=
 2553: 
 2554: doc-d0<
 2555: doc-d0<=
 2556: doc-d0<>
 2557: doc-d0=
 2558: doc-d0>
 2559: doc-d0>=
 2560: 
 2561: doc-du<
 2562: doc-du<=
 2563: @c du<> and du= exist but are the same as d<> and d=
 2564: @c doc-du<>
 2565: @c doc-du=
 2566: doc-du>
 2567: doc-du>=
 2568: 
 2569: 
 2570: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
 2571: @subsection Mixed precision
 2572: @cindex mixed precision arithmetic words
 2573: 
 2574: 
 2575: doc-m+
 2576: doc-*/
 2577: doc-*/mod
 2578: doc-m*
 2579: doc-um*
 2580: doc-m*/
 2581: doc-um/mod
 2582: doc-fm/mod
 2583: doc-sm/rem
 2584: 
 2585: 
 2586: @node Floating Point,  , Mixed precision, Arithmetic
 2587: @subsection Floating Point
 2588: @cindex floating point arithmetic words
 2589: 
 2590: @xref{Number Conversion} for the rules used by the text interpreter for
 2591: recognising floating-point numbers.
 2592: 
 2593: Gforth has a separate floating point
 2594: stack, but the documentation uses the unified notation.
 2595: 
 2596: @cindex floating-point arithmetic, pitfalls
 2597: Floating point numbers have a number of unpleasant surprises for the
 2598: unwary (e.g., floating point addition is not associative) and even a few
 2599: for the wary. You should not use them unless you know what you are doing
 2600: or you don't care that the results you get are totally bogus. If you
 2601: want to learn about the problems of floating point numbers (and how to
 2602: avoid them), you might start with @cite{David Goldberg, What Every
 2603: Computer Scientist Should Know About Floating-Point Arithmetic, ACM
 2604: Computing Surveys 23(1):5@minus{}48, March 1991}
 2605: (@url{http://www.validgh.com/goldberg/paper.ps}).
 2606: 
 2607: 
 2608: doc-d>f
 2609: doc-f>d
 2610: doc-f+
 2611: doc-f-
 2612: doc-f*
 2613: doc-f/
 2614: doc-fnegate
 2615: doc-fabs
 2616: doc-fmax
 2617: doc-fmin
 2618: doc-floor
 2619: doc-fround
 2620: doc-f**
 2621: doc-fsqrt
 2622: doc-fexp
 2623: doc-fexpm1
 2624: doc-fln
 2625: doc-flnp1
 2626: doc-flog
 2627: doc-falog
 2628: doc-f2*
 2629: doc-f2/
 2630: doc-1/f
 2631: doc-precision
 2632: doc-set-precision
 2633: 
 2634: @cindex angles in trigonometric operations
 2635: @cindex trigonometric operations
 2636: Angles in floating point operations are given in radians (a full circle
 2637: has 2 pi radians).
 2638: 
 2639: doc-fsin
 2640: doc-fcos
 2641: doc-fsincos
 2642: doc-ftan
 2643: doc-fasin
 2644: doc-facos
 2645: doc-fatan
 2646: doc-fatan2
 2647: doc-fsinh
 2648: doc-fcosh
 2649: doc-ftanh
 2650: doc-fasinh
 2651: doc-facosh
 2652: doc-fatanh
 2653: doc-pi
 2654: 
 2655: @cindex equality of floats
 2656: @cindex floating-point comparisons
 2657: One particular problem with floating-point arithmetic is that comparison
 2658: for equality often fails when you would expect it to succeed.  For this
 2659: reason approximate equality is often preferred (but you still have to
 2660: know what you are doing).  The comparison words are:
 2661: 
 2662: doc-f~rel
 2663: doc-f~abs
 2664: doc-f=
 2665: doc-f~
 2666: doc-f<>
 2667: 
 2668: doc-f<
 2669: doc-f<=
 2670: doc-f>
 2671: doc-f>=
 2672: 
 2673: doc-f0<
 2674: doc-f0<=
 2675: doc-f0<>
 2676: doc-f0=
 2677: doc-f0>
 2678: doc-f0>=
 2679: 
 2680: 
 2681: @node Stack Manipulation, Memory, Arithmetic, Words
 2682: @section Stack Manipulation
 2683: @cindex stack manipulation words
 2684: 
 2685: @cindex floating-point stack in the standard
 2686: Gforth maintains a number of separate stacks:
 2687: 
 2688: @cindex data stack
 2689: @cindex parameter stack
 2690: @itemize @bullet
 2691: @item
 2692: A data stack (also known as the @dfn{parameter stack}) -- for
 2693: characters, cells, addresses, and double cells.
 2694: 
 2695: @cindex floating-point stack
 2696: @item
 2697: A floating point stack -- for holding floating point (FP) numbers.
 2698: 
 2699: @cindex return stack
 2700: @item
 2701: A return stack -- for holding the return addresses of colon
 2702: definitions and other (non-FP) data.
 2703: 
 2704: @cindex locals stack
 2705: @item
 2706: A locals stack -- for holding local variables.
 2707: @end itemize
 2708: 
 2709: @menu
 2710: * Data stack::                  
 2711: * Floating point stack::        
 2712: * Return stack::                
 2713: * Locals stack::                
 2714: * Stack pointer manipulation::  
 2715: @end menu
 2716: 
 2717: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
 2718: @subsection Data stack
 2719: @cindex data stack manipulation words
 2720: @cindex stack manipulations words, data stack
 2721: 
 2722: 
 2723: doc-drop
 2724: doc-nip
 2725: doc-dup
 2726: doc-over
 2727: doc-tuck
 2728: doc-swap
 2729: doc-pick
 2730: doc-rot
 2731: doc--rot
 2732: doc-?dup
 2733: doc-roll
 2734: doc-2drop
 2735: doc-2nip
 2736: doc-2dup
 2737: doc-2over
 2738: doc-2tuck
 2739: doc-2swap
 2740: doc-2rot
 2741: 
 2742: 
 2743: @node Floating point stack, Return stack, Data stack, Stack Manipulation
 2744: @subsection Floating point stack
 2745: @cindex floating-point stack manipulation words
 2746: @cindex stack manipulation words, floating-point stack
 2747: 
 2748: Whilst every sane Forth has a separate floating-point stack, it is not
 2749: strictly required; an ANS Forth system could theoretically keep
 2750: floating-point numbers on the data stack. As an additional difficulty,
 2751: you don't know how many cells a floating-point number takes. It is
 2752: reportedly possible to write words in a way that they work also for a
 2753: unified stack model, but we do not recommend trying it. Instead, just
 2754: say that your program has an environmental dependency on a separate
 2755: floating-point stack.
 2756: 
 2757: doc-floating-stack
 2758: 
 2759: doc-fdrop
 2760: doc-fnip
 2761: doc-fdup
 2762: doc-fover
 2763: doc-ftuck
 2764: doc-fswap
 2765: doc-fpick
 2766: doc-frot
 2767: 
 2768: 
 2769: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
 2770: @subsection Return stack
 2771: @cindex return stack manipulation words
 2772: @cindex stack manipulation words, return stack
 2773: 
 2774: @cindex return stack and locals
 2775: @cindex locals and return stack
 2776: A Forth system is allowed to keep local variables on the
 2777: return stack. This is reasonable, as local variables usually eliminate
 2778: the need to use the return stack explicitly. So, if you want to produce
 2779: a standard compliant program and you are using local variables in a
 2780: word, forget about return stack manipulations in that word (refer to the
 2781: standard document for the exact rules).
 2782: 
 2783: doc->r
 2784: doc-r>
 2785: doc-r@
 2786: doc-rdrop
 2787: doc-2>r
 2788: doc-2r>
 2789: doc-2r@
 2790: doc-2rdrop
 2791: 
 2792: 
 2793: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
 2794: @subsection Locals stack
 2795: 
 2796: @comment TODO
 2797: 
 2798: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
 2799: @subsection Stack pointer manipulation
 2800: @cindex stack pointer manipulation words
 2801: 
 2802: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
 2803: doc-sp0
 2804: doc-sp@
 2805: doc-sp!
 2806: doc-fp0
 2807: doc-fp@
 2808: doc-fp!
 2809: doc-rp0
 2810: doc-rp@
 2811: doc-rp!
 2812: doc-lp0
 2813: doc-lp@
 2814: doc-lp!
 2815: 
 2816: 
 2817: @node Memory, Control Structures, Stack Manipulation, Words
 2818: @section Memory
 2819: @cindex memory words
 2820: 
 2821: @menu
 2822: * Memory model::                
 2823: * Dictionary allocation::       
 2824: * Heap Allocation::             
 2825: * Memory Access::               
 2826: * Address arithmetic::          
 2827: * Memory Blocks::               
 2828: @end menu
 2829: 
 2830: @node Memory model, Dictionary allocation, Memory, Memory
 2831: @subsection ANS Forth and Gforth memory models
 2832: 
 2833: @c The ANS Forth description is a mess (e.g., is the heap part of
 2834: @c the dictionary?), so let's not stick to closely with it.
 2835: 
 2836: ANS Forth considers a Forth system as consisting of several memories, of
 2837: which only @dfn{data space} is managed and accessible with the memory
 2838: words.  Memory not necessarily in data space includes the stacks, the
 2839: code (called code space) and the headers (called name space). In Gforth
 2840: everything is in data space, but the code for the primitives is usually
 2841: read-only.
 2842: 
 2843: Data space is divided into a number of areas: The (data space portion of
 2844: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
 2845: refer to the search data structure embodied in word lists and headers,
 2846: because it is used for looking up names, just as you would in a
 2847: conventional dictionary.}, the heap, and a number of system-allocated
 2848: buffers.
 2849: 
 2850: In ANS Forth data space is also divided into contiguous regions.  You
 2851: can only use address arithmetic within a contiguous region, not between
 2852: them.  Usually each allocation gives you one contiguous region, but the
 2853: dictionary allocation words have additional rules (@pxref{Dictionary
 2854: allocation}).
 2855: 
 2856: Gforth provides one big address space, and address arithmetic can be
 2857: performed between any addresses. However, in the dictionary headers or
 2858: code are interleaved with data, so almost the only contiguous data space
 2859: regions there are those described by ANS Forth as contiguous; but you
 2860: can be sure that the dictionary is allocated towards increasing
 2861: addresses even between contiguous regions.  The memory order of
 2862: allocations in the heap is platform-dependent (and possibly different
 2863: from one run to the next).
 2864: 
 2865: @subsubsection ANS Forth dictionary details
 2866: 
 2867: This section is just informative, you can skip it if you are in a hurry.
 2868: 
 2869: When you create a colon definition, the text interpreter compiles the
 2870: code for the definition into the code space and compiles the name
 2871: of the definition into the header space, together with other
 2872: information about the definition (such as its execution token).
 2873: 
 2874: When you create a variable, the execution of @code{Variable} will
 2875: compile some code, assign one cell in data space, and compile the name
 2876: of the variable into the header space.
 2877: 
 2878: @cindex memory regions - relationship between them
 2879: ANS Forth does not specify the relationship between the three memory
 2880: regions, and specifies that a Standard program must not access code or
 2881: data space directly -- it may only access data space directly. In
 2882: addition, the Standard defines what relationships you may and may not
 2883: rely on when allocating regions in data space. These constraints are
 2884: simply a reflection of the many diverse techniques that are used to
 2885: implement Forth systems; understanding and following the requirements of
 2886: the Standard allows you to write portable programs -- programs that run
 2887: in the same way on any of these diverse systems. Another way of looking
 2888: at this is to say that ANS Forth was designed to permit compliant Forth
 2889: systems to be implemented in many diverse ways.
 2890: 
 2891: @cindex memory regions - how they are assigned
 2892: Here are some examples of ways in which name, code and data spaces
 2893: might be assigned in different Forth implementations:
 2894: 
 2895: @itemize @bullet
 2896: @item
 2897: For a Forth system that runs from RAM under a general-purpose operating
 2898: system, it can be convenient to interleave name, code and data spaces in
 2899: a single contiguous memory region. This organisation can be
 2900: memory-efficient (for example, because the relationship between the name
 2901: dictionary entry and the associated code space entry can be
 2902: implicit, rather than requiring an explicit memory pointer to reference
 2903: from the header space and the code space). This is the
 2904: organisation used by Gforth, as this example@footnote{The addresses
 2905: in the example have been truncated to fit it onto the page, and the
 2906: addresses and data shown will not match the output from your system} shows:
 2907: @example
 2908: hex
 2909: variable fred 123456 fred !
 2910: variable jim abcd jim !
 2911: : foo + / - ;
 2912: ' fred 10 - 50 dump 
 2913: ..80: 5C 46 0E 40  84 66 72 65 - 64 20 20 20  20 20 20 20  \F.@.fred       
 2914: ..90: D0 9B 04 08  00 00 00 00 - 56 34 12 00  80 46 0E 40  ........V4...F.@
 2915: ..A0: 83 6A 69 6D  20 20 20 20 - D0 9B 04 08  00 00 00 00  .jim    ........
 2916: ..B0: CD AB 00 00  9C 46 0E 40 - 83 66 6F 6F  20 20 20 20  .....F.@.foo    
 2917: ..C0: 80 9B 04 08  00 00 00 00 - E4 2E 05 08  0C 2F 05 08  ............./..
 2918: @end example
 2919: 
 2920: @item
 2921: For a high-performance system running on a modern RISC processor with a
 2922: modified Harvard architecture (one that has a unified main memory but
 2923: separate instruction and data caches), it is desirable to separate
 2924: processor instructions from processor data. This encourages a high cache
 2925: density and therefore a high cache hit rate. The Forth code space
 2926: is not necessarily made up entirely of processor instructions; its
 2927: nature is dependent upon the Forth implementation. 
 2928: 
 2929: @item
 2930: A Forth compiler that runs on a segmented 8086 processor could be
 2931: designed to interleave the name, code and data spaces within a single
 2932: 64Kbyte segment. A more common implementation choice is to use a
 2933: separate 64Kbyte segment for each region, which provides more memory
 2934: overall but provides an address map in which only the data space is
 2935: accessible.
 2936: 
 2937: @item
 2938: Microprocessors exist that run Forth (or many of the primitives required
 2939: to implement the Forth virtual machine efficiently) directly. On these
 2940: processors, the relationship between name, code and data spaces may be
 2941: imposed as a side-effect of the architecture of the processor.
 2942: 
 2943: @item
 2944: A Forth compiler that executes from ROM on an embedded system needs its
 2945: data space separated from the name and code spaces so that the data
 2946: space can be mapped to a RAM area.
 2947: 
 2948: @item 
 2949: A Forth compiler that runs on an embedded system may have a requirement
 2950: for a small memory footprint. On such a system it can be useful to
 2951: separate the header space from the data and code spaces; once the
 2952: application has been compiled, the header space is no longer
 2953: required@footnote{more strictly speaking, most applications can be
 2954: designed so that this is the case}. The header space can be deleted
 2955: entirely, or could be stored in memory on a remote @i{host} system for
 2956: debug and development purposes. In the latter case, the compiler running
 2957: on the @i{target} system could implement a protocol across a
 2958: communication link that would allow it to interrogate the header space.
 2959: @end itemize
 2960: 
 2961: @node Dictionary allocation, Heap Allocation, Memory model, Memory
 2962: @subsection Dictionary allocation
 2963: @cindex reserving data space
 2964: @cindex data space - reserving some
 2965: 
 2966: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
 2967: you want to deallocate X, you also deallocate everything
 2968: allocated after X.
 2969: 
 2970: The allocations using the words below are contiguous and grow the region
 2971: towards increasing addresses.  Other words that allocate dictionary
 2972: memory of any kind (i.e., defining words including @code{:noname}) end
 2973: the contiguous region and start a new one.
 2974: 
 2975: In ANS Forth only @code{create}d words are guaranteed to produce an
 2976: address that is the start of the following contiguous region.  In
 2977: particular, the cell allocated by @code{variable} is not guaranteed to
 2978: be contiguous with following @code{allot}ed memory.
 2979: 
 2980: You can deallocate memory by using @code{allot} with a negative argument
 2981: (with some restrictions, see @code{allot}). For larger deallocations use
 2982: @code{marker}.
 2983: 
 2984: 
 2985: doc-here
 2986: doc-unused
 2987: doc-allot
 2988: doc-c,
 2989: doc-f,
 2990: doc-,
 2991: doc-2,
 2992: @cindex user space
 2993: doc-udp
 2994: doc-uallot
 2995: 
 2996: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
 2997: course you should allocate memory in an aligned way, too. I.e., before
 2998: allocating allocating a cell, @code{here} must be cell-aligned, etc.
 2999: The words below align @code{here} if it is not already.  Basically it is
 3000: only already aligned for a type, if the last allocation was a multiple
 3001: of the size of this type and if @code{here} was aligned for this type
 3002: before.
 3003: 
 3004: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
 3005: ANS Forth (@code{maxalign}ed in Gforth).
 3006: 
 3007: doc-align
 3008: doc-falign
 3009: doc-sfalign
 3010: doc-dfalign
 3011: doc-maxalign
 3012: doc-cfalign
 3013: 
 3014: 
 3015: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
 3016: @subsection Heap allocation
 3017: @cindex heap allocation
 3018: @cindex dynamic allocation of memory
 3019: @cindex memory-allocation word set
 3020: 
 3021: Heap allocation supports deallocation of allocated memory in any
 3022: order. Dictionary allocation is not affected by it (i.e., it does not
 3023: end a contiguous region). In Gforth, these words are implemented using
 3024: the standard C library calls malloc(), free() and resize().
 3025: 
 3026: doc-allocate
 3027: doc-free
 3028: doc-resize
 3029: 
 3030: 
 3031: @node Memory Access, Address arithmetic, Heap Allocation, Memory
 3032: @subsection Memory Access
 3033: @cindex memory access words
 3034: 
 3035: 
 3036: doc-@
 3037: doc-!
 3038: doc-+!
 3039: doc-c@
 3040: doc-c!
 3041: doc-2@
 3042: doc-2!
 3043: doc-f@
 3044: doc-f!
 3045: doc-sf@
 3046: doc-sf!
 3047: doc-df@
 3048: doc-df!
 3049: 
 3050: @node Address arithmetic, Memory Blocks, Memory Access, Memory
 3051: @subsection Address arithmetic
 3052: @cindex address arithmetic words
 3053: 
 3054: Address arithmetic is the foundation on which data structures like
 3055: arrays, records (@pxref{Structures}) and objects (@pxref{Object-oriented
 3056: Forth}) are built.
 3057: 
 3058: ANS Forth does not specify the sizes of the data types. Instead, it
 3059: offers a number of words for computing sizes and doing address
 3060: arithmetic. Address arithmetic is performed in terms of address units
 3061: (aus); on most systems the address unit is one byte. Note that a
 3062: character may have more than one au, so @code{chars} is no noop (on
 3063: systems where it is a noop, it compiles to nothing).
 3064: 
 3065: @cindex alignment of addresses for types
 3066: ANS Forth also defines words for aligning addresses for specific
 3067: types. Many computers require that accesses to specific data types
 3068: must only occur at specific addresses; e.g., that cells may only be
 3069: accessed at addresses divisible by 4. Even if a machine allows unaligned
 3070: accesses, it can usually perform aligned accesses faster. 
 3071: 
 3072: For the performance-conscious: alignment operations are usually only
 3073: necessary during the definition of a data structure, not during the
 3074: (more frequent) accesses to it.
 3075: 
 3076: ANS Forth defines no words for character-aligning addresses. This is not
 3077: an oversight, but reflects the fact that addresses that are not
 3078: char-aligned have no use in the standard and therefore will not be
 3079: created.
 3080: 
 3081: @cindex @code{CREATE} and alignment
 3082: ANS Forth guarantees that addresses returned by @code{CREATE}d words
 3083: are cell-aligned; in addition, Gforth guarantees that these addresses
 3084: are aligned for all purposes.
 3085: 
 3086: Note that the ANS Forth word @code{char} has nothing to do with address
 3087: arithmetic.
 3088: 
 3089: 
 3090: doc-chars
 3091: doc-char+
 3092: doc-cells
 3093: doc-cell+
 3094: doc-cell
 3095: doc-aligned
 3096: doc-floats
 3097: doc-float+
 3098: doc-float
 3099: doc-faligned
 3100: doc-sfloats
 3101: doc-sfloat+
 3102: doc-sfaligned
 3103: doc-dfloats
 3104: doc-dfloat+
 3105: doc-dfaligned
 3106: doc-maxaligned
 3107: doc-cfaligned
 3108: doc-address-unit-bits
 3109: 
 3110: 
 3111: @node Memory Blocks,  , Address arithmetic, Memory
 3112: @subsection Memory Blocks
 3113: @cindex memory block words
 3114: @cindex character strings - moving and copying
 3115: 
 3116: Memory blocks often represent character strings; @xref{String Formats}
 3117: for ways of storing character strings in memory. @xref{Displaying
 3118: characters and strings} for other string-processing words.
 3119: 
 3120: Some of these words work on address units. Others work on character
 3121: units (increments of @code{CHAR}), and expect a @code{CHAR}-aligned
 3122: address. Choose the correct operation depending upon your data type.
 3123: 
 3124: When copying characters between overlapping memory regions, choose
 3125: carefully between @code{cmove} and @code{cmove>}.
 3126: 
 3127: You can only use any of these words @i{portably} to access data space.
 3128: 
 3129: @comment TODO - think the naming of the arguments is wrong for move
 3130: @comment well, really it seems to be the Standard that's wrong; it
 3131: @comment describes MOVE as a word that requires a CELL-aligned source
 3132: @comment and destination address but a xtranfer count that need not
 3133: @comment be a multiple of CELL.
 3134: 
 3135: doc-move
 3136: doc-erase
 3137: doc-cmove
 3138: doc-cmove>
 3139: doc-fill
 3140: doc-blank
 3141: doc-compare
 3142: doc-search
 3143: doc--trailing
 3144: doc-/string
 3145: 
 3146: 
 3147: @comment TODO examples
 3148: 
 3149: 
 3150: @node Control Structures, Defining Words, Memory, Words
 3151: @section Control Structures
 3152: @cindex control structures
 3153: 
 3154: Control structures in Forth cannot be used interpretively, only in a
 3155: colon definition@footnote{To be precise, they have no interpretation
 3156: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
 3157: not like this limitation, but have not seen a satisfying way around it
 3158: yet, although many schemes have been proposed.
 3159: 
 3160: @menu
 3161: * Selection::                   IF ... ELSE ... ENDIF
 3162: * Simple Loops::                BEGIN ...
 3163: * Counted Loops::               DO
 3164: * Arbitrary control structures::
 3165: * Calls and returns::
 3166: * Exception Handling::          
 3167: @end menu
 3168: 
 3169: @node Selection, Simple Loops, Control Structures, Control Structures
 3170: @subsection Selection
 3171: @cindex selection control structures
 3172: @cindex control structures for selection
 3173: 
 3174: @c what's the purpose of all these @i? Maybe we should define a macro
 3175: @c so we can produce logical markup.  - anton
 3176: 
 3177: @c nac-> When I started working on the manual, a mixture of @i and @var
 3178: @c were used inconsistently in code examples and \Glossary entries. These
 3179: @c two behave differently in info format so I decided to standardize on @i.
 3180: @c Logical markup would be better but texi isn't really upto it, and
 3181: @c texi2html just ignores macros.
 3182: 
 3183: @cindex @code{IF} control structure
 3184: @example
 3185: @i{flag}
 3186: IF
 3187:   @i{code}
 3188: ENDIF
 3189: @end example
 3190: @noindent
 3191: 
 3192: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
 3193: with any bit set represents truth) @i{code} is executed.
 3194: 
 3195: @example
 3196: @i{flag}
 3197: IF
 3198:   @i{code1}
 3199: ELSE
 3200:   @i{code2}
 3201: ENDIF
 3202: @end example
 3203: 
 3204: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
 3205: executed.
 3206: 
 3207: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
 3208: standard, and @code{ENDIF} is not, although it is quite popular. We
 3209: recommend using @code{ENDIF}, because it is less confusing for people
 3210: who also know other languages (and is not prone to reinforcing negative
 3211: prejudices against Forth in these people). Adding @code{ENDIF} to a
 3212: system that only supplies @code{THEN} is simple:
 3213: @example
 3214: : ENDIF   POSTPONE THEN ; immediate
 3215: @end example
 3216: 
 3217: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
 3218: (adv.)}  has the following meanings:
 3219: @quotation
 3220: ... 2b: following next after in order ... 3d: as a necessary consequence
 3221: (if you were there, then you saw them).
 3222: @end quotation
 3223: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
 3224: and many other programming languages has the meaning 3d.]
 3225: 
 3226: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
 3227: you can avoid using @code{?dup}. Using these alternatives is also more
 3228: efficient than using @code{?dup}. Definitions in ANS Forth
 3229: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
 3230: @file{compat/control.fs}.
 3231: 
 3232: @cindex @code{CASE} control structure
 3233: @example
 3234: @i{n}
 3235: CASE
 3236:   @i{n1} OF @i{code1} ENDOF
 3237:   @i{n2} OF @i{code2} ENDOF
 3238:   @dots{}
 3239: ENDCASE
 3240: @end example
 3241: 
 3242: Executes the first @i{codei}, where the @i{ni} is equal to
 3243: @i{n}. A default case can be added by simply writing the code after
 3244: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
 3245: but must not consume it.
 3246: 
 3247: @node Simple Loops, Counted Loops, Selection, Control Structures
 3248: @subsection Simple Loops
 3249: @cindex simple loops
 3250: @cindex loops without count 
 3251: 
 3252: @cindex @code{WHILE} loop
 3253: @example
 3254: BEGIN
 3255:   @i{code1}
 3256:   @i{flag}
 3257: WHILE
 3258:   @i{code2}
 3259: REPEAT
 3260: @end example
 3261: 
 3262: @i{code1} is executed and @i{flag} is computed. If it is true,
 3263: @i{code2} is executed and the loop is restarted; If @i{flag} is
 3264: false, execution continues after the @code{REPEAT}.
 3265: 
 3266: @cindex @code{UNTIL} loop
 3267: @example
 3268: BEGIN
 3269:   @i{code}
 3270:   @i{flag}
 3271: UNTIL
 3272: @end example
 3273: 
 3274: @i{code} is executed. The loop is restarted if @code{flag} is false.
 3275: 
 3276: @cindex endless loop
 3277: @cindex loops, endless
 3278: @example
 3279: BEGIN
 3280:   @i{code}
 3281: AGAIN
 3282: @end example
 3283: 
 3284: This is an endless loop.
 3285: 
 3286: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
 3287: @subsection Counted Loops
 3288: @cindex counted loops
 3289: @cindex loops, counted
 3290: @cindex @code{DO} loops
 3291: 
 3292: The basic counted loop is:
 3293: @example
 3294: @i{limit} @i{start}
 3295: ?DO
 3296:   @i{body}
 3297: LOOP
 3298: @end example
 3299: 
 3300: This performs one iteration for every integer, starting from @i{start}
 3301: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
 3302: accessed with @code{i}. For example, the loop:
 3303: @example
 3304: 10 0 ?DO
 3305:   i .
 3306: LOOP
 3307: @end example
 3308: @noindent
 3309: prints @code{0 1 2 3 4 5 6 7 8 9}
 3310: 
 3311: The index of the innermost loop can be accessed with @code{i}, the index
 3312: of the next loop with @code{j}, and the index of the third loop with
 3313: @code{k}.
 3314: 
 3315: 
 3316: doc-i
 3317: doc-j
 3318: doc-k
 3319: 
 3320: 
 3321: The loop control data are kept on the return stack, so there are some
 3322: restrictions on mixing return stack accesses and counted loop words. In
 3323: particuler, if you put values on the return stack outside the loop, you
 3324: cannot read them inside the loop@footnote{well, not in a way that is
 3325: portable.}. If you put values on the return stack within a loop, you
 3326: have to remove them before the end of the loop and before accessing the
 3327: index of the loop.
 3328: 
 3329: There are several variations on the counted loop:
 3330: 
 3331: @itemize @bullet
 3332: @item
 3333: @code{LEAVE} leaves the innermost counted loop immediately; execution
 3334: continues after the associated @code{LOOP} or @code{NEXT}. For example:
 3335: 
 3336: @example
 3337: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
 3338: @end example
 3339: prints @code{0 1 2 3}
 3340: 
 3341: 
 3342: @item
 3343: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
 3344: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
 3345: return stack so @code{EXIT} can get to its return address. For example:
 3346: 
 3347: @example
 3348: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
 3349: @end example
 3350: prints @code{0 1 2 3}
 3351: 
 3352: 
 3353: @item
 3354: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
 3355: (and @code{LOOP} iterates until they become equal by wrap-around
 3356: arithmetic). This behaviour is usually not what you want. Therefore,
 3357: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
 3358: @code{?DO}), which do not enter the loop if @i{start} is greater than
 3359: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
 3360: unsigned loop parameters.
 3361: 
 3362: @item
 3363: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
 3364: the loop, independent of the loop parameters. Do not use @code{DO}, even
 3365: if you know that the loop is entered in any case. Such knowledge tends
 3366: to become invalid during maintenance of a program, and then the
 3367: @code{DO} will make trouble.
 3368: 
 3369: @item
 3370: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
 3371: index by @i{n} instead of by 1. The loop is terminated when the border
 3372: between @i{limit-1} and @i{limit} is crossed. E.g.:
 3373: 
 3374: @example
 3375: 4 0 +DO  i .  2 +LOOP
 3376: @end example
 3377: @noindent
 3378: prints @code{0 2}
 3379: 
 3380: @example
 3381: 4 1 +DO  i .  2 +LOOP
 3382: @end example
 3383: @noindent
 3384: prints @code{1 3}
 3385: 
 3386: 
 3387: @cindex negative increment for counted loops
 3388: @cindex counted loops with negative increment
 3389: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
 3390: 
 3391: @example
 3392: -1 0 ?DO  i .  -1 +LOOP
 3393: @end example
 3394: @noindent
 3395: prints @code{0 -1}
 3396: 
 3397: @example
 3398: 0 0 ?DO  i .  -1 +LOOP
 3399: @end example
 3400: prints nothing.
 3401: 
 3402: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
 3403: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
 3404: index by @i{u} each iteration. The loop is terminated when the border
 3405: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
 3406: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
 3407: 
 3408: @example
 3409: -2 0 -DO  i .  1 -LOOP
 3410: @end example
 3411: @noindent
 3412: prints @code{0 -1}
 3413: 
 3414: @example
 3415: -1 0 -DO  i .  1 -LOOP
 3416: @end example
 3417: @noindent
 3418: prints @code{0}
 3419: 
 3420: @example
 3421: 0 0 -DO  i .  1 -LOOP
 3422: @end example
 3423: @noindent
 3424: prints nothing.
 3425: 
 3426: @end itemize
 3427: 
 3428: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
 3429: @code{-LOOP} are not defined in ANS Forth. However, an implementation
 3430: for these words that uses only standard words is provided in
 3431: @file{compat/loops.fs}.
 3432: 
 3433: 
 3434: @cindex @code{FOR} loops
 3435: Another counted loop is:
 3436: @example
 3437: @i{n}
 3438: FOR
 3439:   @i{body}
 3440: NEXT
 3441: @end example
 3442: This is the preferred loop of native code compiler writers who are too
 3443: lazy to optimize @code{?DO} loops properly. This loop structure is not
 3444: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
 3445: @code{i} produces values starting with @i{n} and ending with 0. Other
 3446: Forth systems may behave differently, even if they support @code{FOR}
 3447: loops. To avoid problems, don't use @code{FOR} loops.
 3448: 
 3449: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
 3450: @subsection Arbitrary control structures
 3451: @cindex control structures, user-defined
 3452: 
 3453: @cindex control-flow stack
 3454: ANS Forth permits and supports using control structures in a non-nested
 3455: way. Information about incomplete control structures is stored on the
 3456: control-flow stack. This stack may be implemented on the Forth data
 3457: stack, and this is what we have done in Gforth.
 3458: 
 3459: @cindex @code{orig}, control-flow stack item
 3460: @cindex @code{dest}, control-flow stack item
 3461: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
 3462: entry represents a backward branch target. A few words are the basis for
 3463: building any control structure possible (except control structures that
 3464: need storage, like calls, coroutines, and backtracking).
 3465: 
 3466: 
 3467: doc-if
 3468: doc-ahead
 3469: doc-then
 3470: doc-begin
 3471: doc-until
 3472: doc-again
 3473: doc-cs-pick
 3474: doc-cs-roll
 3475: 
 3476: 
 3477: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
 3478: manipulate the control-flow stack in a portable way. Without them, you
 3479: would need to know how many stack items are occupied by a control-flow
 3480: entry (many systems use one cell. In Gforth they currently take three,
 3481: but this may change in the future).
 3482: 
 3483: Some standard control structure words are built from these words:
 3484: 
 3485: 
 3486: doc-else
 3487: doc-while
 3488: doc-repeat
 3489: 
 3490: 
 3491: @noindent
 3492: Gforth adds some more control-structure words:
 3493: 
 3494: 
 3495: doc-endif
 3496: doc-?dup-if
 3497: doc-?dup-0=-if
 3498: 
 3499: 
 3500: @noindent
 3501: Counted loop words constitute a separate group of words:
 3502: 
 3503: 
 3504: doc-?do
 3505: doc-+do
 3506: doc-u+do
 3507: doc--do
 3508: doc-u-do
 3509: doc-do
 3510: doc-for
 3511: doc-loop
 3512: doc-+loop
 3513: doc--loop
 3514: doc-next
 3515: doc-leave
 3516: doc-?leave
 3517: doc-unloop
 3518: doc-done
 3519: 
 3520: 
 3521: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
 3522: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
 3523: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
 3524: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
 3525: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
 3526: resolved (by using one of the loop-ending words or @code{DONE}).
 3527: 
 3528: @noindent
 3529: Another group of control structure words are:
 3530: 
 3531: 
 3532: doc-case
 3533: doc-endcase
 3534: doc-of
 3535: doc-endof
 3536: 
 3537: 
 3538: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
 3539: @code{CS-ROLL}.
 3540: 
 3541: @subsubsection Programming Style
 3542: 
 3543: In order to ensure readability we recommend that you do not create
 3544: arbitrary control structures directly, but define new control structure
 3545: words for the control structure you want and use these words in your
 3546: program. For example, instead of writing:
 3547: 
 3548: @example
 3549: BEGIN
 3550:   ...
 3551: IF [ 1 CS-ROLL ]
 3552:   ...
 3553: AGAIN THEN
 3554: @end example
 3555: 
 3556: @noindent
 3557: we recommend defining control structure words, e.g.,
 3558: 
 3559: @example
 3560: : WHILE ( DEST -- ORIG DEST )
 3561:  POSTPONE IF
 3562:  1 CS-ROLL ; immediate
 3563: 
 3564: : REPEAT ( orig dest -- )
 3565:  POSTPONE AGAIN
 3566:  POSTPONE THEN ; immediate
 3567: @end example
 3568: 
 3569: @noindent
 3570: and then using these to create the control structure:
 3571: 
 3572: @example
 3573: BEGIN
 3574:   ...
 3575: WHILE
 3576:   ...
 3577: REPEAT
 3578: @end example
 3579: 
 3580: That's much easier to read, isn't it? Of course, @code{REPEAT} and
 3581: @code{WHILE} are predefined, so in this example it would not be
 3582: necessary to define them.
 3583: 
 3584: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
 3585: @subsection Calls and returns
 3586: @cindex calling a definition
 3587: @cindex returning from a definition
 3588: 
 3589: @cindex recursive definitions
 3590: A definition can be called simply be writing the name of the definition
 3591: to be called. Normally a definition is invisible during its own
 3592: definition. If you want to write a directly recursive definition, you
 3593: can use @code{recursive} to make the current definition visible, or
 3594: @code{recurse} to call the current definition directly.
 3595: 
 3596: 
 3597: doc-recursive
 3598: doc-recurse
 3599: 
 3600: 
 3601: @comment TODO add example of the two recursion methods
 3602: @quotation
 3603: @progstyle
 3604: I prefer using @code{recursive} to @code{recurse}, because calling the
 3605: definition by name is more descriptive (if the name is well-chosen) than
 3606: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
 3607: implementation, it is much better to read (and think) ``now sort the
 3608: partitions'' than to read ``now do a recursive call''.
 3609: @end quotation
 3610: 
 3611: For mutual recursion, use @code{Defer}red words, like this:
 3612: 
 3613: @example
 3614: Defer foo
 3615: 
 3616: : bar ( ... -- ... )
 3617:  ... foo ... ;
 3618: 
 3619: :noname ( ... -- ... )
 3620:  ... bar ... ;
 3621: IS foo
 3622: @end example
 3623: 
 3624: Deferred words are discussed in more detail in @ref{Deferred words}.
 3625: 
 3626: The current definition returns control to the calling definition when
 3627: the end of the definition is reached or @code{EXIT} is encountered.
 3628: 
 3629: doc-exit
 3630: doc-;s
 3631: 
 3632: 
 3633: @node Exception Handling,  , Calls and returns, Control Structures
 3634: @subsection Exception Handling
 3635: @cindex exceptions
 3636: 
 3637: If your program detects a fatal error condition, the simplest action
 3638: that it can take is to @code{quit}. This resets the return stack and
 3639: restarts the text interpreter, but does not print any error message.
 3640: 
 3641: The next stage in severity is to execute @code{abort}, which has the
 3642: same effect as @code{quit}, with the addition that it resets the data
 3643: stack.
 3644: 
 3645: A slightly more sophisticated approach is use use @code{abort"}, which
 3646: compiles a string to be used as an error message and does a conditional
 3647: @code{abort} at run-time. For example:
 3648: 
 3649: @example
 3650: @kbd{: checker abort" That flag was true" ." A false flag" ;@key{RET}}  ok
 3651: @kbd{0 checker@key{RET}} A false flag ok
 3652: @kbd{1 checker@key{RET}}
 3653: :1: That flag was true
 3654: 1 checker
 3655:   ^^^^^^^
 3656: $400D1648 throw 
 3657: $400E4660
 3658: @end example
 3659: 
 3660: These simple techniques allow a program to react to a fatal error
 3661: condition, but they are not exactly user-friendly. The ANS Forth
 3662: Exception word set provides the pair of words @code{throw} and
 3663: @code{catch}, which can be used to provide sophisticated error-handling.
 3664: 
 3665: @code{catch} has a similar behaviour to @code{execute}, in that it takes
 3666: an @i{xt} as a parameter and starts execution of the xt. However,
 3667: before passing control to the xt, @code{catch} pushes an
 3668: @dfn{exception frame} onto the @dfn{exception stack}. This exception
 3669: frame is used to restore the system to a known state if a detected error
 3670: occurs during the execution of the xt. A typical way to use @code{catch}
 3671: would be:
 3672: 
 3673: @example
 3674: ... ['] foo catch IF ...
 3675: @end example
 3676: 
 3677: @c TOS is undefined. - anton
 3678: 
 3679: @c nac-> TODO -- I need to look at this example again.
 3680: 
 3681: Whilst @code{foo} executes, it can call other words to any level of
 3682: nesting, as usual.  If @code{foo} (and all the words that it calls)
 3683: execute successfully, control will ultimately pass to the word following
 3684: the @code{catch}, and there will be a 0 at TOS.  However, if any word
 3685: detects an error, it can terminate the execution of @code{foo} by
 3686: pushing a non-zero error code onto the stack and then performing a
 3687: @code{throw}. The execution of @code{throw} will pass control to the
 3688: word following the @code{catch}, but this time the TOS will hold the
 3689: error code. Therefore, the @code{IF} in the example can be used to
 3690: determine whether @code{foo} executed successfully.
 3691: 
 3692: This simple example shows how you can use @code{throw} and @code{catch}
 3693: to ``take over'' exception handling from the system:
 3694: @example
 3695: : my-div ['] / catch if ." DIVIDE ERROR" else ." OK.. " . then ;
 3696: @end example
 3697: 
 3698: The next example is more sophisticated and shows a multi-level
 3699: @code{throw} and @code{catch}. To understand this example, start at the
 3700: definition of @code{top-level} and work backwards:
 3701: 
 3702: @example
 3703: : lowest-level ( -- c )
 3704:     key dup 27 = if
 3705:         1 throw \ ESCAPE key pressed
 3706:     else
 3707:         ." lowest-level successful" CR
 3708:     then
 3709: ;
 3710: 
 3711: : lower-level ( -- c )
 3712:     lowest-level
 3713:     \ at this level consider a CTRL-U to be a fatal error
 3714:     dup 21 = if \ CTRL-U
 3715:         2 throw
 3716:     else
 3717:         ." lower-level successful" CR
 3718:     then
 3719: ;
 3720: 
 3721: : low-level ( -- c )
 3722:     ['] lower-level catch
 3723:     ?dup if
 3724:         \ error occurred - do we recognise it?
 3725:         dup 1 = if
 3726:             \ ESCAPE key pressed.. pretend it was an E
 3727:             [char] E
 3728:         else throw \ propogate the error upwards
 3729:         then
 3730:     then
 3731:     ." low-level successfull" CR
 3732: ;
 3733: 
 3734: : top-level ( -- )
 3735:     CR ['] low-level catch \ CATCH is used like EXECUTE
 3736:     ?dup if \ error occurred..
 3737:         ." Error " . ." occurred - contact your supplier"
 3738:     else
 3739:         ." The '" emit ." ' key was pressed" CR
 3740:     then
 3741: ;
 3742: @end example
 3743: 
 3744: The ANS Forth document assigns @code{throw} codes thus:
 3745: 
 3746: @itemize @bullet
 3747: @item
 3748: codes in the range -1 -- -255 are reserved to be assigned by the
 3749: Standard. Assignments for codes in the range -1 -- -58 are currently
 3750: documented in the Standard. In particular, @code{-1 throw} is equivalent
 3751: to @code{abort} and @code{-2 throw} is equivalent to @code{abort"}.
 3752: @item
 3753: codes in the range -256 -- -4095 are reserved to be assigned by the system.
 3754: @item
 3755: all other codes may be assigned by programs.
 3756: @end itemize
 3757: 
 3758: Gforth provides the word @code{exception} as a mechanism for assigning
 3759: system throw codes to applications. This allows multiple applications to
 3760: co-exist in memory without any clash of @code{throw} codes. A definition
 3761: of @code{exception} in ANS Forth is provided in
 3762: @file{compat/exception.fs}.
 3763: 
 3764: 
 3765: doc-quit
 3766: doc-abort
 3767: doc-abort"
 3768: 
 3769: doc-catch
 3770: doc-throw
 3771: doc---exception-exception
 3772: 
 3773: 
 3774: 
 3775: @c -------------------------------------------------------------
 3776: @node Defining Words, The Text Interpreter, Control Structures, Words
 3777: @section Defining Words
 3778: @cindex defining words
 3779: 
 3780: @menu
 3781: * CREATE::
 3782: * Variables::                   Variables and user variables
 3783: * Constants::
 3784: * Values::                      Initialised variables
 3785: * Colon Definitions::
 3786: * Anonymous Definitions::       Definitions without names
 3787: * User-defined Defining Words::
 3788: * Deferred words::              Allow forward references
 3789: * Aliases::
 3790: * Supplying names::
 3791: * Interpretation and Compilation Semantics::
 3792: * Combined words::
 3793: @end menu
 3794: 
 3795: @node CREATE, Variables, Defining Words, Defining Words
 3796: @subsection @code{CREATE}
 3797: @cindex simple defining words
 3798: @cindex defining words, simple
 3799: 
 3800: Defining words are used to create new entries in the dictionary. The
 3801: simplest defining word is @code{CREATE}. @code{CREATE} is used like
 3802: this:
 3803: 
 3804: @example
 3805: CREATE new-word1
 3806: @end example
 3807: 
 3808: @code{CREATE} is a parsing word that generates a dictionary entry for
 3809: @code{new-word1}. When @code{new-word1} is executed, all that it does is
 3810: leave an address on the stack. The address represents the value of
 3811: the data space pointer (@code{HERE}) at the time that @code{new-word1}
 3812: was defined. Therefore, @code{CREATE} is a way of associating a name
 3813: with the address of a region of memory.
 3814: 
 3815: doc-create
 3816: 
 3817: By extending this example to reserve some memory in data space, we end
 3818: up with a @i{variable}. Here are two different ways to do it:
 3819: 
 3820: @example
 3821: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
 3822: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
 3823: @end example
 3824: 
 3825: The variable can be examined and modified using @code{@@} (``fetch'') and
 3826: @code{!} (``store'') like this:
 3827: 
 3828: @example
 3829: new-word2 @@ .      \ get address, fetch from it and display
 3830: 1234 new-word2 !   \ new value, get address, store to it
 3831: @end example
 3832: 
 3833: @cindex arrays
 3834: A similar mechanism can be used to create arrays. For example, an
 3835: 80-character text input buffer:
 3836: 
 3837: @example
 3838: CREATE text-buf 80 chars allot
 3839: 
 3840: text-buf 0 chars c@@ \ the 1st character (offset 0)
 3841: text-buf 3 chars c@@ \ the 4th character (offset 3)
 3842: @end example
 3843: 
 3844: You can build arbitrarily complex data structures by allocating
 3845: appropriate areas of memory. @xref{Structures} for further discussions
 3846: of this, and to learn about some Gforth tools that make it easier.
 3847: 
 3848: 
 3849: @node Variables, Constants, CREATE, Defining Words
 3850: @subsection Variables
 3851: @cindex variables
 3852: 
 3853: The previous section showed how a sequence of commands could be used to
 3854: generate a variable.  As a final refinement, the whole code sequence can
 3855: be wrapped up in a defining word (pre-empting the subject of the next
 3856: section), making it easier to create new variables:
 3857: 
 3858: @example
 3859: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
 3860: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
 3861: 
 3862: myvariableX foo \ variable foo starts off with an unknown value
 3863: myvariable0 joe \ whilst joe is initialised to 0
 3864: 
 3865: 45 3 * foo !   \ set foo to 135
 3866: 1234 joe !     \ set joe to 1234
 3867: 3 joe +!       \ increment joe by 3.. to 1237
 3868: @end example
 3869: 
 3870: Not surprisingly, there is no need to define @code{myvariable}, since
 3871: Forth already has a definition @code{Variable}. ANS Forth does not
 3872: require a @code{Variable} to be initialised when it is created (i.e., it
 3873: behaves like @code{myvariableX}). In contrast, Gforth's @code{Variable}
 3874: initialises the variable to 0 (i.e., it behaves exactly like
 3875: @code{myvariable0}). Forth also provides @code{2Variable} and
 3876: @code{fvariable} for double and floating-point variables,
 3877: respectively -- both are initialised to 0 in Gforth.
 3878: 
 3879: doc-variable
 3880: doc-2variable
 3881: doc-fvariable
 3882: 
 3883: 
 3884: @cindex user variables
 3885: @cindex user space
 3886: The defining word @code{User} behaves in the same way as @code{Variable}.
 3887: The difference is that it reserves space in @i{user (data) space} rather
 3888: than normal data space. In a Forth system that has a multi-tasker, each
 3889: task has its own set of user variables.
 3890: 
 3891: doc-user
 3892: 
 3893: @comment TODO is that stuff about user variables strictly correct? Is it
 3894: @comment just terminal tasks that have user variables?
 3895: @comment should document tasker.fs (with some examples) elsewhere
 3896: @comment in this manual, then expand on user space and user variables.
 3897: 
 3898: 
 3899: @node Constants, Values, Variables, Defining Words
 3900: @subsection Constants
 3901: @cindex constants
 3902: 
 3903: @code{Constant} allows you to declare a fixed value and refer to it by
 3904: name. For example:
 3905: 
 3906: @example
 3907: 12 Constant INCHES-PER-FOOT
 3908: 3E+08 fconstant SPEED-O-LIGHT
 3909: @end example
 3910: 
 3911: A @code{Variable} can be both read and written, so its run-time
 3912: behaviour is to supply an address through which its current value can be
 3913: manipulated. In contrast, the value of a @code{Constant} cannot be
 3914: changed once it has been declared@footnote{Well, often it can be -- but
 3915: not in a Standard, portable way. It's safer to use a @code{Value} (read
 3916: on).} so it's not necessary to supply the address -- it is more
 3917: efficient to return the value of the constant directly. That's exactly
 3918: what happens; the run-time effect of a constant is to put its value on
 3919: the top of the stack (@ref{User-defined Defining Words} describes one
 3920: way of implementing @code{Constant}).
 3921: 
 3922: Gforth also provides @code{2Constant} and @code{fconstant} for defining
 3923: double and floating-point constants, respectively.
 3924: 
 3925: doc-constant
 3926: doc-2constant
 3927: doc-fconstant
 3928: 
 3929: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
 3930: @c nac-> How could that not be true in an ANS Forth? You can't define a
 3931: @c constant, use it and then delete the definition of the constant..
 3932: @c I agree that it's rather deep, but IMO it is an important difference
 3933: @c relative to other programming languages.. often it's annoying: it
 3934: @c certainly changes my programming style relative to C.
 3935: 
 3936: Constants in Forth behave differently from their equivalents in other
 3937: programming languages. In other languages, a constant (such as an EQU in
 3938: assembler or a #define in C) only exists at compile-time; in the
 3939: executable program the constant has been translated into an absolute
 3940: number and, unless you are using a symbolic debugger, it's impossible to
 3941: know what abstract thing that number represents. In Forth a constant has
 3942: an entry in the header space and remains there after the code that uses
 3943: it has been defined. In fact, it must remain in the dictionary since it
 3944: has run-time duties to perform. For example:
 3945: 
 3946: @example
 3947: 12 Constant INCHES-PER-FOOT
 3948: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
 3949: @end example
 3950: 
 3951: @cindex in-lining of constants
 3952: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
 3953: associated with the constant @code{INCHES-PER-FOOT}. If you use
 3954: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
 3955: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
 3956: attempt to optimise constants by in-lining them where they are used. You
 3957: can force Gforth to in-line a constant like this:
 3958: 
 3959: @example
 3960: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
 3961: @end example
 3962: 
 3963: If you use @code{see} to decompile @i{this} version of
 3964: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
 3965: longer present. @xref{Interpret/Compile states} and @ref{Literals} on
 3966: how this works.
 3967: 
 3968: In-lining constants in this way might improve execution time
 3969: fractionally, and can ensure that a constant is now only referenced at
 3970: compile-time. However, the definition of the constant still remains in
 3971: the dictionary. Some Forth compilers provide a mechanism for controlling
 3972: a second dictionary for holding transient words such that this second
 3973: dictionary can be deleted later in order to recover memory
 3974: space. However, there is no standard way of doing this.
 3975: 
 3976: 
 3977: @node Values, Colon Definitions, Constants, Defining Words
 3978: @subsection Values
 3979: @cindex values
 3980: 
 3981: A @code{Value} is like a @code{Variable} but with two important
 3982: differences:
 3983: 
 3984: @itemize @bullet
 3985: @item
 3986: A @code{Value} is initialised when it is declared; like a
 3987: @code{Constant} but unlike a @code{Variable}.
 3988: @item
 3989: A @code{Value} returns its value rather than its address when it is
 3990: executed; i.e., it has the same run-time behaviour as @code{Constant}.
 3991: @end itemize
 3992: 
 3993: A @code{Value} needs an additional word, @code{TO} to allow its value to
 3994: be changed. Here are some examples:
 3995: 
 3996: @example
 3997: 12 Value APPLES \ Define APPLES with an initial value of 12
 3998: 34 TO APPLES    \ Change the value of APPLES. TO is a parsing word
 3999: APPLES          \ puts 34 on the top of the stack.
 4000: @end example
 4001: 
 4002: doc-value
 4003: doc-to
 4004: 
 4005: 
 4006: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
 4007: @subsection Colon Definitions
 4008: @cindex colon definitions
 4009: 
 4010: @example
 4011: : name ( ... -- ... )
 4012:     word1 word2 word3 ;
 4013: @end example
 4014: 
 4015: @noindent
 4016: Creates a word called @code{name} that, upon execution, executes
 4017: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
 4018: 
 4019: The explanation above is somewhat superficial. @xref{Your first
 4020: definition} for simple examples of colon definitions, then
 4021: @xref{Interpretation and Compilation Semantics} for an in-depth
 4022: discussion of some of the issues involved.
 4023: 
 4024: doc-:
 4025: doc-;
 4026: 
 4027: 
 4028: @node Anonymous Definitions, User-defined Defining Words, Colon Definitions, Defining Words
 4029: @subsection Anonymous Definitions
 4030: @cindex colon definitions
 4031: @cindex defining words without name
 4032: 
 4033: Sometimes you want to define an @dfn{anonymous word}; a word without a
 4034: name. You can do this with:
 4035: 
 4036: doc-:noname
 4037: 
 4038: This leaves the execution token for the word on the stack after the
 4039: closing @code{;}. Here's an example in which a deferred word is
 4040: initialised with an @code{xt} from an anonymous colon definition:
 4041: 
 4042: @example
 4043: Defer deferred
 4044: :noname ( ... -- ... )
 4045:   ... ;
 4046: IS deferred
 4047: @end example
 4048: 
 4049: @noindent
 4050: Gforth provides an alternative way of doing this, using two separate
 4051: words:
 4052: 
 4053: doc-noname
 4054: @cindex execution token of last defined word
 4055: doc-lastxt
 4056: 
 4057: @noindent
 4058: The previous example can be rewritten using @code{noname} and
 4059: @code{lastxt}:
 4060: 
 4061: @example
 4062: Defer deferred
 4063: noname : ( ... -- ... )
 4064:   ... ;
 4065: lastxt IS deferred
 4066: @end example
 4067: 
 4068: @noindent
 4069: @code{noname} works with any defining word, not just @code{:}.
 4070: 
 4071: @code{lastxt} also works when the last word was not defined as
 4072: @code{noname}. It also has the useful property that is is valid as soon
 4073: as the header for a definition has been built. Thus:
 4074: 
 4075: @example
 4076: lastxt . : foo [ lastxt . ] ; ' foo .
 4077: @end example
 4078: 
 4079: @noindent
 4080: prints 3 numbers; the last two are the same.
 4081: 
 4082: 
 4083: @node User-defined Defining Words, Deferred words, Anonymous Definitions, Defining Words
 4084: @subsection User-defined Defining Words
 4085: @cindex user-defined defining words
 4086: @cindex defining words, user-defined
 4087: 
 4088: You can create a new defining word by wrapping defining-time code around
 4089: an existing defining word and putting the sequence in a colon
 4090: definition. For example, suppose that you have a word @code{stats} that
 4091: gathers statistics about colon definitions given the @i{xt} of the
 4092: definition, and you want every colon definition in your application to
 4093: make a call to @code{stats}. You can define and use a new version of
 4094: @code{:} like this:
 4095: 
 4096: @example
 4097: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
 4098:   ... ;  \ other code
 4099: 
 4100: : my: : lastxt postpone literal ['] stats compile, ;
 4101: 
 4102: my: foo + - ;
 4103: @end example
 4104: 
 4105: When @code{foo} is defined using @code{my:} these steps occur:
 4106: 
 4107: @itemize @bullet
 4108: @item
 4109: @code{my:} is executed.
 4110: @item
 4111: The @code{:} within the definition (the one between @code{my:} and
 4112: @code{lastxt}) is executed, and does just what it always does; it parses
 4113: the input stream for a name, builds a dictionary header for the name
 4114: @code{foo} and switches @code{state} from interpret to compile.
 4115: @item
 4116: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
 4117: being defined -- @code{foo} -- onto the stack.
 4118: @item
 4119: The code that was produced by @code{postpone literal} is executed; this
 4120: causes the value on the stack to be compiled as a literal in the code
 4121: area of @code{foo}.
 4122: @item
 4123: The code @code{['] stats} compiles a literal into the definition of
 4124: @code{my:}. When @code{compile,} is executed, that literal -- the
 4125: execution token for @code{stats} -- is layed down in the code area of
 4126: @code{foo} , following the literal@footnote{Strictly speaking, the
 4127: mechanism that @code{compile,} uses to convert an @i{xt} into something
 4128: in the code area is implementation-dependent. A threaded implementation
 4129: might spit out the execution token directly whilst another
 4130: implementation might spit out a native code sequence.}.
 4131: @item
 4132: At this point, the execution of @code{my:} is complete, and control
 4133: returns to the text interpreter. The text interpreter is in compile
 4134: state, so subsequent text @code{+ -} is compiled into the definition of
 4135: @code{foo} and the @code{;} terminates the definition as always.
 4136: @end itemize
 4137: 
 4138: You can use @code{see} to decompile a word that was defined using
 4139: @code{my:} and see how it is different from a normal @code{:}
 4140: definition. For example:
 4141: 
 4142: @example
 4143: : bar + - ;  \ like foo but using : rather than my:
 4144: see bar
 4145: : bar
 4146:   + - ;
 4147: see foo
 4148: : foo
 4149:   107645672 stats + - ;
 4150: 
 4151: \ use ' stats . to show that 107645672 is the xt for stats
 4152: @end example
 4153: 
 4154: You can use techniques like this to make new defining words in terms of
 4155: @i{any} existing defining word.
 4156: 
 4157: 
 4158: @cindex defining defining words
 4159: @cindex @code{CREATE} ... @code{DOES>}
 4160: If you want the words defined with your defining words to behave
 4161: differently from words defined with standard defining words, you can
 4162: write your defining word like this:
 4163: 
 4164: @example
 4165: : def-word ( "name" -- )
 4166:     CREATE @i{code1}
 4167: DOES> ( ... -- ... )
 4168:     @i{code2} ;
 4169: 
 4170: def-word name
 4171: @end example
 4172: 
 4173: @cindex child words
 4174: This fragment defines a @dfn{defining word} @code{def-word} and then
 4175: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
 4176: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
 4177: is not executed at this time. The word @code{name} is sometimes called a
 4178: @dfn{child} of @code{def-word}.
 4179: 
 4180: When you execute @code{name}, the address of the body of @code{name} is
 4181: put on the data stack and @i{code2} is executed (the address of the body
 4182: of @code{name} is the address @code{HERE} returns immediately after the
 4183: @code{CREATE}).
 4184: 
 4185: @cindex atavism in child words
 4186: You can use @code{def-word} to define a set of child words that behave
 4187: differently, though atavistically; they all have a common run-time
 4188: behaviour determined by @i{code2}. Typically, the @i{code1} sequence
 4189: builds a data area in the body of the child word. The structure of the
 4190: data is common to all children of @code{def-word}, but the data values
 4191: are specific -- and private -- to each child word. When a child word is
 4192: executed, the address of its private data area is passed as a parameter
 4193: on TOS to be used and manipulated@footnote{It is legitimate both to read
 4194: and write to this data area.} by @i{code2}.
 4195: 
 4196: The two fragments of code that make up the defining words act (are
 4197: executed) at two completely separate times:
 4198: 
 4199: @itemize @bullet
 4200: @item
 4201: At @i{define time}, the defining word executes @i{code1} to generate a
 4202: child word
 4203: @item
 4204: At @i{child execution time}, when a child word is invoked, @i{code2}
 4205: is executed, using parameters (data) that are private and specific to
 4206: the child word.
 4207: @end itemize
 4208: 
 4209: Another way of understanding the behaviour of @code{def-word} and
 4210: @code{name} is to say that, if you make the following definitions:
 4211: @example
 4212: : def-word1 ( "name" -- )
 4213:     CREATE @i{code1} ;
 4214: 
 4215: : action1 ( ... -- ... )
 4216:     @i{code2} ;
 4217: 
 4218: def-word1 name1
 4219: @end example
 4220: 
 4221: @noindent
 4222: Then using @code{name1 action1} is equivalent to using @code{name}.
 4223: 
 4224: The classic example is that you can define @code{CONSTANT} in this way:
 4225: 
 4226: @example
 4227: : CONSTANT ( w "name" -- )
 4228:     CREATE ,
 4229: DOES> ( -- w )
 4230:     @@ ;
 4231: @end example
 4232: 
 4233: @comment There is a beautiful description of how this works and what
 4234: @comment it does in the Forthwrite 100th edition.. as well as an elegant
 4235: @comment commentary on the Counting Fruits problem.
 4236: 
 4237: When you create a constant with @code{5 CONSTANT five}, a set of
 4238: define-time actions take place; first a new word @code{five} is created,
 4239: then the value 5 is laid down in the body of @code{five} with
 4240: @code{,}. When @code{five} is executed, the address of the body is put on
 4241: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
 4242: no code of its own; it simply contains a data field and a pointer to the
 4243: code that follows @code{DOES>} in its defining word. That makes words
 4244: created in this way very compact.
 4245: 
 4246: The final example in this section is intended to remind you that space
 4247: reserved in @code{CREATE}d words is @i{data} space and therefore can be
 4248: both read and written by a Standard program@footnote{Exercise: use this
 4249: example as a starting point for your own implementation of @code{Value}
 4250: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
 4251: @code{[']}.}:
 4252: 
 4253: @example
 4254: : foo ( "name" -- )
 4255:     CREATE -1 ,
 4256: DOES> ( -- )
 4257:     @@ . ;
 4258: 
 4259: foo first-word
 4260: foo second-word
 4261: 
 4262: 123 ' first-word >BODY !
 4263: @end example
 4264: 
 4265: If @code{first-word} had been a @code{CREATE}d word, we could simply
 4266: have executed it to get the address of its data field. However, since it
 4267: was defined to have @code{DOES>} actions, its execution semantics are to
 4268: perform those @code{DOES>} actions. To get the address of its data field
 4269: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
 4270: translate the xt into the address of the data field.  When you execute
 4271: @code{first-word}, it will display @code{123}. When you execute
 4272: @code{second-word} it will display @code{-1}.
 4273: 
 4274: @cindex stack effect of @code{DOES>}-parts
 4275: @cindex @code{DOES>}-parts, stack effect
 4276: In the examples above the stack comment after the @code{DOES>} specifies
 4277: the stack effect of the defined words, not the stack effect of the
 4278: following code (the following code expects the address of the body on
 4279: the top of stack, which is not reflected in the stack comment). This is
 4280: the convention that I use and recommend (it clashes a bit with using
 4281: locals declarations for stack effect specification, though).
 4282: 
 4283: @subsubsection Applications of @code{CREATE..DOES>}
 4284: @cindex @code{CREATE} ... @code{DOES>}, applications
 4285: 
 4286: You may wonder how to use this feature. Here are some usage patterns:
 4287: 
 4288: @cindex factoring similar colon definitions
 4289: When you see a sequence of code occurring several times, and you can
 4290: identify a meaning, you will factor it out as a colon definition. When
 4291: you see similar colon definitions, you can factor them using
 4292: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
 4293: that look very similar:
 4294: @example
 4295: : ori, ( reg-target reg-source n -- )
 4296:     0 asm-reg-reg-imm ;
 4297: : andi, ( reg-target reg-source n -- )
 4298:     1 asm-reg-reg-imm ;
 4299: @end example
 4300: 
 4301: @noindent
 4302: This could be factored with:
 4303: @example
 4304: : reg-reg-imm ( op-code -- )
 4305:     CREATE ,
 4306: DOES> ( reg-target reg-source n -- )
 4307:     @@ asm-reg-reg-imm ;
 4308: 
 4309: 0 reg-reg-imm ori,
 4310: 1 reg-reg-imm andi,
 4311: @end example
 4312: 
 4313: @cindex currying
 4314: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
 4315: supply a part of the parameters for a word (known as @dfn{currying} in
 4316: the functional language community). E.g., @code{+} needs two
 4317: parameters. Creating versions of @code{+} with one parameter fixed can
 4318: be done like this:
 4319: @example
 4320: : curry+ ( n1 -- )
 4321:     CREATE ,
 4322: DOES> ( n2 -- n1+n2 )
 4323:     @@ + ;
 4324: 
 4325:  3 curry+ 3+
 4326: -2 curry+ 2-
 4327: @end example
 4328: 
 4329: @subsubsection The gory details of @code{CREATE..DOES>}
 4330: @cindex @code{CREATE} ... @code{DOES>}, details
 4331: 
 4332: doc-does>
 4333: 
 4334: @cindex @code{DOES>} in a separate definition
 4335: This means that you need not use @code{CREATE} and @code{DOES>} in the
 4336: same definition; you can put the @code{DOES>}-part in a separate
 4337: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
 4338: @example
 4339: : does1 
 4340: DOES> ( ... -- ... )
 4341:     ... ;
 4342: 
 4343: : does2
 4344: DOES> ( ... -- ... )
 4345:     ... ;
 4346: 
 4347: : def-word ( ... -- ... )
 4348:     create ...
 4349:     IF
 4350:        does1
 4351:     ELSE
 4352:        does2
 4353:     ENDIF ;
 4354: @end example
 4355: 
 4356: In this example, the selection of whether to use @code{does1} or
 4357: @code{does2} is made at compile-time; at the time that the child word is
 4358: @code{CREATE}d.
 4359: 
 4360: @cindex @code{DOES>} in interpretation state
 4361: In a standard program you can apply a @code{DOES>}-part only if the last
 4362: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
 4363: will override the behaviour of the last word defined in any case. In a
 4364: standard program, you can use @code{DOES>} only in a colon
 4365: definition. In Gforth, you can also use it in interpretation state, in a
 4366: kind of one-shot mode; for example:
 4367: @example
 4368: CREATE name ( ... -- ... )
 4369:   @i{initialization}
 4370: DOES>
 4371:   @i{code} ;
 4372: @end example
 4373: 
 4374: @noindent
 4375: is equivalent to the standard:
 4376: @example
 4377: :noname
 4378: DOES>
 4379:     @i{code} ;
 4380: CREATE name EXECUTE ( ... -- ... )
 4381:     @i{initialization}
 4382: @end example
 4383: 
 4384: 
 4385: doc->body
 4386: 
 4387: 
 4388: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
 4389: @subsection Deferred words
 4390: @cindex deferred words
 4391: 
 4392: The defining word @code{Defer} allows you to define a word by name
 4393: without defining its behaviour; the definition of its behaviour is
 4394: deferred. Here are two situation where this can be useful:
 4395: 
 4396: @itemize @bullet
 4397: @item
 4398: Where you want to allow the behaviour of a word to be altered later, and
 4399: for all precompiled references to the word to change when its behaviour
 4400: is changed.
 4401: @item
 4402: For mutual recursion; @xref{Calls and returns}.
 4403: @end itemize
 4404: 
 4405: In the following example, @code{foo} always invokes the version of
 4406: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
 4407: always invokes the version that prints ``@code{Hello}''. There is no way
 4408: of getting @code{foo} to use the later version without re-ordering the
 4409: source code and recompiling it.
 4410: 
 4411: @example
 4412: : greet ." Good morning" ;
 4413: : foo ... greet ... ;
 4414: : greet ." Hello" ;
 4415: : bar ... greet ... ;
 4416: @end example
 4417: 
 4418: This problem can be solved by defining @code{greet} as a @code{Defer}red
 4419: word. The behaviour of a @code{Defer}red word can be defined and
 4420: redefined at any time by using @code{IS} to associate the xt of a
 4421: previously-defined word with it. The previous example becomes:
 4422: 
 4423: @example
 4424: Defer greet
 4425: : foo ... greet ... ;
 4426: : bar ... greet ... ;
 4427: : greet1 ." Good morning" ;
 4428: : greet2 ." Hello" ;
 4429: ' greet2 <IS> greet  \ make greet behave like greet2
 4430: @end example
 4431: 
 4432: A deferred word can be used to improve the statistics-gathering example
 4433: from @ref{User-defined Defining Words}; rather than edit the
 4434: application's source code to change every @code{:} to a @code{my:}, do
 4435: this:
 4436: 
 4437: @example
 4438: : real: : ;     \ retain access to the original
 4439: defer :         \ redefine as a deferred word
 4440: ' my: IS :      \ use special version of :
 4441: \
 4442: \ load application here
 4443: \
 4444: ' real: IS :    \ go back to the original
 4445: @end example
 4446: 
 4447: 
 4448: One thing to note is that @code{<IS>} consumes its name when it is
 4449: executed.  If you want to specify the name at compile time, use
 4450: @code{[IS]}:
 4451: 
 4452: @example
 4453: : set-greet ( xt -- )
 4454:   [IS] greet ;
 4455: 
 4456: ' greet1 set-greet
 4457: @end example
 4458: 
 4459: A deferred word can only inherit default semantics from the xt (because
 4460: that is all that an xt can represent -- @pxref{Tokens for Words} for
 4461: more discussion of this). However, the semantics of the deferred word
 4462: itself can be modified at the time that it is defined. For example:
 4463: 
 4464: @example
 4465: : bar .... ; compile-only
 4466: Defer fred immediate
 4467: Defer jim
 4468: 
 4469: ' bar <IS> jim  \ jim has default semantics
 4470: ' bar <IS> fred \ fred is immediate
 4471: @end example
 4472: 
 4473: doc-defer
 4474: doc-<is>
 4475: doc-[is]
 4476: doc-is
 4477: @comment TODO document these: what's defers [is]
 4478: doc-what's
 4479: doc-defers
 4480: 
 4481: @c Use @code{words-deferred} to see a list of deferred words.
 4482: 
 4483: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
 4484: are provided in @file{compat/defer.fs}.
 4485: 
 4486: 
 4487: @node Aliases, Supplying names, Deferred words, Defining Words
 4488: @subsection Aliases
 4489: @cindex aliases
 4490: 
 4491: The defining word @code{Alias} allows you to define a word by name that
 4492: has the same behaviour as some other word. Here are two situation where
 4493: this can be useful:
 4494: 
 4495: @itemize @bullet
 4496: @item
 4497: When you want access to a word's definition from a different word list
 4498: (for an example of this, see the definition of the @code{Root} word list
 4499: in the Gforth source).
 4500: @item
 4501: When you want to create a synonym; a definition that can be known by
 4502: either of two names (for example, @code{THEN} and @code{ENDIF} are
 4503: aliases).
 4504: @end itemize
 4505: 
 4506: The word whose behaviour the alias is to inherit is represented by an
 4507: xt. Therefore, the alias only inherits default semantics from its
 4508: ancestor. The semantics of the alias itself can be modified at the time
 4509: that it is defined. For example:
 4510: 
 4511: @example
 4512: : foo ... ; immediate
 4513: 
 4514: ' foo Alias bar \ bar is not an immediate word
 4515: ' foo Alias fooby immediate \ fooby is an immediate word
 4516: @end example
 4517: 
 4518: Words that are aliases have the same xt, different headers in the
 4519: dictionary, and consequently different name tokens (@pxref{Tokens for
 4520: Words}) and possibly different immediate flags.  An alias can only have
 4521: default or immediate compilation semantics; you can define aliases for
 4522: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
 4523: 
 4524: doc-alias
 4525: 
 4526: 
 4527: @node Supplying names, Interpretation and Compilation Semantics, Aliases, Defining Words
 4528: @subsection Supplying the name of a defined word
 4529: @cindex names for defined words
 4530: @cindex defining words, name given in a string
 4531: 
 4532: By default, a defining word takes the name for the defined word from the
 4533: input stream. Sometimes you want to supply the name from a string. You
 4534: can do this with:
 4535: 
 4536: doc-nextname
 4537: 
 4538: For example:
 4539: 
 4540: @example
 4541: s" foo" nextname create
 4542: @end example
 4543: 
 4544: @noindent
 4545: is equivalent to:
 4546: 
 4547: @example
 4548: create foo
 4549: @end example
 4550: 
 4551: @noindent
 4552: @code{nextname} works with any defining word, not just @code{:}.
 4553: 
 4554: 
 4555: @node Interpretation and Compilation Semantics, Combined words, Supplying names, Defining Words
 4556: @subsection Interpretation and Compilation Semantics
 4557: @cindex semantics, interpretation and compilation
 4558: 
 4559: @cindex interpretation semantics
 4560: The @dfn{interpretation semantics} of a word are what the text
 4561: interpreter does when it encounters the word in interpret state. It also
 4562: appears in some other contexts, e.g., the execution token returned by
 4563: @code{' @i{word}} identifies the interpretation semantics of
 4564: @i{word} (in other words, @code{' @i{word} execute} is equivalent to
 4565: interpret-state text interpretation of @code{@i{word}}).
 4566: 
 4567: @cindex compilation semantics
 4568: The @dfn{compilation semantics} of a word are what the text interpreter
 4569: does when it encounters the word in compile state. It also appears in
 4570: other contexts, e.g, @code{POSTPONE @i{word}} compiles@footnote{In
 4571: standard terminology, ``appends to the current definition''.} the
 4572: compilation semantics of @i{word}.
 4573: 
 4574: @cindex execution semantics
 4575: The standard also talks about @dfn{execution semantics}. They are used
 4576: only for defining the interpretation and compilation semantics of many
 4577: words. By default, the interpretation semantics of a word are to
 4578: @code{execute} its execution semantics, and the compilation semantics of
 4579: a word are to @code{compile,} its execution semantics.@footnote{In
 4580: standard terminology: The default interpretation semantics are its
 4581: execution semantics; the default compilation semantics are to append its
 4582: execution semantics to the execution semantics of the current
 4583: definition.}
 4584: 
 4585: @comment TODO expand, make it co-operate with new sections on text interpreter.
 4586: 
 4587: @cindex immediate words
 4588: @cindex compile-only words
 4589: You can change the semantics of the most-recently defined word:
 4590: 
 4591: 
 4592: doc-immediate
 4593: doc-compile-only
 4594: doc-restrict
 4595: 
 4596: 
 4597: Note that ticking (@code{'}) a compile-only word gives an error
 4598: (``Interpreting a compile-only word'').
 4599: 
 4600: 
 4601: @node Combined words, ,Interpretation and Compilation Semantics, Defining Words
 4602: @subsection Combined Words
 4603: @cindex combined words
 4604: 
 4605: Gforth allows you to define @dfn{combined words} -- words that have an
 4606: arbitrary combination of interpretation and compilation semantics.
 4607: 
 4608: 
 4609: doc-interpret/compile:
 4610: 
 4611: 
 4612: This feature was introduced for implementing @code{TO} and @code{S"}. I
 4613: recommend that you do not define such words, as cute as they may be:
 4614: they make it hard to get at both parts of the word in some contexts.
 4615: E.g., assume you want to get an execution token for the compilation
 4616: part. Instead, define two words, one that embodies the interpretation
 4617: part, and one that embodies the compilation part.  Once you have done
 4618: that, you can define a combined word with @code{interpret/compile:} for
 4619: the convenience of your users.
 4620: 
 4621: You might try to use this feature to provide an optimizing
 4622: implementation of the default compilation semantics of a word. For
 4623: example, by defining:
 4624: @example
 4625: :noname
 4626:    foo bar ;
 4627: :noname
 4628:    POSTPONE foo POSTPONE bar ;
 4629: interpret/compile: opti-foobar
 4630: @end example
 4631: 
 4632: @noindent
 4633: as an optimizing version of:
 4634: 
 4635: @example
 4636: : foobar
 4637:     foo bar ;
 4638: @end example
 4639: 
 4640: Unfortunately, this does not work correctly with @code{[compile]},
 4641: because @code{[compile]} assumes that the compilation semantics of all
 4642: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
 4643: opti-foobar} would compile compilation semantics, whereas
 4644: @code{[compile] foobar} would compile interpretation semantics.
 4645: 
 4646: @cindex state-smart words (are a bad idea)
 4647: Some people try to use @dfn{state-smart} words to emulate the feature provided
 4648: by @code{interpret/compile:} (words are state-smart if they check
 4649: @code{STATE} during execution). E.g., they would try to code
 4650: @code{foobar} like this:
 4651: 
 4652: @example
 4653: : foobar
 4654:   STATE @@
 4655:   IF ( compilation state )
 4656:     POSTPONE foo POSTPONE bar
 4657:   ELSE
 4658:     foo bar
 4659:   ENDIF ; immediate
 4660: @end example
 4661: 
 4662: Although this works if @code{foobar} is only processed by the text
 4663: interpreter, it does not work in other contexts (like @code{'} or
 4664: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
 4665: for a state-smart word, not for the interpretation semantics of the
 4666: original @code{foobar}; when you execute this execution token (directly
 4667: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
 4668: state, the result will not be what you expected (i.e., it will not
 4669: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
 4670: write them@footnote{For a more detailed discussion of this topic, see
 4671: @cite{@code{State}-smartness -- Why it is Evil and How to Exorcise it} by Anton
 4672: Ertl; presented at EuroForth '98 and available from
 4673: @url{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz}}!
 4674: 
 4675: @cindex defining words with arbitrary semantics combinations
 4676: It is also possible to write defining words that define words with
 4677: arbitrary combinations of interpretation and compilation semantics. In
 4678: general, they look like this:
 4679: 
 4680: @example
 4681: : def-word
 4682:     create-interpret/compile
 4683:     @i{code1}
 4684: interpretation>
 4685:     @i{code2}
 4686: <interpretation
 4687: compilation>
 4688:     @i{code3}
 4689: <compilation ;
 4690: @end example
 4691: 
 4692: For a @i{word} defined with @code{def-word}, the interpretation
 4693: semantics are to push the address of the body of @i{word} and perform
 4694: @i{code2}, and the compilation semantics are to push the address of
 4695: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
 4696: can also be defined like this (except that the defined constants don't
 4697: behave correctly when @code{[compile]}d):
 4698: 
 4699: @example
 4700: : constant ( n "name" -- )
 4701:     create-interpret/compile
 4702:     ,
 4703: interpretation> ( -- n )
 4704:     @@
 4705: <interpretation
 4706: compilation> ( compilation. -- ; run-time. -- n )
 4707:     @@ postpone literal
 4708: <compilation ;
 4709: @end example
 4710: 
 4711: 
 4712: doc-create-interpret/compile
 4713: doc-interpretation>
 4714: doc-<interpretation
 4715: doc-compilation>
 4716: doc-<compilation
 4717: 
 4718: 
 4719: Words defined with @code{interpret/compile:} and
 4720: @code{create-interpret/compile} have an extended header structure that
 4721: differs from other words; however, unless you try to access them with
 4722: plain address arithmetic, you should not notice this. Words for
 4723: accessing the header structure usually know how to deal with this; e.g.,
 4724: @code{'} @i{word} @code{>body} also gives you the body of a word created
 4725: with @code{create-interpret/compile}.
 4726: 
 4727: 
 4728: doc-postpone
 4729: 
 4730: @comment TODO -- expand glossary text for POSTPONE
 4731: 
 4732: @c ----------------------------------------------------------
 4733: @node The Text Interpreter, Tokens for Words, Defining Words, Words
 4734: @section  The Text Interpreter
 4735: @cindex interpreter - outer
 4736: @cindex text interpreter
 4737: @cindex outer interpreter
 4738: 
 4739: @c Should we really describe all these ugly details?  IMO the text
 4740: @c interpreter should be much cleaner, but that may not be possible within
 4741: @c ANS Forth. - anton
 4742: @c nac-> I wanted to explain how it works to show how you can exploit
 4743: @c it in your own programs. When I was writing a cross-compiler, figuring out
 4744: @c some of these gory details was very helpful to me. None of the textbooks
 4745: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
 4746: @c seems to positively avoid going into too much detail for some of
 4747: @c the internals.
 4748: 
 4749: The text interpreter@footnote{This is an expanded version of the
 4750: material in @ref{Introducing the Text Interpreter}.} is an endless loop
 4751: that processes input from the current input device. It is also called
 4752: the outer interpreter, in contrast to the inner interpreter
 4753: (@pxref{Engine}) which executes the compiled Forth code on interpretive
 4754: implementations.
 4755: 
 4756: @cindex interpret state
 4757: @cindex compile state
 4758: The text interpreter operates in one of two states: @dfn{interpret
 4759: state} and @dfn{compile state}. The current state is defined by the
 4760: aptly-named variable, @code{state}.
 4761: 
 4762: This section starts by describing how the text interpreter behaves when
 4763: it is in interpret state, processing input from the user input device --
 4764: the keyboard. This is the mode that a Forth system is in after it starts
 4765: up.
 4766: 
 4767: @cindex input buffer
 4768: @cindex terminal input buffer
 4769: The text interpreter works from an area of memory called the @dfn{input
 4770: buffer}@footnote{When the text interpreter is processing input from the
 4771: keyboard, this area of memory is called the @dfn{terminal input buffer}
 4772: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
 4773: @code{#TIB}.}, which stores your keyboard input when you press the
 4774: @key{RET} key. Starting at the beginning of the input buffer, it skips
 4775: leading spaces (called @dfn{delimiters}) then parses a string (a
 4776: sequence of non-space characters) until it reaches either a space
 4777: character or the end of the buffer. Having parsed a string, it makes two
 4778: attempts to process it:
 4779: 
 4780: @cindex dictionary
 4781: @itemize @bullet
 4782: @item
 4783: It looks for the string in a @dfn{dictionary} of definitions. If the
 4784: string is found, the string names a @dfn{definition} (also known as a
 4785: @dfn{word}) and the dictionary search returns information that allows
 4786: the text interpreter to perform the word's @dfn{interpretation
 4787: semantics}. In most cases, this simply means that the word will be
 4788: executed.
 4789: @item
 4790: If the string is not found in the dictionary, the text interpreter
 4791: attempts to treat it as a number, using the rules described in
 4792: @ref{Number Conversion}. If the string represents a legal number in the
 4793: current radix, the number is pushed onto a parameter stack (the data
 4794: stack for integers, the floating-point stack for floating-point
 4795: numbers).
 4796: @end itemize
 4797: 
 4798: If both attempts fail, or if the word is found in the dictionary but has
 4799: no interpretation semantics@footnote{This happens if the word was
 4800: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
 4801: remainder of the input buffer, issues an error message and waits for
 4802: more input. If one of the attempts succeeds, the text interpreter
 4803: repeats the parsing process until the whole of the input buffer has been
 4804: processed, at which point it prints the status message ``@code{ ok}''
 4805: and waits for more input.
 4806: 
 4807: @cindex parse area
 4808: The text interpreter keeps track of its position in the input buffer by
 4809: updating a variable called @code{>IN} (pronounced ``to-in''). The value
 4810: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
 4811: of the input buffer. The region from offset @code{>IN @@} to the end of
 4812: the input buffer is called the @dfn{parse area}@footnote{In other words,
 4813: the text interpreter processes the contents of the input buffer by
 4814: parsing strings from the parse area until the parse area is empty.}.
 4815: This example shows how @code{>IN} changes as the text interpreter parses
 4816: the input buffer:
 4817: 
 4818: @example
 4819: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
 4820:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
 4821: 
 4822: 1 2 3 remaining + remaining . 
 4823: 
 4824: : foo 1 2 3 remaining SWAP remaining ;
 4825: @end example
 4826: 
 4827: @noindent
 4828: The result is:
 4829: 
 4830: @example
 4831: ->+ remaining .<-
 4832: ->.<-5  ok
 4833: 
 4834: ->SWAP remaining ;-<
 4835: ->;<-  ok
 4836: @end example
 4837: 
 4838: @cindex parsing words
 4839: The value of @code{>IN} can also be modified by a word in the input
 4840: buffer that is executed by the text interpreter.  This means that a word
 4841: can ``trick'' the text interpreter into either skipping a section of the
 4842: input buffer@footnote{This is how parsing words work.} or into parsing a
 4843: section twice. For example:
 4844: 
 4845: @example
 4846: : lat ." <<lat>>" ;
 4847: : flat ." <<flat>>" >IN DUP @@ 3 - SWAP ! ;
 4848: @end example
 4849: 
 4850: @noindent
 4851: When @code{flat} is executed, this output is produced@footnote{Exercise
 4852: for the reader: what would happen if the @code{3} were replaced with
 4853: @code{4}?}:
 4854: 
 4855: @example
 4856: <<flat>><<lat>>
 4857: @end example
 4858: 
 4859: @noindent
 4860: Two important notes about the behaviour of the text interpreter:
 4861: 
 4862: @itemize @bullet
 4863: @item
 4864: It processes each input string to completion before parsing additional
 4865: characters from the input buffer.
 4866: @item
 4867: It treats the input buffer as a read-only region (and so must your code).
 4868: @end itemize
 4869: 
 4870: @noindent
 4871: When the text interpreter is in compile state, its behaviour changes in
 4872: these ways:
 4873: 
 4874: @itemize @bullet
 4875: @item
 4876: If a parsed string is found in the dictionary, the text interpreter will
 4877: perform the word's @dfn{compilation semantics}. In most cases, this
 4878: simply means that the execution semantics of the word will be appended
 4879: to the current definition.
 4880: @item
 4881: When a number is encountered, it is compiled into the current definition
 4882: (as a literal) rather than being pushed onto a parameter stack.
 4883: @item
 4884: If an error occurs, @code{state} is modified to put the text interpreter
 4885: back into interpret state.
 4886: @item
 4887: Each time a line is entered from the keyboard, Gforth prints
 4888: ``@code{ compiled}'' rather than `` @code{ok}''.
 4889: @end itemize
 4890: 
 4891: @cindex text interpreter - input sources
 4892: When the text interpreter is using an input device other than the
 4893: keyboard, its behaviour changes in these ways:
 4894: 
 4895: @itemize @bullet
 4896: @item
 4897: When the parse area is empty, the text interpreter attempts to refill
 4898: the input buffer from the input source. When the input source is
 4899: exhausted, the input source is set back to the user input device.
 4900: @item
 4901: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
 4902: time the parse area is emptied.
 4903: @item
 4904: If an error occurs, the input source is set back to the user input
 4905: device.
 4906: @end itemize
 4907: 
 4908: @ref{Input Sources} describes this in more detail.
 4909: 
 4910: 
 4911: doc->in
 4912: doc-source
 4913: 
 4914: doc-tib
 4915: doc-#tib
 4916: 
 4917: 
 4918: @menu
 4919: * Input Sources::
 4920: * Number Conversion::
 4921: * Interpret/Compile states::
 4922: * Literals::
 4923: * Interpreter Directives::
 4924: @end menu
 4925: 
 4926: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
 4927: @subsection Input Sources
 4928: @cindex input sources
 4929: @cindex text interpreter - input sources
 4930: 
 4931: By default, the text interpreter processes input from the user input
 4932: device (the keyboard) when Forth starts up. The text interpreter can
 4933: process input from any of these sources:
 4934: 
 4935: @itemize @bullet
 4936: @item
 4937: The user input device -- the keyboard.
 4938: @item
 4939: A file, using the words described in @ref{Forth source files}.
 4940: @item
 4941: A block, using the words described in @ref{Blocks}.
 4942: @item
 4943: A text string, using @code{evaluate}.
 4944: @end itemize
 4945: 
 4946: A program can identify the current input device from the values of
 4947: @code{source-id} and @code{blk}.
 4948: 
 4949: 
 4950: doc-source-id
 4951: doc-blk
 4952: 
 4953: doc-save-input
 4954: doc-restore-input
 4955: 
 4956: doc-evaluate
 4957: 
 4958: 
 4959: 
 4960: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
 4961: @subsection Number Conversion
 4962: @cindex number conversion
 4963: @cindex double-cell numbers, input format
 4964: @cindex input format for double-cell numbers
 4965: @cindex single-cell numbers, input format
 4966: @cindex input format for single-cell numbers
 4967: @cindex floating-point numbers, input format
 4968: @cindex input format for floating-point numbers
 4969: 
 4970: This section describes the rules that the text interpreter uses when it
 4971: tries to convert a string into a number.
 4972: 
 4973: Let <digit> represent any character that is a legal digit in the current
 4974: number base@footnote{For example, 0-9 when the number base is decimal or
 4975: 0-9, A-F when the number base is hexadecimal.}.
 4976: 
 4977: Let <decimal digit> represent any character in the range 0-9.
 4978: 
 4979: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
 4980: in the braces (@i{a} or @i{b} or neither).
 4981: 
 4982: Let * represent any number of instances of the previous character
 4983: (including none).
 4984: 
 4985: Let any other character represent itself.
 4986: 
 4987: @noindent
 4988: Now, the conversion rules are:
 4989: 
 4990: @itemize @bullet
 4991: @item
 4992: A string of the form <digit><digit>* is treated as a single-precision
 4993: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
 4994: @item
 4995: A string of the form -<digit><digit>* is treated as a single-precision
 4996: (cell-sized) negative integer, and is represented using 2's-complement
 4997: arithmetic. Examples are -45 -5681 -0
 4998: @item
 4999: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
 5000: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
 5001: (all three of these represent the same number).
 5002: @item
 5003: A string of the form -<digit><digit>*.<digit>* is treated as a
 5004: double-precision (double-cell-sized) negative integer, and is
 5005: represented using 2's-complement arithmetic. Examples are -3465. -3.465
 5006: -34.65 (all three of these represent the same number).
 5007: @item
 5008: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
 5009: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
 5010: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
 5011: number) +12.E-4
 5012: @end itemize
 5013: 
 5014: By default, the number base used for integer number conversion is given
 5015: by the contents of the variable @code{base}.  Note that a lot of
 5016: confusion can result from unexpected values of @code{base}.  If you
 5017: change @code{base} anywhere, make sure to save the old value and restore
 5018: it afterwards.  In general I recommend keeping @code{base} decimal, and
 5019: using the prefixes described below for the popular non-decimal bases.
 5020: 
 5021: doc-dpl
 5022: doc-base
 5023: doc-hex
 5024: doc-decimal
 5025: 
 5026: 
 5027: @cindex '-prefix for character strings
 5028: @cindex &-prefix for decimal numbers
 5029: @cindex %-prefix for binary numbers
 5030: @cindex $-prefix for hexadecimal numbers
 5031: Gforth allows you to override the value of @code{base} by using a
 5032: prefix@footnote{Some Forth implementations provide a similar scheme by
 5033: implementing @code{$} etc. as parsing words that process the subsequent
 5034: number in the input stream and push it onto the stack. For example, see
 5035: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
 5036: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
 5037: is required between the prefix and the number.} before the first digit
 5038: of an (integer) number. Four prefixes are supported:
 5039: 
 5040: @itemize @bullet
 5041: @item
 5042: @code{&} -- decimal
 5043: @item
 5044: @code{%} -- binary
 5045: @item
 5046: @code{$} -- hexadecimal
 5047: @item
 5048: @code{'} -- base @code{max-char+1}
 5049: @end itemize
 5050: 
 5051: Here are some examples, with the equivalent decimal number shown after
 5052: in braces:
 5053: 
 5054: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
 5055: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
 5056: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
 5057: &905 (905), $abc (2478), $ABC (2478).
 5058: 
 5059: @cindex number conversion - traps for the unwary
 5060: @noindent
 5061: Number conversion has a number of traps for the unwary:
 5062: 
 5063: @itemize @bullet
 5064: @item
 5065: You cannot determine the current number base using the code sequence
 5066: @code{base @@ .} -- the number base is always 10 in the current number
 5067: base. Instead, use something like @code{base @@ dec.}
 5068: @item
 5069: If the number base is set to a value greater than 14 (for example,
 5070: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
 5071: it to be intepreted as either a single-precision integer or a
 5072: floating-point number (Gforth treats it as an integer). The ambiguity
 5073: can be resolved by explicitly stating the sign of the mantissa and/or
 5074: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
 5075: ambiguity arises; either representation will be treated as a
 5076: floating-point number.
 5077: @item
 5078: There is a word @code{bin} but it does @i{not} set the number base!
 5079: It is used to specify file types.
 5080: @item
 5081: ANS Forth requires the @code{.} of a double-precision number to
 5082: be the final character in the string. Allowing the @code{.} to be
 5083: anywhere after the first digit is a Gforth extension.
 5084: @item
 5085: The number conversion process does not check for overflow.
 5086: @item
 5087: In Gforth, number conversion to floating-point numbers always use base
 5088: 10, irrespective of the value of @code{base}. In ANS Forth,
 5089: conversion to floating-point numbers whilst the value of
 5090: @code{base} is not 10 is an ambiguous condition.
 5091: @end itemize
 5092: 
 5093: @ref{Input} describes words that you can use to read numbers into your
 5094: programs.
 5095: 
 5096: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
 5097: @subsection Interpret/Compile states
 5098: @cindex Interpret/Compile states
 5099: 
 5100: A standard program is not permitted to change @code{state}
 5101: explicitly. However, it can change @code{state} implicitly, using the
 5102: words @code{[} and @code{]}. When @code{[} is executed it switches
 5103: @code{state} to interpret state, and therefore the text interpreter
 5104: starts interpreting. When @code{]} is executed it switches @code{state}
 5105: to compile state and therefore the text interpreter starts
 5106: compiling. The most common usage for these words is for switching into
 5107: interpret state and back from within a colon definition; this technique
 5108: can be used to compile a literal (@pxref{Literals} for an example) or
 5109: for conditional compilation (@pxref{Interpreter Directives} for an
 5110: example).
 5111: 
 5112: 
 5113: @c This is a bad example: It's non-standard, and it's not necessary.
 5114: @c However, I can't think of a good example for switching into compile
 5115: @c state when there is no current word (@code{state}-smart words are not a
 5116: @c good reason).  So maybe we should use an example for switching into
 5117: @c interpret @code{state} in a colon def. - anton
 5118: @c nac-> I agree. I started out by putting in the example, then realised
 5119: @c that it was non-ANS, so wrote more words around it. I hope this
 5120: @c re-written version is acceptable to you. I do want to keep the example
 5121: @c as it is helpful for showing what is and what is not portable, particularly
 5122: @c where it outlaws a style in common use.
 5123: 
 5124: 
 5125: @code{[} and @code{]} also give you the ability to switch into compile
 5126: state and back, but we cannot think of any useful Standard application
 5127: for this ability. Pre-ANS Forth textbooks have examples like this:
 5128: 
 5129: @example
 5130: : AA ." this is A" ;
 5131: : BB ." this is B" ;
 5132: : CC ." this is C" ;
 5133: 
 5134: create table ] aa bb cc [
 5135: 
 5136: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
 5137:   cells table + @ execute ;
 5138: @end example
 5139: 
 5140: This example builds a jump table; @code{0 go} will display ``@code{this
 5141: is A}''. Using @code{[} and @code{]} in this example is equivalent to
 5142: defining @code{table} like this:
 5143: 
 5144: @example
 5145: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
 5146: @end example
 5147: 
 5148: The problem with this code is that the definition of @code{table} is not
 5149: portable -- it @i{compile}s execution tokens into code space. Whilst it
 5150: @i{may} work on systems where code space and data space co-incide, the
 5151: Standard only allows data space to be assigned for a @code{CREATE}d
 5152: word. In addition, the Standard only allows @code{@@} to access data
 5153: space, whilst this example is using it to access code space. The only
 5154: portable, Standard way to build this table is to build it in data space,
 5155: like this:
 5156: 
 5157: @example
 5158: create table ' aa , ' bb , ' cc ,
 5159: @end example
 5160: 
 5161: doc-state
 5162: doc-[
 5163: doc-]
 5164: 
 5165: 
 5166: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
 5167: @subsection Literals
 5168: @cindex Literals
 5169: 
 5170: Often, you want to use a number within a colon definition. When you do
 5171: this, the text interpreter automatically compiles the number as a
 5172: @i{literal}. A literal is a number whose run-time effect is to be pushed
 5173: onto the stack.  If you had to do some maths to generate the number, you
 5174: might write it like this:
 5175: 
 5176: @example
 5177: : HOUR-TO-SEC ( n1 -- n2 )
 5178:   60 *      \ to minutes
 5179:   60 * ;    \ to seconds
 5180: @end example
 5181: 
 5182: It is very clear what this definition is doing, but it's inefficient
 5183: since it is performing 2 multiples at run-time. An alternative would be
 5184: to write:
 5185: 
 5186: @example
 5187: : HOUR-TO-SEC ( n1 -- n2 )
 5188:   3600 * ;  \ to seconds
 5189: @end example
 5190: 
 5191: Which does the same thing, and has the advantage of using a single
 5192: multiply. Ideally, we'd like the efficiency of the second with the
 5193: readability of the first.
 5194: 
 5195: @code{Literal} allows us to achieve that. It takes a number from the
 5196: stack and lays it down in the current definition just as though the
 5197: number had been typed directly into the definition. Our first attempt
 5198: might look like this:
 5199: 
 5200: @example
 5201: 60          \ mins per hour
 5202: 60 *        \ seconds per minute
 5203: : HOUR-TO-SEC ( n1 -- n2 )
 5204:   Literal * ;  \ to seconds
 5205: @end example
 5206: 
 5207: But this produces the error message @code{unstructured}. What happened?
 5208: The stack notation for @code{:} is (@i{ -- colon-sys}) and the size of
 5209: @i{colon-sys} is implementation-defined. In other words, once we start a
 5210: colon definition we can't portably access anything that was on the stack
 5211: before the definition began@footnote{@cite{Two Problems in ANS Forth},
 5212: by Thomas Worthington; Forth Dimensions 20(2) pages 32--34 describes
 5213: some situations where you might want to access stack items above
 5214: colon-sys, and provides a solution to the problem.}. The correct way of
 5215: solving this problem in this instance is to use @code{[ ]} like this:
 5216: 
 5217: @example
 5218: : HOUR-TO-SEC ( n1 -- n2 )
 5219:   [ 60          \ minutes per hour
 5220:     60 * ]      \ seconds per minute
 5221:   LITERAL * ;   \ to seconds
 5222: @end example
 5223: 
 5224: 
 5225: doc-literal
 5226: doc-]L
 5227: doc-2literal
 5228: doc-fliteral
 5229: 
 5230: 
 5231: @node Interpreter Directives, , Literals, The Text Interpreter
 5232: @subsection Interpreter Directives
 5233: @cindex interpreter directives
 5234: 
 5235: These words are usually used in interpret state; typically to control
 5236: which parts of a source file are processed by the text
 5237: interpreter. There are only a few ANS Forth Standard words, but Gforth
 5238: supplements these with a rich set of immediate control structure words
 5239: to compensate for the fact that the non-immediate versions can only be
 5240: used in compile state (@pxref{Control Structures}). Typical usages:
 5241: 
 5242: @example
 5243: FALSE Constant ASSEMBLER
 5244: .
 5245: .
 5246: ASSEMBLER [IF]
 5247: : ASSEMBLER-FEATURE
 5248:   ...
 5249: ;
 5250: [ENDIF]
 5251: .
 5252: .
 5253: : SEE
 5254:   ... \ general-purpose SEE code
 5255:   [ ASSEMBLER [IF] ]
 5256:   ... \ assembler-specific SEE code
 5257:   [ [ENDIF] ]
 5258: ;
 5259: @end example
 5260: 
 5261: 
 5262: doc-[IF]
 5263: doc-[ELSE]
 5264: doc-[THEN]
 5265: doc-[ENDIF]
 5266: 
 5267: doc-[IFDEF]
 5268: doc-[IFUNDEF]
 5269: 
 5270: doc-[?DO]
 5271: doc-[DO]
 5272: doc-[FOR]
 5273: doc-[LOOP]
 5274: doc-[+LOOP]
 5275: doc-[NEXT]
 5276: 
 5277: doc-[BEGIN]
 5278: doc-[UNTIL]
 5279: doc-[AGAIN]
 5280: doc-[WHILE]
 5281: doc-[REPEAT]
 5282: 
 5283: 
 5284: 
 5285: 
 5286: @c -------------------------------------------------------------
 5287: @node Tokens for Words, Word Lists, The Text Interpreter, Words
 5288: @section Tokens for Words
 5289: @cindex tokens for words
 5290: 
 5291: This section describes the creation and use of tokens that represent
 5292: words.
 5293: 
 5294: Named words have information stored in their header space entries to
 5295: indicate any non-default semantics (@pxref{Interpretation and
 5296: Compilation Semantics}). The semantics can be modified, using
 5297: @code{immediate} and/or @code{compile-only}, at the time that the words
 5298: are defined. Unnamed words have (by definition) no header space
 5299: entry, and therefore must have default semantics.
 5300: 
 5301: Named words have interpretation and compilation semantics. Unnamed words
 5302: just have execution semantics.
 5303: 
 5304: @cindex xt
 5305: @cindex execution token
 5306: The execution semantics of an unnamed word are represented by an
 5307: @dfn{execution token} (@i{xt}). As explained in @ref{Supplying names},
 5308: the execution token of the last word defined can be produced with
 5309: @code{lastxt}.
 5310: 
 5311: The interpretation semantics of a named word are also represented by an
 5312: execution token. You can produce the execution token using @code{'} or
 5313: @code{[']}. A simple example shows the difference between the two:
 5314: 
 5315: @example
 5316: : greet ( -- )   ." Hello" ;
 5317: : foo ( -- xt )  ['] greet execute ; \ ['] parses greet at compile-time
 5318: : bar ( -- )     ' execute ; \  '  parses at run-time
 5319: 
 5320: \ the next four lines all do the same thing
 5321: foo
 5322: bar greet
 5323: greet
 5324: ' greet EXECUTE
 5325: @end example
 5326: 
 5327: An execution token occupies one cell.
 5328: @cindex code field address
 5329: @cindex CFA
 5330: In Gforth, the abstract data type @i{execution token} is implemented
 5331: as a code field address (CFA).
 5332: @comment TODO note that the standard does not say what it represents..
 5333: @comment and you cannot necessarily compile it in all Forths (eg native
 5334: @comment compilers?).
 5335: 
 5336: For literals, use @code{'} in interpreted code and @code{[']} in
 5337: compiled code. Gforth's @code{'} and @code{[']} behave somewhat
 5338: unusually by complaining about compile-only words. To get the execution
 5339: token for a compile-only word @i{name}, use @code{COMP' @i{name} DROP}
 5340: or @code{[COMP'] @i{name} DROP}.
 5341: 
 5342: @cindex compilation token
 5343: The compilation semantics of a named word are represented by a
 5344: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
 5345: @i{xt} is an execution token. The compilation semantics represented by
 5346: the compilation token can be performed with @code{execute}, which
 5347: consumes the whole compilation token, with an additional stack effect
 5348: determined by the represented compilation semantics.
 5349: 
 5350: At present, the @i{w} part of a compilation token is an execution token,
 5351: and the @i{xt} part represents either @code{execute} or
 5352: @code{compile,}@footnote{Depending upon the compilation semantics of the
 5353: word. If the word has default compilation semantics, the @i{xt} will
 5354: represent @code{compile,}. Otherwise (e.g., for immediate words), the
 5355: @i{xt} will represent @code{execute}.}. However, don't rely on that
 5356: knowledge, unless necessary; future versions of Gforth may introduce
 5357: unusual compilation tokens (e.g., a compilation token that represents
 5358: the compilation semantics of a literal).
 5359: 
 5360: You can compile the compilation semantics with @code{postpone,}. I.e.,
 5361: @code{COMP' @i{word} postpone,} is equivalent to @code{postpone
 5362: @i{word}}.
 5363: 
 5364: @cindex name token
 5365: @cindex name field address
 5366: @cindex NFA
 5367: Named words are also represented by the @dfn{name token}, (@i{nt}). In
 5368: Gforth, the abstract data type @emph{name token} is implemented as a
 5369: name field address (NFA).
 5370: 
 5371: 
 5372: doc-execute
 5373: doc-compile,
 5374: doc-[']
 5375: doc-'
 5376: doc-[comp']
 5377: doc-comp'
 5378: doc-postpone,
 5379: 
 5380: doc-find-name
 5381: doc-name>int
 5382: doc-name?int
 5383: doc-name>comp
 5384: doc-name>string
 5385: 
 5386: 
 5387: @c -------------------------------------------------------------
 5388: @node Word Lists, Environmental Queries, Tokens for Words, Words
 5389: @section Word Lists
 5390: @cindex word lists
 5391: @cindex header space
 5392: 
 5393: A wordlist is a list of named words; you can add new words and look up
 5394: words by name (and you can remove words in a restricted way with
 5395: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
 5396: 
 5397: @cindex search order stack
 5398: The text interpreter searches the wordlists present in the search order
 5399: (a stack of wordlists), from the top to the bottom.  Within each
 5400: wordlist, the search starts conceptually at the newest word; i.e., if
 5401: two words in a wordlist have the same name, the newer word is found.
 5402: 
 5403: @cindex compilation word list
 5404: New words are added to the @dfn{compilation wordlist} (aka current
 5405: wordlist).
 5406: 
 5407: @cindex wid
 5408: A word list is identified by a cell-sized word list identifier (@i{wid})
 5409: in much the same way as a file is identified by a file handle. The
 5410: numerical value of the wid has no (portable) meaning, and might change
 5411: from session to session.
 5412: 
 5413: The ANS Forth ``Search order'' word set is intended to provide a set of
 5414: low-level tools that allow various different schemes to be
 5415: implemented. Gforth provides @code{vocabulary}, a traditional Forth
 5416: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
 5417: Forth.
 5418: 
 5419: @comment TODO: locals section refers to here, saying that every word list (aka
 5420: @comment vocabulary) has its own methods for searching etc. Need to document that.
 5421: 
 5422: @comment TODO: document markers, reveal, tables, mappedwordlist
 5423: 
 5424: @comment the gforthman- prefix is used to pick out the true definition of a
 5425: @comment word from the source files, rather than some alias.
 5426: 
 5427: doc-forth-wordlist
 5428: doc-definitions
 5429: doc-get-current
 5430: doc-set-current
 5431: doc-get-order
 5432: doc---gforthman-set-order
 5433: doc-wordlist
 5434: doc-table
 5435: doc-push-order
 5436: doc-previous
 5437: doc-also
 5438: doc---gforthman-forth
 5439: doc-only
 5440: doc---gforthman-order
 5441: 
 5442: doc-find
 5443: doc-search-wordlist
 5444: 
 5445: doc-words
 5446: doc-vlist
 5447: @c doc-words-deferred
 5448: 
 5449: doc-mappedwordlist
 5450: doc-root
 5451: doc-vocabulary
 5452: doc-seal
 5453: doc-vocs
 5454: doc-current
 5455: doc-context
 5456: 
 5457: 
 5458: @menu
 5459: * Why use word lists?::
 5460: * Word list examples::
 5461: @end menu
 5462: 
 5463: @node Why use word lists?, Word list examples, Word Lists, Word Lists
 5464: @subsection Why use word lists?
 5465: @cindex word lists - why use them?
 5466: 
 5467: Here are some reasons for using multiple word lists:
 5468: 
 5469: @itemize @bullet
 5470: @item
 5471: To improve compilation speed by reducing the number of header space
 5472: entries that must be searched. This is achieved by creating a new
 5473: word list that contains all of the definitions that are used in the
 5474: definition of a Forth system but which would not usually be used by
 5475: programs running on that system. That word list would be on the search
 5476: list when the Forth system was compiled but would be removed from the
 5477: search list for normal operation. This can be a useful technique for
 5478: low-performance systems (for example, 8-bit processors in embedded
 5479: systems) but is unlikely to be necessary in high-performance desktop
 5480: systems.
 5481: @item
 5482: To prevent a set of words from being used outside the context in which
 5483: they are valid. Two classic examples of this are an integrated editor
 5484: (all of the edit commands are defined in a separate word list; the
 5485: search order is set to the editor word list when the editor is invoked;
 5486: the old search order is restored when the editor is terminated) and an
 5487: integrated assembler (the op-codes for the machine are defined in a
 5488: separate word list which is used when a @code{CODE} word is defined).
 5489: @item
 5490: To prevent a name-space clash between multiple definitions with the same
 5491: name. For example, when building a cross-compiler you might have a word
 5492: @code{IF} that generates conditional code for your target system. By
 5493: placing this definition in a different word list you can control whether
 5494: the host system's @code{IF} or the target system's @code{IF} get used in
 5495: any particular context by controlling the order of the word lists on the
 5496: search order stack.
 5497: @end itemize
 5498: 
 5499: @node Word list examples, ,Why use word lists?, Word Lists
 5500: @subsection Word list examples
 5501: @cindex word lists - examples
 5502: 
 5503: Here is an example of creating and using a new wordlist using ANS
 5504: Forth Standard words:
 5505: 
 5506: @example
 5507: wordlist constant my-new-words-wordlist
 5508: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
 5509: 
 5510: \ add it to the search order
 5511: also my-new-words
 5512: 
 5513: \ alternatively, add it to the search order and make it
 5514: \ the compilation word list
 5515: also my-new-words definitions
 5516: \ type "order" to see the problem
 5517: @end example
 5518: 
 5519: The problem with this example is that @code{order} has no way to
 5520: associate the name @code{my-new-words} with the wid of the word list (in
 5521: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
 5522: that has no associated name). There is no Standard way of associating a
 5523: name with a wid.
 5524: 
 5525: In Gforth, this example can be re-coded using @code{vocabulary}, which
 5526: associates a name with a wid:
 5527: 
 5528: @example
 5529: vocabulary my-new-words
 5530: 
 5531: \ add it to the search order
 5532: also my-new-words
 5533: 
 5534: \ alternatively, add it to the search order and make it
 5535: \ the compilation word list
 5536: my-new-words definitions
 5537: \ type "order" to see that the problem is solved
 5538: @end example
 5539: 
 5540: @c -------------------------------------------------------------
 5541: @node Environmental Queries, Files, Word Lists, Words
 5542: @section Environmental Queries
 5543: @cindex environmental queries
 5544: 
 5545: ANS Forth introduced the idea of ``environmental queries'' as a way
 5546: for a program running on a system to determine certain characteristics of the system.
 5547: The Standard specifies a number of strings that might be recognised by a system.
 5548: 
 5549: The Standard requires that the header space used for environmental queries
 5550: be distinct from the header space used for definitions.
 5551: 
 5552: Typically, environmental queries are supported by creating a set of
 5553: definitions in a word list that is @i{only} used during environmental
 5554: queries; that is what Gforth does. There is no Standard way of adding
 5555: definitions to the set of recognised environmental queries, but any
 5556: implementation that supports the loading of optional word sets must have
 5557: some mechanism for doing this (after loading the word set, the
 5558: associated environmental query string must return @code{true}). In
 5559: Gforth, the word list used to honour environmental queries can be
 5560: manipulated just like any other word list.
 5561: 
 5562: 
 5563: doc-environment?
 5564: doc-environment-wordlist
 5565: 
 5566: doc-gforth
 5567: doc-os-class
 5568: 
 5569: 
 5570: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
 5571: returning two items on the stack, querying it using @code{environment?}
 5572: will return an additional item; the @code{true} flag that shows that the
 5573: string was recognised.
 5574: 
 5575: @comment TODO Document the standard strings or note where they are documented herein
 5576: 
 5577: Here are some examples of using environmental queries:
 5578: 
 5579: @example
 5580: s" address-unit-bits" environment? 0=
 5581: [IF]
 5582:      cr .( environmental attribute address-units-bits unknown... ) cr
 5583: [THEN]
 5584: 
 5585: s" block" environment? [IF] DROP include block.fs [THEN]
 5586: 
 5587: s" gforth" environment? [IF] 2DROP include compat/vocabulary.fs [THEN]
 5588: 
 5589: s" gforth" environment? [IF] .( Gforth version ) TYPE
 5590:                         [ELSE] .( Not Gforth..) [THEN]
 5591: @end example
 5592: 
 5593: 
 5594: Here is an example of adding a definition to the environment word list:
 5595: 
 5596: @example
 5597: get-current environment-wordlist set-current
 5598: true constant block
 5599: true constant block-ext
 5600: set-current
 5601: @end example
 5602: 
 5603: You can see what definitions are in the environment word list like this:
 5604: 
 5605: @example
 5606: get-order 1+ environment-wordlist swap set-order words previous
 5607: @end example
 5608: 
 5609: 
 5610: @c -------------------------------------------------------------
 5611: @node Files, Blocks, Environmental Queries, Words
 5612: @section Files
 5613: @cindex files
 5614: @cindex I/O - file-handling
 5615: 
 5616: Gforth provides facilities for accessing files that are stored in the
 5617: host operating system's file-system. Files that are processed by Gforth
 5618: can be divided into two categories:
 5619: 
 5620: @itemize @bullet
 5621: @item
 5622: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
 5623: @item
 5624: Files that are processed by some other program (@dfn{general files}).
 5625: @end itemize
 5626: 
 5627: doc-loadfilename
 5628: doc-sourcefilename
 5629: doc-sourceline#
 5630: 
 5631: @menu
 5632: * Forth source files::
 5633: * General files::         
 5634: * Search Paths::                 
 5635: * Forth Search Paths::    
 5636: * General Search Paths::        
 5637: @end menu
 5638: 
 5639: 
 5640: @c -------------------------------------------------------------
 5641: @node Forth source files, General files, Files, Files
 5642: @subsection Forth source files
 5643: @cindex including files
 5644: @cindex Forth source files
 5645: 
 5646: The simplest way to interpret the contents of a file is to use one of
 5647: these two formats:
 5648: 
 5649: @example
 5650: include mysource.fs
 5651: s" mysource.fs" included
 5652: @end example
 5653: 
 5654: Sometimes you want to include a file only if it is not included already
 5655: (by, say, another source file). In that case, you can use one of these
 5656: three formats:
 5657: 
 5658: @example
 5659: require mysource.fs
 5660: needs mysource.fs
 5661: s" mysource.fs" required
 5662: @end example
 5663: 
 5664: @cindex stack effect of included files
 5665: @cindex including files, stack effect
 5666: It is good practice to write your source files such that interpreting them
 5667: does not change the stack. Source files designed in this way can be used with
 5668: @code{required} and friends without complications. For example:
 5669: 
 5670: @example
 5671: 1 require foo.fs drop
 5672: @end example
 5673: 
 5674: 
 5675: doc-include-file
 5676: doc-included
 5677: doc-included?
 5678: doc-include
 5679: doc-required
 5680: doc-require
 5681: doc-needs
 5682: doc-init-included-files
 5683: 
 5684: 
 5685: A definition in ANS Forth for @code{required} is provided in
 5686: @file{compat/required.fs}.
 5687: 
 5688: @c -------------------------------------------------------------
 5689: @node General files, Search Paths, Forth source files, Files
 5690: @subsection General files
 5691: @cindex general files
 5692: @cindex file-handling
 5693: 
 5694: Files are opened/created by name and type. The following types are
 5695: recognised:
 5696: 
 5697: 
 5698: doc-r/o
 5699: doc-r/w
 5700: doc-w/o
 5701: doc-bin
 5702: 
 5703: 
 5704: When a file is opened/created, it returns a file identifier,
 5705: @i{wfileid} that is used for all other file commands. All file
 5706: commands also return a status value, @i{wior}, that is 0 for a
 5707: successful operation and an implementation-defined non-zero value in the
 5708: case of an error.
 5709: 
 5710: 
 5711: doc-open-file
 5712: doc-create-file
 5713: 
 5714: doc-close-file
 5715: doc-delete-file
 5716: doc-rename-file
 5717: doc-read-file
 5718: doc-read-line
 5719: doc-write-file
 5720: doc-write-line
 5721: doc-emit-file
 5722: doc-flush-file
 5723: 
 5724: doc-file-status
 5725: doc-file-position
 5726: doc-reposition-file
 5727: doc-file-size
 5728: doc-resize-file
 5729: 
 5730: 
 5731: @c ---------------------------------------------------------
 5732: @node Search Paths, Forth Search Paths, General files, Files
 5733: @subsection Search Paths
 5734: @cindex path for @code{included}
 5735: @cindex file search path
 5736: @cindex @code{include} search path
 5737: @cindex search path for files
 5738: 
 5739: If you specify an absolute filename (i.e., a filename starting with
 5740: @file{/} or @file{~}, or with @file{:} in the second position (as in
 5741: @samp{C:...})) for @code{included} and friends, that file is included
 5742: just as you would expect.
 5743: 
 5744: For relative filenames, Gforth uses a search path similar to Forth's
 5745: search order (@pxref{Word Lists}). It tries to find the given filename
 5746: in the directories present in the path, and includes the first one it
 5747: finds. There are separate search paths for Forth source files and
 5748: general files.
 5749: 
 5750: If the search path contains the directory @file{.} (as it should), this
 5751: refers to the directory that the present file was @code{included}
 5752: from. This allows files to include other files relative to their own
 5753: position (irrespective of the current working directory or the absolute
 5754: position).  This feature is essential for libraries consisting of
 5755: several files, where a file may include other files from the library.
 5756: It corresponds to @code{#include "..."} in C. If the current input
 5757: source is not a file, @file{.} refers to the directory of the innermost
 5758: file being included, or, if there is no file being included, to the
 5759: current working directory.
 5760: 
 5761: Use @file{~+} to refer to the current working directory (as in the
 5762: @code{bash}).
 5763: 
 5764: If the filename starts with @file{./}, the search path is not searched
 5765: (just as with absolute filenames), and the @file{.} has the same meaning
 5766: as described above.
 5767: 
 5768: @c ---------------------------------------------------------
 5769: @node Forth Search Paths, General Search Paths, Search Paths, Files
 5770: @subsubsection Forth Search Paths
 5771: @cindex search path control - Forth
 5772: 
 5773: The search path is initialized when you start Gforth (@pxref{Invoking
 5774: Gforth}). You can display it and change it using these words:
 5775: 
 5776: 
 5777: doc-.fpath
 5778: doc-fpath+
 5779: doc-fpath=
 5780: doc-open-fpath-file
 5781: 
 5782: 
 5783: @noindent
 5784: Here is an example of using @code{fpath} and @code{require}:
 5785: 
 5786: @example
 5787: fpath= /usr/lib/forth/|./
 5788: require timer.fs
 5789: @end example
 5790: 
 5791: @c ---------------------------------------------------------
 5792: @node General Search Paths,  , Forth Search Paths, Files
 5793: @subsubsection General Search Paths
 5794: @cindex search path control - for user applications
 5795: 
 5796: Your application may need to search files in several directories, like
 5797: @code{included} does. To facilitate this, Gforth allows you to define
 5798: and use your own search paths, by providing generic equivalents of the
 5799: Forth search path words:
 5800: 
 5801: 
 5802: doc-.path
 5803: doc-path+
 5804: doc-path=
 5805: doc-open-path-file
 5806: 
 5807: 
 5808: Here's an example of creating a search path:
 5809: 
 5810: @example
 5811: \ Make a buffer for the path:
 5812: create mypath   100 chars ,     \ maximum length (is checked)
 5813:                 0 ,             \ real len
 5814:                 100 chars allot \ space for path
 5815: @end example
 5816: 
 5817: @c -------------------------------------------------------------
 5818: @node Blocks, Other I/O, Files, Words
 5819: @section Blocks
 5820: @cindex I/O - blocks
 5821: @cindex blocks
 5822: 
 5823: When you run Gforth on a modern desk-top computer, it runs under the
 5824: control of an operating system which provides certain services.  One of
 5825: these services is @var{file services}, which allows Forth source code
 5826: and data to be stored in files and read into Gforth (@pxref{Files}).
 5827: 
 5828: Traditionally, Forth has been an important programming language on
 5829: systems where it has interfaced directly to the underlying hardware with
 5830: no intervening operating system. Forth provides a mechanism, called
 5831: @dfn{blocks}, for accessing mass storage on such systems.
 5832: 
 5833: A block is a 1024-byte data area, which can be used to hold data or
 5834: Forth source code. No structure is imposed on the contents of the
 5835: block. A block is identified by its number; blocks are numbered
 5836: contiguously from 1 to an implementation-defined maximum.
 5837: 
 5838: A typical system that used blocks but no operating system might use a
 5839: single floppy-disk drive for mass storage, with the disks formatted to
 5840: provide 256-byte sectors. Blocks would be implemented by assigning the
 5841: first four sectors of the disk to block 1, the second four sectors to
 5842: block 2 and so on, up to the limit of the capacity of the disk. The disk
 5843: would not contain any file system information, just the set of blocks.
 5844: 
 5845: @cindex blocks file
 5846: On systems that do provide file services, blocks are typically
 5847: implemented by storing a sequence of blocks within a single @dfn{blocks
 5848: file}.  The size of the blocks file will be an exact multiple of 1024
 5849: bytes, corresponding to the number of blocks it contains. This is the
 5850: mechanism that Gforth uses.
 5851: 
 5852: @cindex @file{blocks.fb}
 5853: Only 1 blocks file can be open at a time. If you use block words without
 5854: having specified a blocks file, Gforth defaults to the blocks file
 5855: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
 5856: locate a blocks file (@pxref{Forth Search Paths}).
 5857: 
 5858: @cindex block buffers
 5859: When you read and write blocks under program control, Gforth uses a
 5860: number of @dfn{block buffers} as intermediate storage. These buffers are
 5861: not used when you use @code{load} to interpret the contents of a block.
 5862: 
 5863: The behaviour of the block buffers is directly analagous to that of a
 5864: cache. Each block buffer has three states:
 5865: 
 5866: @itemize @bullet
 5867: @item
 5868: Unassigned
 5869: @item
 5870: Assigned-clean
 5871: @item
 5872: Assigned-dirty
 5873: @end itemize
 5874: 
 5875: Initially, all block buffers are @i{unassigned}. In order to access a
 5876: block, the block (specified by its block number) must be assigned to a
 5877: block buffer.
 5878: 
 5879: The assignment of a block to a block buffer is performed by @code{block}
 5880: or @code{buffer}. Use @code{block} when you wish to modify the existing
 5881: contents of a block. Use @code{buffer} when you don't care about the
 5882: existing contents of the block@footnote{The ANS Forth definition of
 5883: @code{buffer} is intended not to cause disk I/O; if the data associated
 5884: with the particular block is already stored in a block buffer due to an
 5885: earlier @code{block} command, @code{buffer} will return that block
 5886: buffer and the existing contents of the block will be
 5887: available. Otherwise, @code{buffer} will simply assign a new, empty
 5888: block buffer for the block.}.
 5889: 
 5890: Once a block has been assigned to a block buffer, the block buffer state
 5891: becomes @i{assigned-clean}. Data can now be manipulated within the
 5892: block buffer.
 5893: 
 5894: When the contents of a block buffer is changed it is necessary,
 5895: @i{before calling} @code{block} @i{or} @code{buffer} @i{again}, to
 5896: either abandon the changes (by doing nothing) or commit the changes,
 5897: using @code{update}. Using @code{update} does not change the blocks
 5898: file; it simply changes a block buffer's state to @i{assigned-dirty}.
 5899: 
 5900: The word @code{flush} causes all @i{assigned-dirty} blocks to be
 5901: written back to the blocks file on disk. Leaving Gforth using @code{bye}
 5902: also causes a @code{flush} to be performed.
 5903: 
 5904: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
 5905: algorithm to assign a block buffer to a block. That means that any
 5906: particular block can only be assigned to one specific block buffer,
 5907: called (for the particular operation) the @i{victim buffer}. If the
 5908: victim buffer is @i{unassigned} or @i{assigned-clean} it can be
 5909: allocated to the new block immediately. If it is @i{assigned-dirty}
 5910: its current contents must be written out to disk before it can be
 5911: allocated to the new block.
 5912: 
 5913: Although no structure is imposed on the contents of a block, it is
 5914: traditional to display the contents as 16 lines each of 64 characters.  A
 5915: block provides a single, continuous stream of input (for example, it
 5916: acts as a single parse area) -- there are no end-of-line characters
 5917: within a block, and no end-of-file character at the end of a
 5918: block. There are two consequences of this:
 5919: 
 5920: @itemize @bullet
 5921: @item
 5922: The last character of one line wraps straight into the first character
 5923: of the following line
 5924: @item
 5925: The word @code{\} -- comment to end of line -- requires special
 5926: treatment; in the context of a block it causes all characters until the
 5927: end of the current 64-character ``line'' to be ignored.
 5928: @end itemize
 5929: 
 5930: In Gforth, when you use @code{block} with a non-existent block number,
 5931: the current blocks file will be extended to the appropriate size and the
 5932: block buffer will be initialised with spaces.
 5933: 
 5934: Gforth includes a simple block editor (type @code{use blocked.fb} then
 5935: @i{0 list} for details) but doesn't encourage the use of blocks; the
 5936: mechanism is only provided for backward compatibility -- ANS Forth
 5937: requires blocks to be available when files are.
 5938: 
 5939: Common techniques that are used when working with blocks include:
 5940: 
 5941: @itemize @bullet
 5942: @item
 5943: A screen editor that allows you to edit blocks without leaving the Forth
 5944: environment.
 5945: @item
 5946: Shadow screens; where every code block has an associated block
 5947: containing comments (for example: code in odd block numbers, comments in
 5948: even block numbers). Typically, the block editor provides a convenient
 5949: mechanism to toggle between code and comments.
 5950: @item
 5951: Load blocks; a single block (typically block 1) contains a number of
 5952: @code{thru} commands which @code{load} the whole of the application.
 5953: @end itemize
 5954: 
 5955: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
 5956: integrated into a Forth programming environment.
 5957: 
 5958: @comment TODO what about errors on open-blocks?
 5959: 
 5960: doc-open-blocks
 5961: doc-use
 5962: doc-get-block-fid
 5963: doc-block-position
 5964: 
 5965: doc-scr
 5966: doc-list
 5967: 
 5968: doc---gforthman-block
 5969: doc-buffer
 5970: 
 5971: doc-update
 5972: doc-updated?
 5973: doc-save-buffers
 5974: doc-empty-buffers
 5975: doc-empty-buffer
 5976: doc-flush
 5977: 
 5978: doc-load
 5979: doc-thru
 5980: doc-+load
 5981: doc-+thru
 5982: doc---gforthman--->
 5983: doc-block-included
 5984: 
 5985: 
 5986: @c -------------------------------------------------------------
 5987: @node Other I/O, Programming Tools, Blocks, Words
 5988: @section Other I/O
 5989: @cindex I/O - keyboard and display
 5990: 
 5991: @menu
 5992: * Simple numeric output::       Predefined formats
 5993: * Formatted numeric output::    Formatted (pictured) output
 5994: * String Formats::              How Forth stores strings in memory
 5995: * Displaying characters and strings:: Other stuff
 5996: * Input::                       Input
 5997: @end menu
 5998: 
 5999: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
 6000: @subsection Simple numeric output
 6001: @cindex numeric output - simple/free-format
 6002: 
 6003: The simplest output functions are those that display numbers from the
 6004: data or floating-point stacks. Floating-point output is always displayed
 6005: using base 10. Numbers displayed from the data stack use the value stored
 6006: in @code{base}.
 6007: 
 6008: 
 6009: doc-.
 6010: doc-dec.
 6011: doc-hex.
 6012: doc-u.
 6013: doc-.r
 6014: doc-u.r
 6015: doc-d.
 6016: doc-ud.
 6017: doc-d.r
 6018: doc-ud.r
 6019: doc-f.
 6020: doc-fe.
 6021: doc-fs.
 6022: 
 6023: 
 6024: Examples of printing the number 1234.5678E23 in the different floating-point output
 6025: formats are shown below:
 6026: 
 6027: @example
 6028: f. 123456779999999000000000000.
 6029: fe. 123.456779999999E24
 6030: fs. 1.23456779999999E26
 6031: @end example
 6032: 
 6033: 
 6034: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
 6035: @subsection Formatted numeric output
 6036: @cindex formatted numeric output
 6037: @cindex pictured numeric output
 6038: @cindex numeric output - formatted
 6039: 
 6040: Forth traditionally uses a technique called @dfn{pictured numeric
 6041: output} for formatted printing of integers.  In this technique, digits
 6042: are extracted from the number (using the current output radix defined by
 6043: @code{base}), converted to ASCII codes and appended to a string that is
 6044: built in a scratch-pad area of memory (@pxref{core-idef,
 6045: Implementation-defined options, Implementation-defined
 6046: options}). Arbitrary characters can be appended to the string during the
 6047: extraction process. The completed string is specified by an address
 6048: and length and can be manipulated (@code{TYPE}ed, copied, modified)
 6049: under program control.
 6050: 
 6051: All of the words described in the previous section for simple numeric
 6052: output are implemented in Gforth using pictured numeric output.
 6053: 
 6054: Three important things to remember about Pictured Numeric Output:
 6055: 
 6056: @itemize @bullet
 6057: @item
 6058: It always operates on double-precision numbers; to display a
 6059: single-precision number, convert it first (@pxref{Double precision} for
 6060: ways of doing this).
 6061: @item
 6062: It always treats the double-precision number as though it were
 6063: unsigned. The examples below show ways of printing signed numbers.
 6064: @item
 6065: The string is built up from right to left; least significant digit first.
 6066: @end itemize
 6067: 
 6068: 
 6069: doc-<#
 6070: doc-#
 6071: doc-#s
 6072: doc-hold
 6073: doc-sign
 6074: doc-#>
 6075: 
 6076: doc-represent
 6077: 
 6078: 
 6079: @noindent
 6080: Here are some examples of using pictured numeric output:
 6081: 
 6082: @example
 6083: : my-u. ( u -- )
 6084:   \ Simplest use of pns.. behaves like Standard u. 
 6085:   0              \ convert to unsigned double
 6086:   <#             \ start conversion
 6087:   #s             \ convert all digits
 6088:   #>             \ complete conversion
 6089:   TYPE SPACE ;   \ display, with trailing space
 6090: 
 6091: : cents-only ( u -- )
 6092:   0              \ convert to unsigned double
 6093:   <#             \ start conversion
 6094:   # #            \ convert two least-significant digits
 6095:   #>             \ complete conversion, discard other digits
 6096:   TYPE SPACE ;   \ display, with trailing space
 6097: 
 6098: : dollars-and-cents ( u -- )
 6099:   0              \ convert to unsigned double
 6100:   <#             \ start conversion
 6101:   # #            \ convert two least-significant digits
 6102:   [char] . hold  \ insert decimal point
 6103:   #s             \ convert remaining digits
 6104:   [char] $ hold  \ append currency symbol
 6105:   #>             \ complete conversion
 6106:   TYPE SPACE ;   \ display, with trailing space
 6107: 
 6108: : my-. ( n -- )
 6109:   \ handling negatives.. behaves like Standard .
 6110:   s>d            \ convert to signed double
 6111:   swap over dabs \ leave sign byte followed by unsigned double
 6112:   <#             \ start conversion
 6113:   #s             \ convert all digits
 6114:   rot sign       \ get at sign byte, append "-" if needed
 6115:   #>             \ complete conversion
 6116:   TYPE SPACE ;   \ display, with trailing space
 6117: 
 6118: : account. ( n -- )
 6119:   \ accountants don't like minus signs, they use braces
 6120:   \ for negative numbers
 6121:   s>d            \ convert to signed double
 6122:   swap over dabs \ leave sign byte followed by unsigned double
 6123:   <#             \ start conversion
 6124:   2 pick         \ get copy of sign byte
 6125:   0< IF [char] ) hold THEN \ right-most character of output
 6126:   #s             \ convert all digits
 6127:   rot            \ get at sign byte
 6128:   0< IF [char] ( hold THEN
 6129:   #>             \ complete conversion
 6130:   TYPE SPACE ;   \ display, with trailing space
 6131: @end example
 6132: 
 6133: Here are some examples of using these words:
 6134: 
 6135: @example
 6136: 1 my-u. 1
 6137: hex -1 my-u. decimal FFFFFFFF
 6138: 1 cents-only 01
 6139: 1234 cents-only 34
 6140: 2 dollars-and-cents $0.02
 6141: 1234 dollars-and-cents $12.34
 6142: 123 my-. 123
 6143: -123 my. -123
 6144: 123 account. 123
 6145: -456 account. (456)
 6146: @end example
 6147: 
 6148: 
 6149: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
 6150: @subsection String Formats
 6151: @cindex strings - see character strings
 6152: @cindex character strings - formats
 6153: @cindex I/O - see character strings
 6154: 
 6155: Forth commonly uses two different methods for representing character
 6156: strings:
 6157: 
 6158: @itemize @bullet
 6159: @item
 6160: @cindex address of counted string
 6161: @cindex counted string
 6162: As a @dfn{counted string}, represented by a @i{c-addr}. The char
 6163: addressed by @i{c-addr} contains a character-count, @i{n}, of the
 6164: string and the string occupies the subsequent @i{n} char addresses in
 6165: memory.
 6166: @item
 6167: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
 6168: of the string in characters, and @i{c-addr} is the address of the
 6169: first byte of the string.
 6170: @end itemize
 6171: 
 6172: ANS Forth encourages the use of the second format when representing
 6173: strings on the stack, whilst conceeding that the counted string format
 6174: remains useful as a way of storing strings in memory.
 6175: 
 6176: 
 6177: doc-count
 6178: 
 6179: 
 6180: @xref{Memory Blocks} for words that move, copy and search
 6181: for strings. @xref{Displaying characters and strings,} for words that
 6182: display characters and strings.
 6183: 
 6184: 
 6185: @node Displaying characters and strings, Input, String Formats, Other I/O
 6186: @subsection Displaying characters and strings
 6187: @cindex characters - compiling and displaying
 6188: @cindex character strings - compiling and displaying
 6189: 
 6190: This section starts with a glossary of Forth words and ends with a set
 6191: of examples.
 6192: 
 6193: 
 6194: doc-bl
 6195: doc-space
 6196: doc-spaces
 6197: doc-emit
 6198: doc-toupper
 6199: doc-."
 6200: doc-.(
 6201: doc-type
 6202: doc-typewhite
 6203: doc-cr
 6204: @cindex cursor control
 6205: doc-at-xy
 6206: doc-page
 6207: doc-s"
 6208: doc-c"
 6209: doc-char
 6210: doc-[char]
 6211: doc-sliteral
 6212: 
 6213: 
 6214: @noindent
 6215: As an example, consider the following text, stored in a file @file{test.fs}:
 6216: 
 6217: @example
 6218: .( text-1)
 6219: : my-word
 6220:   ." text-2" cr
 6221:   .( text-3)
 6222: ;
 6223: 
 6224: ." text-4"
 6225: 
 6226: : my-char
 6227:   [char] ALPHABET emit
 6228:   char emit
 6229: ;
 6230: @end example
 6231: 
 6232: When you load this code into Gforth, the following output is generated:
 6233: 
 6234: @example
 6235: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
 6236: @end example
 6237: 
 6238: @itemize @bullet
 6239: @item
 6240: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
 6241: is an immediate word; it behaves in the same way whether it is used inside
 6242: or outside a colon definition.
 6243: @item
 6244: Message @code{text-4} is displayed because of Gforth's added interpretation
 6245: semantics for @code{."}.
 6246: @item
 6247: Message @code{text-2} is @i{not} displayed, because the text interpreter
 6248: performs the compilation semantics for @code{."} within the definition of
 6249: @code{my-word}.
 6250: @end itemize
 6251: 
 6252: Here are some examples of executing @code{my-word} and @code{my-char}:
 6253: 
 6254: @example
 6255: @kbd{my-word @key{RET}} text-2
 6256:  ok
 6257: @kbd{my-char fred @key{RET}} Af ok
 6258: @kbd{my-char jim @key{RET}} Aj ok
 6259: @end example
 6260: 
 6261: @itemize @bullet
 6262: @item
 6263: Message @code{text-2} is displayed because of the run-time behaviour of
 6264: @code{."}.
 6265: @item
 6266: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
 6267: on the stack at run-time. @code{emit} always displays the character
 6268: when @code{my-char} is executed.
 6269: @item
 6270: @code{char} parses a string at run-time and the second @code{emit} displays
 6271: the first character of the string.
 6272: @item
 6273: If you type @code{see my-char} you can see that @code{[char]} discarded
 6274: the text ``LPHABET'' and only compiled the display code for ``A'' into the
 6275: definition of @code{my-char}.
 6276: @end itemize
 6277: 
 6278: 
 6279: 
 6280: @node Input, , Displaying characters and strings, Other I/O
 6281: @subsection Input
 6282: @cindex input
 6283: @cindex I/O - see input
 6284: @cindex parsing a string
 6285: 
 6286: @xref{String Formats} for ways of storing character strings in memory.
 6287: 
 6288: @comment TODO examples for >number >float accept key key? pad parse word refill
 6289: @comment then index them
 6290: 
 6291: 
 6292: doc-key
 6293: doc-key?
 6294: doc-ekey
 6295: doc-ekey?
 6296: doc-ekey>char
 6297: doc->number
 6298: doc->float
 6299: doc-accept
 6300: doc-pad
 6301: doc-parse
 6302: doc-word
 6303: doc-sword
 6304: doc-(name)
 6305: doc-refill
 6306: @comment obsolescent words..
 6307: doc-convert
 6308: doc-query
 6309: doc-expect
 6310: doc-span
 6311: 
 6312: 
 6313: 
 6314: @c -------------------------------------------------------------
 6315: @node Programming Tools, Assembler and Code Words, Other I/O, Words
 6316: @section Programming Tools
 6317: @cindex programming tools
 6318: 
 6319: @menu
 6320: * Debugging::                   Simple and quick.
 6321: * Assertions::                  Making your programs self-checking.
 6322: * Singlestep Debugger::		Executing your program word by word.
 6323: @end menu
 6324: 
 6325: @node Debugging, Assertions, Programming Tools, Programming Tools
 6326: @subsection Debugging
 6327: @cindex debugging
 6328: 
 6329: Languages with a slow edit/compile/link/test development loop tend to
 6330: require sophisticated tracing/stepping debuggers to facilate
 6331: productive debugging.
 6332: 
 6333: A much better (faster) way in fast-compiling languages is to add
 6334: printing code at well-selected places, let the program run, look at
 6335: the output, see where things went wrong, add more printing code, etc.,
 6336: until the bug is found.
 6337: 
 6338: The simple debugging aids provided in @file{debugs.fs}
 6339: are meant to support this style of debugging. In addition, there are
 6340: words for non-destructively inspecting the stack and memory:
 6341: 
 6342: 
 6343: doc-.s
 6344: doc-f.s
 6345: 
 6346: 
 6347: There is a word @code{.r} but it does @i{not} display the return
 6348: stack! It is used for formatted numeric output.
 6349: 
 6350: 
 6351: doc-depth
 6352: doc-fdepth
 6353: doc-clearstack
 6354: doc-?
 6355: doc-dump
 6356: 
 6357: 
 6358: The word @code{~~} prints debugging information (by default the source
 6359: location and the stack contents). It is easy to insert. If you use Emacs
 6360: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
 6361: query-replace them with nothing). The deferred words
 6362: @code{printdebugdata} and @code{printdebugline} control the output of
 6363: @code{~~}. The default source location output format works well with
 6364: Emacs' compilation mode, so you can step through the program at the
 6365: source level using @kbd{C-x `} (the advantage over a stepping debugger
 6366: is that you can step in any direction and you know where the crash has
 6367: happened or where the strange data has occurred).
 6368: 
 6369: The default actions of @code{~~} clobber the contents of the pictured
 6370: numeric output string, so you should not use @code{~~}, e.g., between
 6371: @code{<#} and @code{#>}.
 6372: 
 6373: 
 6374: doc-~~
 6375: doc-printdebugdata
 6376: doc-printdebugline
 6377: 
 6378: doc-see
 6379: doc-marker
 6380: 
 6381: 
 6382: Here's an example of using @code{marker} at the start of a source file
 6383: that you are debugging; it ensures that you only ever have one copy of
 6384: the file's definitions compiled at any time:
 6385: 
 6386: @example
 6387: [IFDEF] my-code
 6388:     my-code
 6389: [ENDIF]
 6390: 
 6391: marker my-code
 6392: init-included-files
 6393: 
 6394: \ .. definitions start here
 6395: \ .
 6396: \ .
 6397: \ end
 6398: @end example
 6399: 
 6400: 
 6401: 
 6402: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
 6403: @subsection Assertions
 6404: @cindex assertions
 6405: 
 6406: It is a good idea to make your programs self-checking, especially if you
 6407: make an assumption that may become invalid during maintenance (for
 6408: example, that a certain field of a data structure is never zero). Gforth
 6409: supports @dfn{assertions} for this purpose. They are used like this:
 6410: 
 6411: @example
 6412: assert( @i{flag} )
 6413: @end example
 6414: 
 6415: The code between @code{assert(} and @code{)} should compute a flag, that
 6416: should be true if everything is alright and false otherwise. It should
 6417: not change anything else on the stack. The overall stack effect of the
 6418: assertion is @code{( -- )}. E.g.
 6419: 
 6420: @example
 6421: assert( 1 1 + 2 = ) \ what we learn in school
 6422: assert( dup 0<> ) \ assert that the top of stack is not zero
 6423: assert( false ) \ this code should not be reached
 6424: @end example
 6425: 
 6426: The need for assertions is different at different times. During
 6427: debugging, we want more checking, in production we sometimes care more
 6428: for speed. Therefore, assertions can be turned off, i.e., the assertion
 6429: becomes a comment. Depending on the importance of an assertion and the
 6430: time it takes to check it, you may want to turn off some assertions and
 6431: keep others turned on. Gforth provides several levels of assertions for
 6432: this purpose:
 6433: 
 6434: 
 6435: doc-assert0(
 6436: doc-assert1(
 6437: doc-assert2(
 6438: doc-assert3(
 6439: doc-assert(
 6440: doc-)
 6441: 
 6442: 
 6443: The variable @code{assert-level} specifies the highest assertions that
 6444: are turned on. I.e., at the default @code{assert-level} of one,
 6445: @code{assert0(} and @code{assert1(} assertions perform checking, while
 6446: @code{assert2(} and @code{assert3(} assertions are treated as comments.
 6447: 
 6448: The value of @code{assert-level} is evaluated at compile-time, not at
 6449: run-time. Therefore you cannot turn assertions on or off at run-time;
 6450: you have to set the @code{assert-level} appropriately before compiling a
 6451: piece of code. You can compile different pieces of code at different
 6452: @code{assert-level}s (e.g., a trusted library at level 1 and
 6453: newly-written code at level 3).
 6454: 
 6455: 
 6456: doc-assert-level
 6457: 
 6458: 
 6459: If an assertion fails, a message compatible with Emacs' compilation mode
 6460: is produced and the execution is aborted (currently with @code{ABORT"}.
 6461: If there is interest, we will introduce a special throw code. But if you
 6462: intend to @code{catch} a specific condition, using @code{throw} is
 6463: probably more appropriate than an assertion).
 6464: 
 6465: Definitions in ANS Forth for these assertion words are provided
 6466: in @file{compat/assert.fs}.
 6467: 
 6468: 
 6469: @node Singlestep Debugger, , Assertions, Programming Tools
 6470: @subsection Singlestep Debugger
 6471: @cindex singlestep Debugger
 6472: @cindex debugging Singlestep
 6473: 
 6474: When you create a new word there's often the need to check whether it
 6475: behaves correctly or not. You can do this by typing @code{dbg
 6476: badword}. A debug session might look like this:
 6477: 
 6478: @example
 6479: : badword 0 DO i . LOOP ;  ok
 6480: 2 dbg badword 
 6481: : badword  
 6482: Scanning code...
 6483: 
 6484: Nesting debugger ready!
 6485: 
 6486: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
 6487: 400D4740  8049F68 DO             -> [ 0 ] 
 6488: 400D4744  804A0C8 i              -> [ 1 ] 00000 
 6489: 400D4748 400C5E60 .              -> 0 [ 0 ] 
 6490: 400D474C  8049D0C LOOP           -> [ 0 ] 
 6491: 400D4744  804A0C8 i              -> [ 1 ] 00001 
 6492: 400D4748 400C5E60 .              -> 1 [ 0 ] 
 6493: 400D474C  8049D0C LOOP           -> [ 0 ] 
 6494: 400D4758  804B384 ;              ->  ok
 6495: @end example
 6496: 
 6497: Each line displayed is one step. You always have to hit return to
 6498: execute the next word that is displayed. If you don't want to execute
 6499: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
 6500: an overview what keys are available:
 6501: 
 6502: @table @i
 6503: 
 6504: @item @key{RET}
 6505: Next; Execute the next word.
 6506: 
 6507: @item n
 6508: Nest; Single step through next word.
 6509: 
 6510: @item u
 6511: Unnest; Stop debugging and execute rest of word. If we got to this word
 6512: with nest, continue debugging with the calling word.
 6513: 
 6514: @item d
 6515: Done; Stop debugging and execute rest.
 6516: 
 6517: @item s
 6518: Stop; Abort immediately.
 6519: 
 6520: @end table
 6521: 
 6522: Debugging large application with this mechanism is very difficult, because
 6523: you have to nest very deeply into the program before the interesting part
 6524: begins. This takes a lot of time. 
 6525: 
 6526: To do it more directly put a @code{BREAK:} command into your source code.
 6527: When program execution reaches @code{BREAK:} the single step debugger is
 6528: invoked and you have all the features described above.
 6529: 
 6530: If you have more than one part to debug it is useful to know where the
 6531: program has stopped at the moment. You can do this by the 
 6532: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
 6533: string is typed out when the ``breakpoint'' is reached.
 6534: 
 6535: 
 6536: doc-dbg
 6537: doc-break:
 6538: doc-break"
 6539: 
 6540: 
 6541: 
 6542: @c -------------------------------------------------------------
 6543: @node Assembler and Code Words, Threading Words, Programming Tools, Words
 6544: @section Assembler and Code Words
 6545: @cindex assembler
 6546: @cindex code words
 6547: 
 6548: Gforth provides some words for defining primitives (words written in
 6549: machine code), and for defining the machine-code equivalent of
 6550: @code{DOES>}-based defining words. However, the machine-independent
 6551: nature of Gforth poses a few problems: First of all, Gforth runs on
 6552: several architectures, so it can provide no standard assembler. What's
 6553: worse is that the register allocation not only depends on the processor,
 6554: but also on the @code{gcc} version and options used.
 6555: 
 6556: The words that Gforth offers encapsulate some system dependences (e.g.,
 6557: the header structure), so a system-independent assembler may be used in
 6558: Gforth. If you do not have an assembler, you can compile machine code
 6559: directly with @code{,} and @code{c,}@footnote{This isn't portable,
 6560: because these words emit stuff in @i{data} space; it works because
 6561: Gforth has unified code/data spaces. Assembler isn't likely to be
 6562: portable anyway.}.
 6563: 
 6564: 
 6565: doc-assembler
 6566: doc-init-asm
 6567: doc-code
 6568: doc-end-code
 6569: doc-;code
 6570: doc-flush-icache
 6571: 
 6572: 
 6573: If @code{flush-icache} does not work correctly, @code{code} words
 6574: etc. will not work (reliably), either.
 6575: 
 6576: The typical usage of these @code{code} words can be shown most easily by
 6577: analogy to the equivalent high-level defining words:
 6578: 
 6579: @example
 6580: : foo                                        code foo
 6581:    <high-level Forth words>                        <assembler>
 6582: ;                                            end-code
 6583: 
 6584: : bar                                        : bar
 6585:    <high-level Forth words>                     <high-level Forth words>
 6586:    CREATE                                       CREATE
 6587:       <high-level Forth words>                     <high-level Forth words>
 6588:    DOES>                                        ;code
 6589:       <high-level Forth words>                     <assembler>
 6590: ;                                            end-code
 6591: @end example
 6592: 
 6593: @code{flush-icache} is always present. The other words are rarely used
 6594: and reside in @code{code.fs}, which is usually not loaded. You can load
 6595: it with @code{require code.fs}.
 6596: 
 6597: @cindex registers of the inner interpreter
 6598: In the assembly code you will want to refer to the inner interpreter's
 6599: registers (e.g., the data stack pointer) and you may want to use other
 6600: registers for temporary storage. Unfortunately, the register allocation
 6601: is installation-dependent.
 6602: 
 6603: The easiest solution is to use explicit register declarations
 6604: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
 6605: GNU C Manual}) for all of the inner interpreter's registers: You have to
 6606: compile Gforth with @code{-DFORCE_REG} (configure option
 6607: @code{--enable-force-reg}) and the appropriate declarations must be
 6608: present in the @code{machine.h} file (see @code{mips.h} for an example;
 6609: you can find a full list of all declarable register symbols with
 6610: @code{grep register engine.c}). If you give explicit registers to all
 6611: variables that are declared at the beginning of @code{engine()}, you
 6612: should be able to use the other caller-saved registers for temporary
 6613: storage. Alternatively, you can use the @code{gcc} option
 6614: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
 6615: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
 6616: (however, this restriction on register allocation may slow Gforth
 6617: significantly).
 6618: 
 6619: If this solution is not viable (e.g., because @code{gcc} does not allow
 6620: you to explicitly declare all the registers you need), you have to find
 6621: out by looking at the code where the inner interpreter's registers
 6622: reside and which registers can be used for temporary storage. You can
 6623: get an assembly listing of the engine's code with @code{make engine.s}.
 6624: 
 6625: In any case, it is good practice to abstract your assembly code from the
 6626: actual register allocation. E.g., if the data stack pointer resides in
 6627: register @code{$17}, create an alias for this register called @code{sp},
 6628: and use that in your assembly code.
 6629: 
 6630: @cindex code words, portable
 6631: Another option for implementing normal and defining words efficiently
 6632: is to add the desired functionality to the source of Gforth. For normal
 6633: words you just have to edit @file{primitives} (@pxref{Automatic
 6634: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
 6635: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
 6636: @file{prims2x.fs}, and possibly @file{cross.fs}.
 6637: 
 6638: 
 6639: @c -------------------------------------------------------------
 6640: @node Threading Words, Locals, Assembler and Code Words, Words
 6641: @section Threading Words
 6642: @cindex threading words
 6643: 
 6644: @cindex code address
 6645: These words provide access to code addresses and other threading stuff
 6646: in Gforth (and, possibly, other interpretive Forths). It more or less
 6647: abstracts away the differences between direct and indirect threading
 6648: (and, for direct threading, the machine dependences). However, at
 6649: present this wordset is still incomplete. It is also pretty low-level;
 6650: some day it will hopefully be made unnecessary by an internals wordset
 6651: that abstracts implementation details away completely.
 6652: 
 6653: 
 6654: doc-threading-method
 6655: doc->code-address
 6656: doc->does-code
 6657: doc-code-address!
 6658: doc-does-code!
 6659: doc-does-handler!
 6660: doc-/does-handler
 6661: 
 6662: 
 6663: The code addresses produced by various defining words are produced by
 6664: the following words:
 6665: 
 6666: 
 6667: doc-docol:
 6668: doc-docon:
 6669: doc-dovar:
 6670: doc-douser:
 6671: doc-dodefer:
 6672: doc-dofield:
 6673: 
 6674: 
 6675: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
 6676: with @code{>does-code}. If the word was defined in that way, the value
 6677: returned is non-zero and identifies the @code{DOES>} used by the
 6678: defining word.
 6679: @comment TODO should that be ``identifies the xt of the DOES> ??''
 6680: 
 6681: @c -------------------------------------------------------------
 6682: @node Locals, Structures, Threading Words, Words
 6683: @section Locals
 6684: @cindex locals
 6685: 
 6686: Local variables can make Forth programming more enjoyable and Forth
 6687: programs easier to read. Unfortunately, the locals of ANS Forth are
 6688: laden with restrictions. Therefore, we provide not only the ANS Forth
 6689: locals wordset, but also our own, more powerful locals wordset (we
 6690: implemented the ANS Forth locals wordset through our locals wordset).
 6691: 
 6692: The ideas in this section have also been published in the paper
 6693: @cite{Automatic Scoping of Local Variables} by M. Anton Ertl, presented
 6694: at EuroForth '94; it is available at
 6695: @*@url{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz}.
 6696: 
 6697: @menu
 6698: * Gforth locals::               
 6699: * ANS Forth locals::            
 6700: @end menu
 6701: 
 6702: @node Gforth locals, ANS Forth locals, Locals, Locals
 6703: @subsection Gforth locals
 6704: @cindex Gforth locals
 6705: @cindex locals, Gforth style
 6706: 
 6707: Locals can be defined with
 6708: 
 6709: @example
 6710: @{ local1 local2 ... -- comment @}
 6711: @end example
 6712: or
 6713: @example
 6714: @{ local1 local2 ... @}
 6715: @end example
 6716: 
 6717: E.g.,
 6718: @example
 6719: : max @{ n1 n2 -- n3 @}
 6720:  n1 n2 > if
 6721:    n1
 6722:  else
 6723:    n2
 6724:  endif ;
 6725: @end example
 6726: 
 6727: The similarity of locals definitions with stack comments is intended. A
 6728: locals definition often replaces the stack comment of a word. The order
 6729: of the locals corresponds to the order in a stack comment and everything
 6730: after the @code{--} is really a comment.
 6731: 
 6732: This similarity has one disadvantage: It is too easy to confuse locals
 6733: declarations with stack comments, causing bugs and making them hard to
 6734: find. However, this problem can be avoided by appropriate coding
 6735: conventions: Do not use both notations in the same program. If you do,
 6736: they should be distinguished using additional means, e.g. by position.
 6737: 
 6738: @cindex types of locals
 6739: @cindex locals types
 6740: The name of the local may be preceded by a type specifier, e.g.,
 6741: @code{F:} for a floating point value:
 6742: 
 6743: @example
 6744: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
 6745: \ complex multiplication
 6746:  Ar Br f* Ai Bi f* f-
 6747:  Ar Bi f* Ai Br f* f+ ;
 6748: @end example
 6749: 
 6750: @cindex flavours of locals
 6751: @cindex locals flavours
 6752: @cindex value-flavoured locals
 6753: @cindex variable-flavoured locals
 6754: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
 6755: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
 6756: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
 6757: with @code{W:}, @code{D:} etc.) produces its value and can be changed
 6758: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
 6759: produces its address (which becomes invalid when the variable's scope is
 6760: left). E.g., the standard word @code{emit} can be defined in terms of
 6761: @code{type} like this:
 6762: 
 6763: @example
 6764: : emit @{ C^ char* -- @}
 6765:     char* 1 type ;
 6766: @end example
 6767: 
 6768: @cindex default type of locals
 6769: @cindex locals, default type
 6770: A local without type specifier is a @code{W:} local. Both flavours of
 6771: locals are initialized with values from the data or FP stack.
 6772: 
 6773: Currently there is no way to define locals with user-defined data
 6774: structures, but we are working on it.
 6775: 
 6776: Gforth allows defining locals everywhere in a colon definition. This
 6777: poses the following questions:
 6778: 
 6779: @menu
 6780: * Where are locals visible by name?::  
 6781: * How long do locals live?::    
 6782: * Programming Style::           
 6783: * Implementation::              
 6784: @end menu
 6785: 
 6786: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
 6787: @subsubsection Where are locals visible by name?
 6788: @cindex locals visibility
 6789: @cindex visibility of locals
 6790: @cindex scope of locals
 6791: 
 6792: Basically, the answer is that locals are visible where you would expect
 6793: it in block-structured languages, and sometimes a little longer. If you
 6794: want to restrict the scope of a local, enclose its definition in
 6795: @code{SCOPE}...@code{ENDSCOPE}.
 6796: 
 6797: 
 6798: doc-scope
 6799: doc-endscope
 6800: 
 6801: 
 6802: These words behave like control structure words, so you can use them
 6803: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
 6804: arbitrary ways.
 6805: 
 6806: If you want a more exact answer to the visibility question, here's the
 6807: basic principle: A local is visible in all places that can only be
 6808: reached through the definition of the local@footnote{In compiler
 6809: construction terminology, all places dominated by the definition of the
 6810: local.}. In other words, it is not visible in places that can be reached
 6811: without going through the definition of the local. E.g., locals defined
 6812: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
 6813: defined in @code{BEGIN}...@code{UNTIL} are visible after the
 6814: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
 6815: 
 6816: The reasoning behind this solution is: We want to have the locals
 6817: visible as long as it is meaningful. The user can always make the
 6818: visibility shorter by using explicit scoping. In a place that can
 6819: only be reached through the definition of a local, the meaning of a
 6820: local name is clear. In other places it is not: How is the local
 6821: initialized at the control flow path that does not contain the
 6822: definition? Which local is meant, if the same name is defined twice in
 6823: two independent control flow paths?
 6824: 
 6825: This should be enough detail for nearly all users, so you can skip the
 6826: rest of this section. If you really must know all the gory details and
 6827: options, read on.
 6828: 
 6829: In order to implement this rule, the compiler has to know which places
 6830: are unreachable. It knows this automatically after @code{AHEAD},
 6831: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
 6832: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
 6833: compiler that the control flow never reaches that place. If
 6834: @code{UNREACHABLE} is not used where it could, the only consequence is
 6835: that the visibility of some locals is more limited than the rule above
 6836: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
 6837: lie to the compiler), buggy code will be produced.
 6838: 
 6839: 
 6840: doc-unreachable
 6841: 
 6842: 
 6843: Another problem with this rule is that at @code{BEGIN}, the compiler
 6844: does not know which locals will be visible on the incoming
 6845: back-edge. All problems discussed in the following are due to this
 6846: ignorance of the compiler (we discuss the problems using @code{BEGIN}
 6847: loops as examples; the discussion also applies to @code{?DO} and other
 6848: loops). Perhaps the most insidious example is:
 6849: @example
 6850: AHEAD
 6851: BEGIN
 6852:   x
 6853: [ 1 CS-ROLL ] THEN
 6854:   @{ x @}
 6855:   ...
 6856: UNTIL
 6857: @end example
 6858: 
 6859: This should be legal according to the visibility rule. The use of
 6860: @code{x} can only be reached through the definition; but that appears
 6861: textually below the use.
 6862: 
 6863: From this example it is clear that the visibility rules cannot be fully
 6864: implemented without major headaches. Our implementation treats common
 6865: cases as advertised and the exceptions are treated in a safe way: The
 6866: compiler makes a reasonable guess about the locals visible after a
 6867: @code{BEGIN}; if it is too pessimistic, the
 6868: user will get a spurious error about the local not being defined; if the
 6869: compiler is too optimistic, it will notice this later and issue a
 6870: warning. In the case above the compiler would complain about @code{x}
 6871: being undefined at its use. You can see from the obscure examples in
 6872: this section that it takes quite unusual control structures to get the
 6873: compiler into trouble, and even then it will often do fine.
 6874: 
 6875: If the @code{BEGIN} is reachable from above, the most optimistic guess
 6876: is that all locals visible before the @code{BEGIN} will also be
 6877: visible after the @code{BEGIN}. This guess is valid for all loops that
 6878: are entered only through the @code{BEGIN}, in particular, for normal
 6879: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
 6880: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
 6881: compiler. When the branch to the @code{BEGIN} is finally generated by
 6882: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
 6883: warns the user if it was too optimistic:
 6884: @example
 6885: IF
 6886:   @{ x @}
 6887: BEGIN
 6888:   \ x ? 
 6889: [ 1 cs-roll ] THEN
 6890:   ...
 6891: UNTIL
 6892: @end example
 6893: 
 6894: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
 6895: optimistically assumes that it lives until the @code{THEN}. It notices
 6896: this difference when it compiles the @code{UNTIL} and issues a
 6897: warning. The user can avoid the warning, and make sure that @code{x}
 6898: is not used in the wrong area by using explicit scoping:
 6899: @example
 6900: IF
 6901:   SCOPE
 6902:   @{ x @}
 6903:   ENDSCOPE
 6904: BEGIN
 6905: [ 1 cs-roll ] THEN
 6906:   ...
 6907: UNTIL
 6908: @end example
 6909: 
 6910: Since the guess is optimistic, there will be no spurious error messages
 6911: about undefined locals.
 6912: 
 6913: If the @code{BEGIN} is not reachable from above (e.g., after
 6914: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
 6915: optimistic guess, as the locals visible after the @code{BEGIN} may be
 6916: defined later. Therefore, the compiler assumes that no locals are
 6917: visible after the @code{BEGIN}. However, the user can use
 6918: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
 6919: visible at the BEGIN as at the point where the top control-flow stack
 6920: item was created.
 6921: 
 6922: 
 6923: doc-assume-live
 6924: 
 6925: 
 6926: @noindent
 6927: E.g.,
 6928: @example
 6929: @{ x @}
 6930: AHEAD
 6931: ASSUME-LIVE
 6932: BEGIN
 6933:   x
 6934: [ 1 CS-ROLL ] THEN
 6935:   ...
 6936: UNTIL
 6937: @end example
 6938: 
 6939: Other cases where the locals are defined before the @code{BEGIN} can be
 6940: handled by inserting an appropriate @code{CS-ROLL} before the
 6941: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
 6942: behind the @code{ASSUME-LIVE}).
 6943: 
 6944: Cases where locals are defined after the @code{BEGIN} (but should be
 6945: visible immediately after the @code{BEGIN}) can only be handled by
 6946: rearranging the loop. E.g., the ``most insidious'' example above can be
 6947: arranged into:
 6948: @example
 6949: BEGIN
 6950:   @{ x @}
 6951:   ... 0=
 6952: WHILE
 6953:   x
 6954: REPEAT
 6955: @end example
 6956: 
 6957: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
 6958: @subsubsection How long do locals live?
 6959: @cindex locals lifetime
 6960: @cindex lifetime of locals
 6961: 
 6962: The right answer for the lifetime question would be: A local lives at
 6963: least as long as it can be accessed. For a value-flavoured local this
 6964: means: until the end of its visibility. However, a variable-flavoured
 6965: local could be accessed through its address far beyond its visibility
 6966: scope. Ultimately, this would mean that such locals would have to be
 6967: garbage collected. Since this entails un-Forth-like implementation
 6968: complexities, I adopted the same cowardly solution as some other
 6969: languages (e.g., C): The local lives only as long as it is visible;
 6970: afterwards its address is invalid (and programs that access it
 6971: afterwards are erroneous).
 6972: 
 6973: @node Programming Style, Implementation, How long do locals live?, Gforth locals
 6974: @subsubsection Programming Style
 6975: @cindex locals programming style
 6976: @cindex programming style, locals
 6977: 
 6978: The freedom to define locals anywhere has the potential to change
 6979: programming styles dramatically. In particular, the need to use the
 6980: return stack for intermediate storage vanishes. Moreover, all stack
 6981: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
 6982: determined arguments) can be eliminated: If the stack items are in the
 6983: wrong order, just write a locals definition for all of them; then
 6984: write the items in the order you want.
 6985: 
 6986: This seems a little far-fetched and eliminating stack manipulations is
 6987: unlikely to become a conscious programming objective. Still, the number
 6988: of stack manipulations will be reduced dramatically if local variables
 6989: are used liberally (e.g., compare @code{max} in @ref{Gforth locals} with
 6990: a traditional implementation of @code{max}).
 6991: 
 6992: This shows one potential benefit of locals: making Forth programs more
 6993: readable. Of course, this benefit will only be realized if the
 6994: programmers continue to honour the principle of factoring instead of
 6995: using the added latitude to make the words longer.
 6996: 
 6997: @cindex single-assignment style for locals
 6998: Using @code{TO} can and should be avoided.  Without @code{TO},
 6999: every value-flavoured local has only a single assignment and many
 7000: advantages of functional languages apply to Forth. I.e., programs are
 7001: easier to analyse, to optimize and to read: It is clear from the
 7002: definition what the local stands for, it does not turn into something
 7003: different later.
 7004: 
 7005: E.g., a definition using @code{TO} might look like this:
 7006: @example
 7007: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 7008:  u1 u2 min 0
 7009:  ?do
 7010:    addr1 c@@ addr2 c@@ -
 7011:    ?dup-if
 7012:      unloop exit
 7013:    then
 7014:    addr1 char+ TO addr1
 7015:    addr2 char+ TO addr2
 7016:  loop
 7017:  u1 u2 - ;
 7018: @end example
 7019: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
 7020: every loop iteration. @code{strcmp} is a typical example of the
 7021: readability problems of using @code{TO}. When you start reading
 7022: @code{strcmp}, you think that @code{addr1} refers to the start of the
 7023: string. Only near the end of the loop you realize that it is something
 7024: else.
 7025: 
 7026: This can be avoided by defining two locals at the start of the loop that
 7027: are initialized with the right value for the current iteration.
 7028: @example
 7029: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 7030:  addr1 addr2
 7031:  u1 u2 min 0 
 7032:  ?do @{ s1 s2 @}
 7033:    s1 c@@ s2 c@@ -
 7034:    ?dup-if
 7035:      unloop exit
 7036:    then
 7037:    s1 char+ s2 char+
 7038:  loop
 7039:  2drop
 7040:  u1 u2 - ;
 7041: @end example
 7042: Here it is clear from the start that @code{s1} has a different value
 7043: in every loop iteration.
 7044: 
 7045: @node Implementation,  , Programming Style, Gforth locals
 7046: @subsubsection Implementation
 7047: @cindex locals implementation
 7048: @cindex implementation of locals
 7049: 
 7050: @cindex locals stack
 7051: Gforth uses an extra locals stack. The most compelling reason for
 7052: this is that the return stack is not float-aligned; using an extra stack
 7053: also eliminates the problems and restrictions of using the return stack
 7054: as locals stack. Like the other stacks, the locals stack grows toward
 7055: lower addresses. A few primitives allow an efficient implementation:
 7056: 
 7057: 
 7058: doc-@local#
 7059: doc-f@local#
 7060: doc-laddr#
 7061: doc-lp+!#
 7062: doc-lp!
 7063: doc->l
 7064: doc-f>l
 7065: 
 7066: 
 7067: In addition to these primitives, some specializations of these
 7068: primitives for commonly occurring inline arguments are provided for
 7069: efficiency reasons, e.g., @code{@@local0} as specialization of
 7070: @code{@@local#} for the inline argument 0. The following compiling words
 7071: compile the right specialized version, or the general version, as
 7072: appropriate:
 7073: 
 7074: 
 7075: doc-compile-@local
 7076: doc-compile-f@local
 7077: doc-compile-lp+!
 7078: 
 7079: 
 7080: Combinations of conditional branches and @code{lp+!#} like
 7081: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
 7082: is taken) are provided for efficiency and correctness in loops.
 7083: 
 7084: A special area in the dictionary space is reserved for keeping the
 7085: local variable names. @code{@{} switches the dictionary pointer to this
 7086: area and @code{@}} switches it back and generates the locals
 7087: initializing code. @code{W:} etc.@ are normal defining words. This
 7088: special area is cleared at the start of every colon definition.
 7089: 
 7090: @cindex word list for defining locals
 7091: A special feature of Gforth's dictionary is used to implement the
 7092: definition of locals without type specifiers: every word list (aka
 7093: vocabulary) has its own methods for searching
 7094: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
 7095: with a special search method: When it is searched for a word, it
 7096: actually creates that word using @code{W:}. @code{@{} changes the search
 7097: order to first search the word list containing @code{@}}, @code{W:} etc.,
 7098: and then the word list for defining locals without type specifiers.
 7099: 
 7100: The lifetime rules support a stack discipline within a colon
 7101: definition: The lifetime of a local is either nested with other locals
 7102: lifetimes or it does not overlap them.
 7103: 
 7104: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
 7105: pointer manipulation is generated. Between control structure words
 7106: locals definitions can push locals onto the locals stack. @code{AGAIN}
 7107: is the simplest of the other three control flow words. It has to
 7108: restore the locals stack depth of the corresponding @code{BEGIN}
 7109: before branching. The code looks like this:
 7110: @format
 7111: @code{lp+!#} current-locals-size @minus{} dest-locals-size
 7112: @code{branch} <begin>
 7113: @end format
 7114: 
 7115: @code{UNTIL} is a little more complicated: If it branches back, it
 7116: must adjust the stack just like @code{AGAIN}. But if it falls through,
 7117: the locals stack must not be changed. The compiler generates the
 7118: following code:
 7119: @format
 7120: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
 7121: @end format
 7122: The locals stack pointer is only adjusted if the branch is taken.
 7123: 
 7124: @code{THEN} can produce somewhat inefficient code:
 7125: @format
 7126: @code{lp+!#} current-locals-size @minus{} orig-locals-size
 7127: <orig target>:
 7128: @code{lp+!#} orig-locals-size @minus{} new-locals-size
 7129: @end format
 7130: The second @code{lp+!#} adjusts the locals stack pointer from the
 7131: level at the @i{orig} point to the level after the @code{THEN}. The
 7132: first @code{lp+!#} adjusts the locals stack pointer from the current
 7133: level to the level at the orig point, so the complete effect is an
 7134: adjustment from the current level to the right level after the
 7135: @code{THEN}.
 7136: 
 7137: @cindex locals information on the control-flow stack
 7138: @cindex control-flow stack items, locals information
 7139: In a conventional Forth implementation a dest control-flow stack entry
 7140: is just the target address and an orig entry is just the address to be
 7141: patched. Our locals implementation adds a word list to every orig or dest
 7142: item. It is the list of locals visible (or assumed visible) at the point
 7143: described by the entry. Our implementation also adds a tag to identify
 7144: the kind of entry, in particular to differentiate between live and dead
 7145: (reachable and unreachable) orig entries.
 7146: 
 7147: A few unusual operations have to be performed on locals word lists:
 7148: 
 7149: 
 7150: doc-common-list
 7151: doc-sub-list?
 7152: doc-list-size
 7153: 
 7154: 
 7155: Several features of our locals word list implementation make these
 7156: operations easy to implement: The locals word lists are organised as
 7157: linked lists; the tails of these lists are shared, if the lists
 7158: contain some of the same locals; and the address of a name is greater
 7159: than the address of the names behind it in the list.
 7160: 
 7161: Another important implementation detail is the variable
 7162: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
 7163: determine if they can be reached directly or only through the branch
 7164: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
 7165: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
 7166: definition, by @code{BEGIN} and usually by @code{THEN}.
 7167: 
 7168: Counted loops are similar to other loops in most respects, but
 7169: @code{LEAVE} requires special attention: It performs basically the same
 7170: service as @code{AHEAD}, but it does not create a control-flow stack
 7171: entry. Therefore the information has to be stored elsewhere;
 7172: traditionally, the information was stored in the target fields of the
 7173: branches created by the @code{LEAVE}s, by organizing these fields into a
 7174: linked list. Unfortunately, this clever trick does not provide enough
 7175: space for storing our extended control flow information. Therefore, we
 7176: introduce another stack, the leave stack. It contains the control-flow
 7177: stack entries for all unresolved @code{LEAVE}s.
 7178: 
 7179: Local names are kept until the end of the colon definition, even if
 7180: they are no longer visible in any control-flow path. In a few cases
 7181: this may lead to increased space needs for the locals name area, but
 7182: usually less than reclaiming this space would cost in code size.
 7183: 
 7184: 
 7185: @node ANS Forth locals,  , Gforth locals, Locals
 7186: @subsection ANS Forth locals
 7187: @cindex locals, ANS Forth style
 7188: 
 7189: The ANS Forth locals wordset does not define a syntax for locals, but
 7190: words that make it possible to define various syntaxes. One of the
 7191: possible syntaxes is a subset of the syntax we used in the Gforth locals
 7192: wordset, i.e.:
 7193: 
 7194: @example
 7195: @{ local1 local2 ... -- comment @}
 7196: @end example
 7197: @noindent
 7198: or
 7199: @example
 7200: @{ local1 local2 ... @}
 7201: @end example
 7202: 
 7203: The order of the locals corresponds to the order in a stack comment. The
 7204: restrictions are:
 7205: 
 7206: @itemize @bullet
 7207: @item
 7208: Locals can only be cell-sized values (no type specifiers are allowed).
 7209: @item
 7210: Locals can be defined only outside control structures.
 7211: @item
 7212: Locals can interfere with explicit usage of the return stack. For the
 7213: exact (and long) rules, see the standard. If you don't use return stack
 7214: accessing words in a definition using locals, you will be all right. The
 7215: purpose of this rule is to make locals implementation on the return
 7216: stack easier.
 7217: @item
 7218: The whole definition must be in one line.
 7219: @end itemize
 7220: 
 7221: Locals defined in this way behave like @code{VALUE}s
 7222: (@xref{Values}). I.e., they are initialized from the stack. Using their
 7223: name produces their value. Their value can be changed using @code{TO}.
 7224: 
 7225: Since this syntax is supported by Gforth directly, you need not do
 7226: anything to use it. If you want to port a program using this syntax to
 7227: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
 7228: syntax on the other system.
 7229: 
 7230: Note that a syntax shown in the standard, section A.13 looks
 7231: similar, but is quite different in having the order of locals
 7232: reversed. Beware!
 7233: 
 7234: The ANS Forth locals wordset itself consists of a word:
 7235: 
 7236: 
 7237: doc-(local)
 7238: 
 7239: 
 7240: The ANS Forth locals extension wordset defines a syntax using @code{locals|}, but it is so
 7241: awful that we strongly recommend not to use it. We have implemented this
 7242: syntax to make porting to Gforth easy, but do not document it here. The
 7243: problem with this syntax is that the locals are defined in an order
 7244: reversed with respect to the standard stack comment notation, making
 7245: programs harder to read, and easier to misread and miswrite. The only
 7246: merit of this syntax is that it is easy to implement using the ANS Forth
 7247: locals wordset.
 7248: 
 7249: 
 7250: @c ----------------------------------------------------------
 7251: @node Structures, Object-oriented Forth, Locals, Words
 7252: @section  Structures
 7253: @cindex structures
 7254: @cindex records
 7255: 
 7256: This section presents the structure package that comes with Gforth. A
 7257: version of the package implemented in ANS Forth is available in
 7258: @file{compat/struct.fs}. This package was inspired by a posting on
 7259: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
 7260: possibly John Hayes). A version of this section has been published in
 7261: ???. Marcel Hendrix provided helpful comments.
 7262: 
 7263: @menu
 7264: * Why explicit structure support?::  
 7265: * Structure Usage::             
 7266: * Structure Naming Convention::  
 7267: * Structure Implementation::    
 7268: * Structure Glossary::          
 7269: @end menu
 7270: 
 7271: @node Why explicit structure support?, Structure Usage, Structures, Structures
 7272: @subsection Why explicit structure support?
 7273: 
 7274: @cindex address arithmetic for structures
 7275: @cindex structures using address arithmetic
 7276: If we want to use a structure containing several fields, we could simply
 7277: reserve memory for it, and access the fields using address arithmetic
 7278: (@pxref{Address arithmetic}). As an example, consider a structure with
 7279: the following fields
 7280: 
 7281: @table @code
 7282: @item a
 7283: is a float
 7284: @item b
 7285: is a cell
 7286: @item c
 7287: is a float
 7288: @end table
 7289: 
 7290: Given the (float-aligned) base address of the structure we get the
 7291: address of the field
 7292: 
 7293: @table @code
 7294: @item a
 7295: without doing anything further.
 7296: @item b
 7297: with @code{float+}
 7298: @item c
 7299: with @code{float+ cell+ faligned}
 7300: @end table
 7301: 
 7302: It is easy to see that this can become quite tiring. 
 7303: 
 7304: Moreover, it is not very readable, because seeing a
 7305: @code{cell+} tells us neither which kind of structure is
 7306: accessed nor what field is accessed; we have to somehow infer the kind
 7307: of structure, and then look up in the documentation, which field of
 7308: that structure corresponds to that offset.
 7309: 
 7310: Finally, this kind of address arithmetic also causes maintenance
 7311: troubles: If you add or delete a field somewhere in the middle of the
 7312: structure, you have to find and change all computations for the fields
 7313: afterwards.
 7314: 
 7315: So, instead of using @code{cell+} and friends directly, how
 7316: about storing the offsets in constants:
 7317: 
 7318: @example
 7319: 0 constant a-offset
 7320: 0 float+ constant b-offset
 7321: 0 float+ cell+ faligned c-offset
 7322: @end example
 7323: 
 7324: Now we can get the address of field @code{x} with @code{x-offset
 7325: +}. This is much better in all respects. Of course, you still
 7326: have to change all later offset definitions if you add a field. You can
 7327: fix this by declaring the offsets in the following way:
 7328: 
 7329: @example
 7330: 0 constant a-offset
 7331: a-offset float+ constant b-offset
 7332: b-offset cell+ faligned constant c-offset
 7333: @end example
 7334: 
 7335: Since we always use the offsets with @code{+}, we could use a defining
 7336: word @code{cfield} that includes the @code{+} in the action of the
 7337: defined word:
 7338: 
 7339: @example
 7340: : cfield ( n "name" -- )
 7341:     create ,
 7342: does> ( name execution: addr1 -- addr2 )
 7343:     @@ + ;
 7344: 
 7345: 0 cfield a
 7346: 0 a float+ cfield b
 7347: 0 b cell+ faligned cfield c
 7348: @end example
 7349: 
 7350: Instead of @code{x-offset +}, we now simply write @code{x}.
 7351: 
 7352: The structure field words now can be used quite nicely. However,
 7353: their definition is still a bit cumbersome: We have to repeat the
 7354: name, the information about size and alignment is distributed before
 7355: and after the field definitions etc.  The structure package presented
 7356: here addresses these problems.
 7357: 
 7358: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
 7359: @subsection Structure Usage
 7360: @cindex structure usage
 7361: 
 7362: @cindex @code{field} usage
 7363: @cindex @code{struct} usage
 7364: @cindex @code{end-struct} usage
 7365: You can define a structure for a (data-less) linked list with:
 7366: @example
 7367: struct
 7368:     cell% field list-next
 7369: end-struct list%
 7370: @end example
 7371: 
 7372: With the address of the list node on the stack, you can compute the
 7373: address of the field that contains the address of the next node with
 7374: @code{list-next}. E.g., you can determine the length of a list
 7375: with:
 7376: 
 7377: @example
 7378: : list-length ( list -- n )
 7379: \ "list" is a pointer to the first element of a linked list
 7380: \ "n" is the length of the list
 7381:     0 BEGIN ( list1 n1 )
 7382:         over
 7383:     WHILE ( list1 n1 )
 7384:         1+ swap list-next @@ swap
 7385:     REPEAT
 7386:     nip ;
 7387: @end example
 7388: 
 7389: You can reserve memory for a list node in the dictionary with
 7390: @code{list% %allot}, which leaves the address of the list node on the
 7391: stack. For the equivalent allocation on the heap you can use @code{list%
 7392: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
 7393: use @code{list% %allocate}). You can get the the size of a list
 7394: node with @code{list% %size} and its alignment with @code{list%
 7395: %alignment}.
 7396: 
 7397: Note that in ANS Forth the body of a @code{create}d word is
 7398: @code{aligned} but not necessarily @code{faligned};
 7399: therefore, if you do a:
 7400: @example
 7401: create @emph{name} foo% %allot
 7402: @end example
 7403: 
 7404: @noindent
 7405: then the memory alloted for @code{foo%} is
 7406: guaranteed to start at the body of @code{@emph{name}} only if
 7407: @code{foo%} contains only character, cell and double fields.
 7408: 
 7409: @cindex structures containing structures
 7410: You can include a structure @code{foo%} as a field of
 7411: another structure, like this:
 7412: @example
 7413: struct
 7414: ...
 7415:     foo% field ...
 7416: ...
 7417: end-struct ...
 7418: @end example
 7419: 
 7420: @cindex structure extension
 7421: @cindex extended records
 7422: Instead of starting with an empty structure, you can extend an
 7423: existing structure. E.g., a plain linked list without data, as defined
 7424: above, is hardly useful; You can extend it to a linked list of integers,
 7425: like this:@footnote{This feature is also known as @emph{extended
 7426: records}. It is the main innovation in the Oberon language; in other
 7427: words, adding this feature to Modula-2 led Wirth to create a new
 7428: language, write a new compiler etc.  Adding this feature to Forth just
 7429: required a few lines of code.}
 7430: 
 7431: @example
 7432: list%
 7433:     cell% field intlist-int
 7434: end-struct intlist%
 7435: @end example
 7436: 
 7437: @code{intlist%} is a structure with two fields:
 7438: @code{list-next} and @code{intlist-int}.
 7439: 
 7440: @cindex structures containing arrays
 7441: You can specify an array type containing @emph{n} elements of
 7442: type @code{foo%} like this:
 7443: 
 7444: @example
 7445: foo% @emph{n} *
 7446: @end example
 7447: 
 7448: You can use this array type in any place where you can use a normal
 7449: type, e.g., when defining a @code{field}, or with
 7450: @code{%allot}.
 7451: 
 7452: @cindex first field optimization
 7453: The first field is at the base address of a structure and the word
 7454: for this field (e.g., @code{list-next}) actually does not change
 7455: the address on the stack. You may be tempted to leave it away in the
 7456: interest of run-time and space efficiency. This is not necessary,
 7457: because the structure package optimizes this case and compiling such
 7458: words does not generate any code. So, in the interest of readability
 7459: and maintainability you should include the word for the field when
 7460: accessing the field.
 7461: 
 7462: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
 7463: @subsection Structure Naming Convention
 7464: @cindex structure naming convention
 7465: 
 7466: The field names that come to (my) mind are often quite generic, and,
 7467: if used, would cause frequent name clashes. E.g., many structures
 7468: probably contain a @code{counter} field. The structure names
 7469: that come to (my) mind are often also the logical choice for the names
 7470: of words that create such a structure.
 7471: 
 7472: Therefore, I have adopted the following naming conventions: 
 7473: 
 7474: @itemize @bullet
 7475: @cindex field naming convention
 7476: @item
 7477: The names of fields are of the form
 7478: @code{@emph{struct}-@emph{field}}, where
 7479: @code{@emph{struct}} is the basic name of the structure, and
 7480: @code{@emph{field}} is the basic name of the field. You can
 7481: think of field words as converting the (address of the)
 7482: structure into the (address of the) field.
 7483: 
 7484: @cindex structure naming convention
 7485: @item
 7486: The names of structures are of the form
 7487: @code{@emph{struct}%}, where
 7488: @code{@emph{struct}} is the basic name of the structure.
 7489: @end itemize
 7490: 
 7491: This naming convention does not work that well for fields of extended
 7492: structures; e.g., the integer list structure has a field
 7493: @code{intlist-int}, but has @code{list-next}, not
 7494: @code{intlist-next}.
 7495: 
 7496: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
 7497: @subsection Structure Implementation
 7498: @cindex structure implementation
 7499: @cindex implementation of structures
 7500: 
 7501: The central idea in the implementation is to pass the data about the
 7502: structure being built on the stack, not in some global
 7503: variable. Everything else falls into place naturally once this design
 7504: decision is made.
 7505: 
 7506: The type description on the stack is of the form @emph{align
 7507: size}. Keeping the size on the top-of-stack makes dealing with arrays
 7508: very simple.
 7509: 
 7510: @code{field} is a defining word that uses @code{Create}
 7511: and @code{DOES>}. The body of the field contains the offset
 7512: of the field, and the normal @code{DOES>} action is simply:
 7513: 
 7514: @example
 7515: @ +
 7516: @end example
 7517: 
 7518: @noindent
 7519: i.e., add the offset to the address, giving the stack effect
 7520: @i{addr1 -- addr2} for a field.
 7521: 
 7522: @cindex first field optimization, implementation
 7523: This simple structure is slightly complicated by the optimization
 7524: for fields with offset 0, which requires a different
 7525: @code{DOES>}-part (because we cannot rely on there being
 7526: something on the stack if such a field is invoked during
 7527: compilation). Therefore, we put the different @code{DOES>}-parts
 7528: in separate words, and decide which one to invoke based on the
 7529: offset. For a zero offset, the field is basically a noop; it is
 7530: immediate, and therefore no code is generated when it is compiled.
 7531: 
 7532: @node Structure Glossary,  , Structure Implementation, Structures
 7533: @subsection Structure Glossary
 7534: @cindex structure glossary
 7535: 
 7536: 
 7537: doc-%align
 7538: doc-%alignment
 7539: doc-%alloc
 7540: doc-%allocate
 7541: doc-%allot
 7542: doc-cell%
 7543: doc-char%
 7544: doc-dfloat%
 7545: doc-double%
 7546: doc-end-struct
 7547: doc-field
 7548: doc-float%
 7549: doc-naligned
 7550: doc-sfloat%
 7551: doc-%size
 7552: doc-struct
 7553: 
 7554: 
 7555: @c -------------------------------------------------------------
 7556: @node Object-oriented Forth, Passing Commands to the OS, Structures, Words
 7557: @section Object-oriented Forth
 7558: 
 7559: Gforth comes with three packages for object-oriented programming:
 7560: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
 7561: is preloaded, so you have to @code{include} them before use. The most
 7562: important differences between these packages (and others) are discussed
 7563: in @ref{Comparison with other object models}. All packages are written
 7564: in ANS Forth and can be used with any other ANS Forth.
 7565: 
 7566: @menu
 7567: * Why object-oriented programming?::
 7568: * Object-Oriented Terminology::
 7569: * Objects::
 7570: * OOF::
 7571: * Mini-OOF::
 7572: * Comparison with other object models::  
 7573: @end menu
 7574: 
 7575: 
 7576: @node Why object-oriented programming?, Object-Oriented Terminology, , Object-oriented Forth
 7577: @subsubsection Why object-oriented programming?
 7578: @cindex object-oriented programming motivation
 7579: @cindex motivation for object-oriented programming
 7580: 
 7581: Often we have to deal with several data structures (@emph{objects}),
 7582: that have to be treated similarly in some respects, but differently in
 7583: others. Graphical objects are the textbook example: circles, triangles,
 7584: dinosaurs, icons, and others, and we may want to add more during program
 7585: development. We want to apply some operations to any graphical object,
 7586: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
 7587: has to do something different for every kind of object.
 7588: @comment TODO add some other operations eg perimeter, area
 7589: @comment and tie in to concrete examples later..
 7590: 
 7591: We could implement @code{draw} as a big @code{CASE}
 7592: control structure that executes the appropriate code depending on the
 7593: kind of object to be drawn. This would be not be very elegant, and,
 7594: moreover, we would have to change @code{draw} every time we add
 7595: a new kind of graphical object (say, a spaceship).
 7596: 
 7597: What we would rather do is: When defining spaceships, we would tell
 7598: the system: ``Here's how you @code{draw} a spaceship; you figure
 7599: out the rest''.
 7600: 
 7601: This is the problem that all systems solve that (rightfully) call
 7602: themselves object-oriented; the object-oriented packages presented here
 7603: solve this problem (and not much else).
 7604: @comment TODO ?list properties of oo systems.. oo vs o-based?
 7605: 
 7606: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
 7607: @subsubsection Object-Oriented Terminology
 7608: @cindex object-oriented terminology
 7609: @cindex terminology for object-oriented programming
 7610: 
 7611: This section is mainly for reference, so you don't have to understand
 7612: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
 7613: short:
 7614: 
 7615: @table @emph
 7616: @cindex class
 7617: @item class
 7618: a data structure definition with some extras.
 7619: 
 7620: @cindex object
 7621: @item object
 7622: an instance of the data structure described by the class definition.
 7623: 
 7624: @cindex instance variables
 7625: @item instance variables
 7626: fields of the data structure.
 7627: 
 7628: @cindex selector
 7629: @cindex method selector
 7630: @cindex virtual function
 7631: @item selector
 7632: (or @emph{method selector}) a word (e.g.,
 7633: @code{draw}) that performs an operation on a variety of data
 7634: structures (classes). A selector describes @emph{what} operation to
 7635: perform. In C++ terminology: a (pure) virtual function.
 7636: 
 7637: @cindex method
 7638: @item method
 7639: the concrete definition that performs the operation
 7640: described by the selector for a specific class. A method specifies
 7641: @emph{how} the operation is performed for a specific class.
 7642: 
 7643: @cindex selector invocation
 7644: @cindex message send
 7645: @cindex invoking a selector
 7646: @item selector invocation
 7647: a call of a selector. One argument of the call (the TOS (top-of-stack))
 7648: is used for determining which method is used. In Smalltalk terminology:
 7649: a message (consisting of the selector and the other arguments) is sent
 7650: to the object.
 7651: 
 7652: @cindex receiving object
 7653: @item receiving object
 7654: the object used for determining the method executed by a selector
 7655: invocation. In the @file{objects.fs} model, it is the object that is on
 7656: the TOS when the selector is invoked. (@emph{Receiving} comes from
 7657: the Smalltalk @emph{message} terminology.)
 7658: 
 7659: @cindex child class
 7660: @cindex parent class
 7661: @cindex inheritance
 7662: @item child class
 7663: a class that has (@emph{inherits}) all properties (instance variables,
 7664: selectors, methods) from a @emph{parent class}. In Smalltalk
 7665: terminology: The subclass inherits from the superclass. In C++
 7666: terminology: The derived class inherits from the base class.
 7667: 
 7668: @end table
 7669: 
 7670: @c If you wonder about the message sending terminology, it comes from
 7671: @c a time when each object had it's own task and objects communicated via
 7672: @c message passing; eventually the Smalltalk developers realized that
 7673: @c they can do most things through simple (indirect) calls. They kept the
 7674: @c terminology.
 7675: 
 7676: 
 7677: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
 7678: @subsection The @file{objects.fs} model
 7679: @cindex objects
 7680: @cindex object-oriented programming
 7681: 
 7682: @cindex @file{objects.fs}
 7683: @cindex @file{oof.fs}
 7684: 
 7685: This section describes the @file{objects.fs} package. This material also
 7686: has been published in @cite{Yet Another Forth Objects Package} by Anton
 7687: Ertl and appeared in Forth Dimensions 19(2), pages 37--43
 7688: (@url{http://www.complang.tuwien.ac.at/forth/objects/objects.html}).
 7689: @c McKewan's and Zsoter's packages
 7690: 
 7691: This section assumes that you have read @ref{Structures}.
 7692: 
 7693: The techniques on which this model is based have been used to implement
 7694: the parser generator, Gray, and have also been used in Gforth for
 7695: implementing the various flavours of word lists (hashed or not,
 7696: case-sensitive or not, special-purpose word lists for locals etc.).
 7697: 
 7698: 
 7699: @menu
 7700: * Properties of the Objects model::  
 7701: * Basic Objects Usage::         
 7702: * The Objects base class::      
 7703: * Creating objects::            
 7704: * Object-Oriented Programming Style::  
 7705: * Class Binding::               
 7706: * Method conveniences::         
 7707: * Classes and Scoping::         
 7708: * Dividing classes::            
 7709: * Object Interfaces::           
 7710: * Objects Implementation::      
 7711: * Objects Glossary::            
 7712: @end menu
 7713: 
 7714: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
 7715: and Bernd Paysan helped me with the related works section.
 7716: 
 7717: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
 7718: @subsubsection Properties of the @file{objects.fs} model
 7719: @cindex @file{objects.fs} properties
 7720: 
 7721: @itemize @bullet
 7722: @item
 7723: It is straightforward to pass objects on the stack. Passing
 7724: selectors on the stack is a little less convenient, but possible.
 7725: 
 7726: @item
 7727: Objects are just data structures in memory, and are referenced by their
 7728: address. You can create words for objects with normal defining words
 7729: like @code{constant}. Likewise, there is no difference between instance
 7730: variables that contain objects and those that contain other data.
 7731: 
 7732: @item
 7733: Late binding is efficient and easy to use.
 7734: 
 7735: @item
 7736: It avoids parsing, and thus avoids problems with state-smartness
 7737: and reduced extensibility; for convenience there are a few parsing
 7738: words, but they have non-parsing counterparts. There are also a few
 7739: defining words that parse. This is hard to avoid, because all standard
 7740: defining words parse (except @code{:noname}); however, such
 7741: words are not as bad as many other parsing words, because they are not
 7742: state-smart.
 7743: 
 7744: @item
 7745: It does not try to incorporate everything. It does a few things and does
 7746: them well (IMO). In particular, this model was not designed to support
 7747: information hiding (although it has features that may help); you can use
 7748: a separate package for achieving this.
 7749: 
 7750: @item
 7751: It is layered; you don't have to learn and use all features to use this
 7752: model. Only a few features are necessary (@xref{Basic Objects Usage},
 7753: @xref{The Objects base class}, @xref{Creating objects}.), the others
 7754: are optional and independent of each other.
 7755: 
 7756: @item
 7757: An implementation in ANS Forth is available.
 7758: 
 7759: @end itemize
 7760: 
 7761: 
 7762: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
 7763: @subsubsection Basic @file{objects.fs} Usage
 7764: @cindex basic objects usage
 7765: @cindex objects, basic usage
 7766: 
 7767: You can define a class for graphical objects like this:
 7768: 
 7769: @cindex @code{class} usage
 7770: @cindex @code{end-class} usage
 7771: @cindex @code{selector} usage
 7772: @example
 7773: object class \ "object" is the parent class
 7774:   selector draw ( x y graphical -- )
 7775: end-class graphical
 7776: @end example
 7777: 
 7778: This code defines a class @code{graphical} with an
 7779: operation @code{draw}.  We can perform the operation
 7780: @code{draw} on any @code{graphical} object, e.g.:
 7781: 
 7782: @example
 7783: 100 100 t-rex draw
 7784: @end example
 7785: 
 7786: @noindent
 7787: where @code{t-rex} is a word (say, a constant) that produces a
 7788: graphical object.
 7789: 
 7790: @comment TODO add a 2nd operation eg perimeter.. and use for
 7791: @comment a concrete example
 7792: 
 7793: @cindex abstract class
 7794: How do we create a graphical object? With the present definitions,
 7795: we cannot create a useful graphical object. The class
 7796: @code{graphical} describes graphical objects in general, but not
 7797: any concrete graphical object type (C++ users would call it an
 7798: @emph{abstract class}); e.g., there is no method for the selector
 7799: @code{draw} in the class @code{graphical}.
 7800: 
 7801: For concrete graphical objects, we define child classes of the
 7802: class @code{graphical}, e.g.:
 7803: 
 7804: @cindex @code{overrides} usage
 7805: @cindex @code{field} usage in class definition
 7806: @example
 7807: graphical class \ "graphical" is the parent class
 7808:   cell% field circle-radius
 7809: 
 7810: :noname ( x y circle -- )
 7811:   circle-radius @@ draw-circle ;
 7812: overrides draw
 7813: 
 7814: :noname ( n-radius circle -- )
 7815:   circle-radius ! ;
 7816: overrides construct
 7817: 
 7818: end-class circle
 7819: @end example
 7820: 
 7821: Here we define a class @code{circle} as a child of @code{graphical},
 7822: with field @code{circle-radius} (which behaves just like a field
 7823: (@pxref{Structures}); it defines (using @code{overrides}) new methods
 7824: for the selectors @code{draw} and @code{construct} (@code{construct} is
 7825: defined in @code{object}, the parent class of @code{graphical}).
 7826: 
 7827: Now we can create a circle on the heap (i.e.,
 7828: @code{allocate}d memory) with:
 7829: 
 7830: @cindex @code{heap-new} usage
 7831: @example
 7832: 50 circle heap-new constant my-circle
 7833: @end example
 7834: 
 7835: @noindent
 7836: @code{heap-new} invokes @code{construct}, thus
 7837: initializing the field @code{circle-radius} with 50. We can draw
 7838: this new circle at (100,100) with:
 7839: 
 7840: @example
 7841: 100 100 my-circle draw
 7842: @end example
 7843: 
 7844: @cindex selector invocation, restrictions
 7845: @cindex class definition, restrictions
 7846: Note: You can only invoke a selector if the object on the TOS
 7847: (the receiving object) belongs to the class where the selector was
 7848: defined or one of its descendents; e.g., you can invoke
 7849: @code{draw} only for objects belonging to @code{graphical}
 7850: or its descendents (e.g., @code{circle}).  Immediately before
 7851: @code{end-class}, the search order has to be the same as
 7852: immediately after @code{class}.
 7853: 
 7854: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
 7855: @subsubsection The @file{object.fs} base class
 7856: @cindex @code{object} class
 7857: 
 7858: When you define a class, you have to specify a parent class.  So how do
 7859: you start defining classes? There is one class available from the start:
 7860: @code{object}. It is ancestor for all classes and so is the
 7861: only class that has no parent. It has two selectors: @code{construct}
 7862: and @code{print}.
 7863: 
 7864: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
 7865: @subsubsection Creating objects
 7866: @cindex creating objects
 7867: @cindex object creation
 7868: @cindex object allocation options
 7869: 
 7870: @cindex @code{heap-new} discussion
 7871: @cindex @code{dict-new} discussion
 7872: @cindex @code{construct} discussion
 7873: You can create and initialize an object of a class on the heap with
 7874: @code{heap-new} ( ... class -- object ) and in the dictionary
 7875: (allocation with @code{allot}) with @code{dict-new} (
 7876: ... class -- object ). Both words invoke @code{construct}, which
 7877: consumes the stack items indicated by "..." above.
 7878: 
 7879: @cindex @code{init-object} discussion
 7880: @cindex @code{class-inst-size} discussion
 7881: If you want to allocate memory for an object yourself, you can get its
 7882: alignment and size with @code{class-inst-size 2@@} ( class --
 7883: align size ). Once you have memory for an object, you can initialize
 7884: it with @code{init-object} ( ... class object -- );
 7885: @code{construct} does only a part of the necessary work.
 7886: 
 7887: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
 7888: @subsubsection Object-Oriented Programming Style
 7889: @cindex object-oriented programming style
 7890: 
 7891: This section is not exhaustive.
 7892: 
 7893: @cindex stack effects of selectors
 7894: @cindex selectors and stack effects
 7895: In general, it is a good idea to ensure that all methods for the
 7896: same selector have the same stack effect: when you invoke a selector,
 7897: you often have no idea which method will be invoked, so, unless all
 7898: methods have the same stack effect, you will not know the stack effect
 7899: of the selector invocation.
 7900: 
 7901: One exception to this rule is methods for the selector
 7902: @code{construct}. We know which method is invoked, because we
 7903: specify the class to be constructed at the same place. Actually, I
 7904: defined @code{construct} as a selector only to give the users a
 7905: convenient way to specify initialization. The way it is used, a
 7906: mechanism different from selector invocation would be more natural
 7907: (but probably would take more code and more space to explain).
 7908: 
 7909: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
 7910: @subsubsection Class Binding
 7911: @cindex class binding
 7912: @cindex early binding
 7913: 
 7914: @cindex late binding
 7915: Normal selector invocations determine the method at run-time depending
 7916: on the class of the receiving object. This run-time selection is called
 7917: @i{late binding}.
 7918: 
 7919: Sometimes it's preferable to invoke a different method. For example,
 7920: you might want to use the simple method for @code{print}ing
 7921: @code{object}s instead of the possibly long-winded @code{print} method
 7922: of the receiver class. You can achieve this by replacing the invocation
 7923: of @code{print} with:
 7924: 
 7925: @cindex @code{[bind]} usage
 7926: @example
 7927: [bind] object print
 7928: @end example
 7929: 
 7930: @noindent
 7931: in compiled code or:
 7932: 
 7933: @cindex @code{bind} usage
 7934: @example
 7935: bind object print
 7936: @end example
 7937: 
 7938: @cindex class binding, alternative to
 7939: @noindent
 7940: in interpreted code. Alternatively, you can define the method with a
 7941: name (e.g., @code{print-object}), and then invoke it through the
 7942: name. Class binding is just a (often more convenient) way to achieve
 7943: the same effect; it avoids name clutter and allows you to invoke
 7944: methods directly without naming them first.
 7945: 
 7946: @cindex superclass binding
 7947: @cindex parent class binding
 7948: A frequent use of class binding is this: When we define a method
 7949: for a selector, we often want the method to do what the selector does
 7950: in the parent class, and a little more. There is a special word for
 7951: this purpose: @code{[parent]}; @code{[parent]
 7952: @emph{selector}} is equivalent to @code{[bind] @emph{parent
 7953: selector}}, where @code{@emph{parent}} is the parent
 7954: class of the current class. E.g., a method definition might look like:
 7955: 
 7956: @cindex @code{[parent]} usage
 7957: @example
 7958: :noname
 7959:   dup [parent] foo \ do parent's foo on the receiving object
 7960:   ... \ do some more
 7961: ; overrides foo
 7962: @end example
 7963: 
 7964: @cindex class binding as optimization
 7965: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
 7966: March 1997), Andrew McKewan presents class binding as an optimization
 7967: technique. I recommend not using it for this purpose unless you are in
 7968: an emergency. Late binding is pretty fast with this model anyway, so the
 7969: benefit of using class binding is small; the cost of using class binding
 7970: where it is not appropriate is reduced maintainability.
 7971: 
 7972: While we are at programming style questions: You should bind
 7973: selectors only to ancestor classes of the receiving object. E.g., say,
 7974: you know that the receiving object is of class @code{foo} or its
 7975: descendents; then you should bind only to @code{foo} and its
 7976: ancestors.
 7977: 
 7978: @node Method conveniences, Classes and Scoping, Class Binding, Objects
 7979: @subsubsection Method conveniences
 7980: @cindex method conveniences
 7981: 
 7982: In a method you usually access the receiving object pretty often.  If
 7983: you define the method as a plain colon definition (e.g., with
 7984: @code{:noname}), you may have to do a lot of stack
 7985: gymnastics. To avoid this, you can define the method with @code{m:
 7986: ... ;m}. E.g., you could define the method for
 7987: @code{draw}ing a @code{circle} with
 7988: 
 7989: @cindex @code{this} usage
 7990: @cindex @code{m:} usage
 7991: @cindex @code{;m} usage
 7992: @example
 7993: m: ( x y circle -- )
 7994:   ( x y ) this circle-radius @@ draw-circle ;m
 7995: @end example
 7996: 
 7997: @cindex @code{exit} in @code{m: ... ;m}
 7998: @cindex @code{exitm} discussion
 7999: @cindex @code{catch} in @code{m: ... ;m}
 8000: When this method is executed, the receiver object is removed from the
 8001: stack; you can access it with @code{this} (admittedly, in this
 8002: example the use of @code{m: ... ;m} offers no advantage). Note
 8003: that I specify the stack effect for the whole method (i.e. including
 8004: the receiver object), not just for the code between @code{m:}
 8005: and @code{;m}. You cannot use @code{exit} in
 8006: @code{m:...;m}; instead, use
 8007: @code{exitm}.@footnote{Moreover, for any word that calls
 8008: @code{catch} and was defined before loading
 8009: @code{objects.fs}, you have to redefine it like I redefined
 8010: @code{catch}: @code{: catch this >r catch r> to-this ;}}
 8011: 
 8012: @cindex @code{inst-var} usage
 8013: You will frequently use sequences of the form @code{this
 8014: @emph{field}} (in the example above: @code{this
 8015: circle-radius}). If you use the field only in this way, you can
 8016: define it with @code{inst-var} and eliminate the
 8017: @code{this} before the field name. E.g., the @code{circle}
 8018: class above could also be defined with:
 8019: 
 8020: @example
 8021: graphical class
 8022:   cell% inst-var radius
 8023: 
 8024: m: ( x y circle -- )
 8025:   radius @@ draw-circle ;m
 8026: overrides draw
 8027: 
 8028: m: ( n-radius circle -- )
 8029:   radius ! ;m
 8030: overrides construct
 8031: 
 8032: end-class circle
 8033: @end example
 8034: 
 8035: @code{radius} can only be used in @code{circle} and its
 8036: descendent classes and inside @code{m:...;m}.
 8037: 
 8038: @cindex @code{inst-value} usage
 8039: You can also define fields with @code{inst-value}, which is
 8040: to @code{inst-var} what @code{value} is to
 8041: @code{variable}.  You can change the value of such a field with
 8042: @code{[to-inst]}.  E.g., we could also define the class
 8043: @code{circle} like this:
 8044: 
 8045: @example
 8046: graphical class
 8047:   inst-value radius
 8048: 
 8049: m: ( x y circle -- )
 8050:   radius draw-circle ;m
 8051: overrides draw
 8052: 
 8053: m: ( n-radius circle -- )
 8054:   [to-inst] radius ;m
 8055: overrides construct
 8056: 
 8057: end-class circle
 8058: @end example
 8059: 
 8060: Finally, you can define named methods with @code{:m}.  One use of this
 8061: feature is the definition of words that occur only in one class and are
 8062: not intended to be overridden, but which still need method context
 8063: (e.g., for accessing @code{inst-var}s).  Another use is for methods that
 8064: would be bound frequently, if defined anonymously.
 8065: 
 8066: 
 8067: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
 8068: @subsubsection Classes and Scoping
 8069: @cindex classes and scoping
 8070: @cindex scoping and classes
 8071: 
 8072: Inheritance is frequent, unlike structure extension. This exacerbates
 8073: the problem with the field name convention (@pxref{Structure Naming
 8074: Convention}): One always has to remember in which class the field was
 8075: originally defined; changing a part of the class structure would require
 8076: changes for renaming in otherwise unaffected code.
 8077: 
 8078: @cindex @code{inst-var} visibility
 8079: @cindex @code{inst-value} visibility
 8080: To solve this problem, I added a scoping mechanism (which was not in my
 8081: original charter): A field defined with @code{inst-var} (or
 8082: @code{inst-value}) is visible only in the class where it is defined and in
 8083: the descendent classes of this class.  Using such fields only makes
 8084: sense in @code{m:}-defined methods in these classes anyway.
 8085: 
 8086: This scoping mechanism allows us to use the unadorned field name,
 8087: because name clashes with unrelated words become much less likely.
 8088: 
 8089: @cindex @code{protected} discussion
 8090: @cindex @code{private} discussion
 8091: Once we have this mechanism, we can also use it for controlling the
 8092: visibility of other words: All words defined after
 8093: @code{protected} are visible only in the current class and its
 8094: descendents. @code{public} restores the compilation
 8095: (i.e. @code{current}) word list that was in effect before. If you
 8096: have several @code{protected}s without an intervening
 8097: @code{public} or @code{set-current}, @code{public}
 8098: will restore the compilation word list in effect before the first of
 8099: these @code{protected}s.
 8100: 
 8101: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
 8102: @subsubsection Dividing classes
 8103: @cindex Dividing classes
 8104: @cindex @code{methods}...@code{end-methods}
 8105: 
 8106: You may want to do the definition of methods separate from the
 8107: definition of the class, its selectors, fields, and instance variables,
 8108: i.e., separate the implementation from the definition.  You can do this
 8109: in the following way:
 8110: 
 8111: @example
 8112: graphical class
 8113:   inst-value radius
 8114: end-class circle
 8115: 
 8116: ... \ do some other stuff
 8117: 
 8118: circle methods \ now we are ready
 8119: 
 8120: m: ( x y circle -- )
 8121:   radius draw-circle ;m
 8122: overrides draw
 8123: 
 8124: m: ( n-radius circle -- )
 8125:   [to-inst] radius ;m
 8126: overrides construct
 8127: 
 8128: end-methods
 8129: @end example
 8130: 
 8131: You can use several @code{methods}...@code{end-methods} sections.  The
 8132: only things you can do to the class in these sections are: defining
 8133: methods, and overriding the class's selectors.  You must not define new
 8134: selectors or fields.
 8135: 
 8136: Note that you often have to override a selector before using it.  In
 8137: particular, you usually have to override @code{construct} with a new
 8138: method before you can invoke @code{heap-new} and friends.  E.g., you
 8139: must not create a circle before the @code{overrides construct} sequence
 8140: in the example above.
 8141: 
 8142: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
 8143: @subsubsection Object Interfaces
 8144: @cindex object interfaces
 8145: @cindex interfaces for objects
 8146: 
 8147: In this model you can only call selectors defined in the class of the
 8148: receiving objects or in one of its ancestors. If you call a selector
 8149: with a receiving object that is not in one of these classes, the
 8150: result is undefined; if you are lucky, the program crashes
 8151: immediately.
 8152: 
 8153: @cindex selectors common to hardly-related classes
 8154: Now consider the case when you want to have a selector (or several)
 8155: available in two classes: You would have to add the selector to a
 8156: common ancestor class, in the worst case to @code{object}. You
 8157: may not want to do this, e.g., because someone else is responsible for
 8158: this ancestor class.
 8159: 
 8160: The solution for this problem is interfaces. An interface is a
 8161: collection of selectors. If a class implements an interface, the
 8162: selectors become available to the class and its descendents. A class
 8163: can implement an unlimited number of interfaces. For the problem
 8164: discussed above, we would define an interface for the selector(s), and
 8165: both classes would implement the interface.
 8166: 
 8167: As an example, consider an interface @code{storage} for
 8168: writing objects to disk and getting them back, and a class
 8169: @code{foo} that implements it. The code would look like this:
 8170: 
 8171: @cindex @code{interface} usage
 8172: @cindex @code{end-interface} usage
 8173: @cindex @code{implementation} usage
 8174: @example
 8175: interface
 8176:   selector write ( file object -- )
 8177:   selector read1 ( file object -- )
 8178: end-interface storage
 8179: 
 8180: bar class
 8181:   storage implementation
 8182: 
 8183: ... overrides write
 8184: ... overrides read1
 8185: ...
 8186: end-class foo
 8187: @end example
 8188: 
 8189: @noindent
 8190: (I would add a word @code{read} @i{( file -- object )} that uses
 8191: @code{read1} internally, but that's beyond the point illustrated
 8192: here.)
 8193: 
 8194: Note that you cannot use @code{protected} in an interface; and
 8195: of course you cannot define fields.
 8196: 
 8197: In the Neon model, all selectors are available for all classes;
 8198: therefore it does not need interfaces. The price you pay in this model
 8199: is slower late binding, and therefore, added complexity to avoid late
 8200: binding.
 8201: 
 8202: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
 8203: @subsubsection @file{objects.fs} Implementation
 8204: @cindex @file{objects.fs} implementation
 8205: 
 8206: @cindex @code{object-map} discussion
 8207: An object is a piece of memory, like one of the data structures
 8208: described with @code{struct...end-struct}. It has a field
 8209: @code{object-map} that points to the method map for the object's
 8210: class.
 8211: 
 8212: @cindex method map
 8213: @cindex virtual function table
 8214: The @emph{method map}@footnote{This is Self terminology; in C++
 8215: terminology: virtual function table.} is an array that contains the
 8216: execution tokens (@i{xt}s) of the methods for the object's class. Each
 8217: selector contains an offset into a method map.
 8218: 
 8219: @cindex @code{selector} implementation, class
 8220: @code{selector} is a defining word that uses
 8221: @code{CREATE} and @code{DOES>}. The body of the
 8222: selector contains the offset; the @code{DOES>} action for a
 8223: class selector is, basically:
 8224: 
 8225: @example
 8226: ( object addr ) @@ over object-map @@ + @@ execute
 8227: @end example
 8228: 
 8229: Since @code{object-map} is the first field of the object, it
 8230: does not generate any code. As you can see, calling a selector has a
 8231: small, constant cost.
 8232: 
 8233: @cindex @code{current-interface} discussion
 8234: @cindex class implementation and representation
 8235: A class is basically a @code{struct} combined with a method
 8236: map. During the class definition the alignment and size of the class
 8237: are passed on the stack, just as with @code{struct}s, so
 8238: @code{field} can also be used for defining class
 8239: fields. However, passing more items on the stack would be
 8240: inconvenient, so @code{class} builds a data structure in memory,
 8241: which is accessed through the variable
 8242: @code{current-interface}. After its definition is complete, the
 8243: class is represented on the stack by a pointer (e.g., as parameter for
 8244: a child class definition).
 8245: 
 8246: A new class starts off with the alignment and size of its parent,
 8247: and a copy of the parent's method map. Defining new fields extends the
 8248: size and alignment; likewise, defining new selectors extends the
 8249: method map. @code{overrides} just stores a new @i{xt} in the method
 8250: map at the offset given by the selector.
 8251: 
 8252: @cindex class binding, implementation
 8253: Class binding just gets the @i{xt} at the offset given by the selector
 8254: from the class's method map and @code{compile,}s (in the case of
 8255: @code{[bind]}) it.
 8256: 
 8257: @cindex @code{this} implementation
 8258: @cindex @code{catch} and @code{this}
 8259: @cindex @code{this} and @code{catch}
 8260: I implemented @code{this} as a @code{value}. At the
 8261: start of an @code{m:...;m} method the old @code{this} is
 8262: stored to the return stack and restored at the end; and the object on
 8263: the TOS is stored @code{TO this}. This technique has one
 8264: disadvantage: If the user does not leave the method via
 8265: @code{;m}, but via @code{throw} or @code{exit},
 8266: @code{this} is not restored (and @code{exit} may
 8267: crash). To deal with the @code{throw} problem, I have redefined
 8268: @code{catch} to save and restore @code{this}; the same
 8269: should be done with any word that can catch an exception. As for
 8270: @code{exit}, I simply forbid it (as a replacement, there is
 8271: @code{exitm}).
 8272: 
 8273: @cindex @code{inst-var} implementation
 8274: @code{inst-var} is just the same as @code{field}, with
 8275: a different @code{DOES>} action:
 8276: @example
 8277: @@ this +
 8278: @end example
 8279: Similar for @code{inst-value}.
 8280: 
 8281: @cindex class scoping implementation
 8282: Each class also has a word list that contains the words defined with
 8283: @code{inst-var} and @code{inst-value}, and its protected
 8284: words. It also has a pointer to its parent. @code{class} pushes
 8285: the word lists of the class and all its ancestors onto the search order stack,
 8286: and @code{end-class} drops them.
 8287: 
 8288: @cindex interface implementation
 8289: An interface is like a class without fields, parent and protected
 8290: words; i.e., it just has a method map. If a class implements an
 8291: interface, its method map contains a pointer to the method map of the
 8292: interface. The positive offsets in the map are reserved for class
 8293: methods, therefore interface map pointers have negative
 8294: offsets. Interfaces have offsets that are unique throughout the
 8295: system, unlike class selectors, whose offsets are only unique for the
 8296: classes where the selector is available (invokable).
 8297: 
 8298: This structure means that interface selectors have to perform one
 8299: indirection more than class selectors to find their method. Their body
 8300: contains the interface map pointer offset in the class method map, and
 8301: the method offset in the interface method map. The
 8302: @code{does>} action for an interface selector is, basically:
 8303: 
 8304: @example
 8305: ( object selector-body )
 8306: 2dup selector-interface @@ ( object selector-body object interface-offset )
 8307: swap object-map @@ + @@ ( object selector-body map )
 8308: swap selector-offset @@ + @@ execute
 8309: @end example
 8310: 
 8311: where @code{object-map} and @code{selector-offset} are
 8312: first fields and generate no code.
 8313: 
 8314: As a concrete example, consider the following code:
 8315: 
 8316: @example
 8317: interface
 8318:   selector if1sel1
 8319:   selector if1sel2
 8320: end-interface if1
 8321: 
 8322: object class
 8323:   if1 implementation
 8324:   selector cl1sel1
 8325:   cell% inst-var cl1iv1
 8326: 
 8327: ' m1 overrides construct
 8328: ' m2 overrides if1sel1
 8329: ' m3 overrides if1sel2
 8330: ' m4 overrides cl1sel2
 8331: end-class cl1
 8332: 
 8333: create obj1 object dict-new drop
 8334: create obj2 cl1    dict-new drop
 8335: @end example
 8336: 
 8337: The data structure created by this code (including the data structure
 8338: for @code{object}) is shown in the <a
 8339: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
 8340: @comment TODO add this diagram..
 8341: 
 8342: @node Objects Glossary,  , Objects Implementation, Objects
 8343: @subsubsection @file{objects.fs} Glossary
 8344: @cindex @file{objects.fs} Glossary
 8345: 
 8346: 
 8347: doc---objects-bind
 8348: doc---objects-<bind>
 8349: doc---objects-bind'
 8350: doc---objects-[bind]
 8351: doc---objects-class
 8352: doc---objects-class->map
 8353: doc---objects-class-inst-size
 8354: doc---objects-class-override!
 8355: doc---objects-construct
 8356: doc---objects-current'
 8357: doc---objects-[current]
 8358: doc---objects-current-interface
 8359: doc---objects-dict-new
 8360: doc---objects-drop-order
 8361: doc---objects-end-class
 8362: doc---objects-end-class-noname
 8363: doc---objects-end-interface
 8364: doc---objects-end-interface-noname
 8365: doc---objects-end-methods
 8366: doc---objects-exitm
 8367: doc---objects-heap-new
 8368: doc---objects-implementation
 8369: doc---objects-init-object
 8370: doc---objects-inst-value
 8371: doc---objects-inst-var
 8372: doc---objects-interface
 8373: doc---objects-m:
 8374: doc---objects-:m
 8375: doc---objects-;m
 8376: doc---objects-method
 8377: doc---objects-methods
 8378: doc---objects-object
 8379: doc---objects-overrides
 8380: doc---objects-[parent]
 8381: doc---objects-print
 8382: doc---objects-protected
 8383: doc---objects-public
 8384: doc---objects-push-order
 8385: doc---objects-selector
 8386: doc---objects-this
 8387: doc---objects-<to-inst>
 8388: doc---objects-[to-inst]
 8389: doc---objects-to-this
 8390: doc---objects-xt-new
 8391: 
 8392: 
 8393: @c -------------------------------------------------------------
 8394: @node OOF, Mini-OOF, Objects, Object-oriented Forth
 8395: @subsection The @file{oof.fs} model
 8396: @cindex oof
 8397: @cindex object-oriented programming
 8398: 
 8399: @cindex @file{objects.fs}
 8400: @cindex @file{oof.fs}
 8401: 
 8402: This section describes the @file{oof.fs} package.
 8403: 
 8404: The package described in this section has been used in bigFORTH since 1991, and
 8405: used for two large applications: a chromatographic system used to
 8406: create new medicaments, and a graphic user interface library (MINOS).
 8407: 
 8408: You can find a description (in German) of @file{oof.fs} in @cite{Object
 8409: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
 8410: 10(2), 1994.
 8411: 
 8412: @menu
 8413: * Properties of the OOF model::
 8414: * Basic OOF Usage::
 8415: * The OOF base class::
 8416: * Class Declaration::
 8417: * Class Implementation::
 8418: @end menu
 8419: 
 8420: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
 8421: @subsubsection Properties of the @file{oof.fs} model
 8422: @cindex @file{oof.fs} properties
 8423: 
 8424: @itemize @bullet
 8425: @item
 8426: This model combines object oriented programming with information
 8427: hiding. It helps you writing large application, where scoping is
 8428: necessary, because it provides class-oriented scoping.
 8429: 
 8430: @item
 8431: Named objects, object pointers, and object arrays can be created,
 8432: selector invocation uses the ``object selector'' syntax. Selector invocation
 8433: to objects and/or selectors on the stack is a bit less convenient, but
 8434: possible.
 8435: 
 8436: @item
 8437: Selector invocation and instance variable usage of the active object is
 8438: straightforward, since both make use of the active object.
 8439: 
 8440: @item
 8441: Late binding is efficient and easy to use.
 8442: 
 8443: @item
 8444: State-smart objects parse selectors. However, extensibility is provided
 8445: using a (parsing) selector @code{postpone} and a selector @code{'}.
 8446: 
 8447: @item
 8448: An implementation in ANS Forth is available.
 8449: 
 8450: @end itemize
 8451: 
 8452: 
 8453: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
 8454: @subsubsection Basic @file{oof.fs} Usage
 8455: @cindex @file{oof.fs} usage
 8456: 
 8457: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
 8458: 
 8459: You can define a class for graphical objects like this:
 8460: 
 8461: @cindex @code{class} usage
 8462: @cindex @code{class;} usage
 8463: @cindex @code{method} usage
 8464: @example
 8465: object class graphical \ "object" is the parent class
 8466:   method draw ( x y graphical -- )
 8467: class;
 8468: @end example
 8469: 
 8470: This code defines a class @code{graphical} with an
 8471: operation @code{draw}.  We can perform the operation
 8472: @code{draw} on any @code{graphical} object, e.g.:
 8473: 
 8474: @example
 8475: 100 100 t-rex draw
 8476: @end example
 8477: 
 8478: @noindent
 8479: where @code{t-rex} is an object or object pointer, created with e.g.
 8480: @code{graphical : t-rex}.
 8481: 
 8482: @cindex abstract class
 8483: How do we create a graphical object? With the present definitions,
 8484: we cannot create a useful graphical object. The class
 8485: @code{graphical} describes graphical objects in general, but not
 8486: any concrete graphical object type (C++ users would call it an
 8487: @emph{abstract class}); e.g., there is no method for the selector
 8488: @code{draw} in the class @code{graphical}.
 8489: 
 8490: For concrete graphical objects, we define child classes of the
 8491: class @code{graphical}, e.g.:
 8492: 
 8493: @example
 8494: graphical class circle \ "graphical" is the parent class
 8495:   cell var circle-radius
 8496: how:
 8497:   : draw ( x y -- )
 8498:     circle-radius @@ draw-circle ;
 8499: 
 8500:   : init ( n-radius -- (
 8501:     circle-radius ! ;
 8502: class;
 8503: @end example
 8504: 
 8505: Here we define a class @code{circle} as a child of @code{graphical},
 8506: with a field @code{circle-radius}; it defines new methods for the
 8507: selectors @code{draw} and @code{init} (@code{init} is defined in
 8508: @code{object}, the parent class of @code{graphical}).
 8509: 
 8510: Now we can create a circle in the dictionary with:
 8511: 
 8512: @example
 8513: 50 circle : my-circle
 8514: @end example
 8515: 
 8516: @noindent
 8517: @code{:} invokes @code{init}, thus initializing the field
 8518: @code{circle-radius} with 50. We can draw this new circle at (100,100)
 8519: with:
 8520: 
 8521: @example
 8522: 100 100 my-circle draw
 8523: @end example
 8524: 
 8525: @cindex selector invocation, restrictions
 8526: @cindex class definition, restrictions
 8527: Note: You can only invoke a selector if the receiving object belongs to
 8528: the class where the selector was defined or one of its descendents;
 8529: e.g., you can invoke @code{draw} only for objects belonging to
 8530: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
 8531: mechanism will check if you try to invoke a selector that is not
 8532: defined in this class hierarchy, so you'll get an error at compilation
 8533: time.
 8534: 
 8535: 
 8536: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
 8537: @subsubsection The @file{oof.fs} base class
 8538: @cindex @file{oof.fs} base class
 8539: 
 8540: When you define a class, you have to specify a parent class.  So how do
 8541: you start defining classes? There is one class available from the start:
 8542: @code{object}. You have to use it as ancestor for all classes. It is the
 8543: only class that has no parent. Classes are also objects, except that
 8544: they don't have instance variables; class manipulation such as
 8545: inheritance or changing definitions of a class is handled through
 8546: selectors of the class @code{object}.
 8547: 
 8548: @code{object} provides a number of selectors:
 8549: 
 8550: @itemize @bullet
 8551: @item
 8552: @code{class} for subclassing, @code{definitions} to add definitions
 8553: later on, and @code{class?} to get type informations (is the class a
 8554: subclass of the class passed on the stack?).
 8555: 
 8556: doc---object-class
 8557: doc---object-definitions
 8558: doc---object-class?
 8559: 
 8560: 
 8561: @item
 8562: @code{init} and @code{dispose} as constructor and destructor of the
 8563: object. @code{init} is invocated after the object's memory is allocated,
 8564: while @code{dispose} also handles deallocation. Thus if you redefine
 8565: @code{dispose}, you have to call the parent's dispose with @code{super
 8566: dispose}, too.
 8567: 
 8568: doc---object-init
 8569: doc---object-dispose
 8570: 
 8571: 
 8572: @item
 8573: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
 8574: @code{[]} to create named and unnamed objects and object arrays or
 8575: object pointers.
 8576: 
 8577: doc---object-new
 8578: doc---object-new[]
 8579: doc---object-:
 8580: doc---object-ptr
 8581: doc---object-asptr
 8582: doc---object-[]
 8583: 
 8584: 
 8585: @item
 8586: @code{::} and @code{super} for explicit scoping. You should use explicit
 8587: scoping only for super classes or classes with the same set of instance
 8588: variables. Explicitly-scoped selectors use early binding.
 8589: 
 8590: doc---object-::
 8591: doc---object-super
 8592: 
 8593: 
 8594: @item
 8595: @code{self} to get the address of the object
 8596: 
 8597: doc---object-self
 8598: 
 8599: 
 8600: @item
 8601: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
 8602: pointers and instance defers.
 8603: 
 8604: doc---object-bind
 8605: doc---object-bound
 8606: doc---object-link
 8607: doc---object-is
 8608: 
 8609: 
 8610: @item
 8611: @code{'} to obtain selector tokens, @code{send} to invocate selectors
 8612: form the stack, and @code{postpone} to generate selector invocation code.
 8613: 
 8614: doc---object-'
 8615: doc---object-postpone
 8616: 
 8617: 
 8618: @item
 8619: @code{with} and @code{endwith} to select the active object from the
 8620: stack, and enable its scope. Using @code{with} and @code{endwith}
 8621: also allows you to create code using selector @code{postpone} without being
 8622: trapped by the state-smart objects.
 8623: 
 8624: doc---object-with
 8625: doc---object-endwith
 8626: 
 8627: 
 8628: @end itemize
 8629: 
 8630: @node Class Declaration, Class Implementation, The OOF base class, OOF
 8631: @subsubsection Class Declaration
 8632: @cindex class declaration
 8633: 
 8634: @itemize @bullet
 8635: @item
 8636: Instance variables
 8637: 
 8638: doc---oof-var
 8639: 
 8640: 
 8641: @item
 8642: Object pointers
 8643: 
 8644: doc---oof-ptr
 8645: doc---oof-asptr
 8646: 
 8647: 
 8648: @item
 8649: Instance defers
 8650: 
 8651: doc---oof-defer
 8652: 
 8653: 
 8654: @item
 8655: Method selectors
 8656: 
 8657: doc---oof-early
 8658: doc---oof-method
 8659: 
 8660: 
 8661: @item
 8662: Class-wide variables
 8663: 
 8664: doc---oof-static
 8665: 
 8666: 
 8667: @item
 8668: End declaration
 8669: 
 8670: doc---oof-how:
 8671: doc---oof-class;
 8672: 
 8673: 
 8674: @end itemize
 8675: 
 8676: @c -------------------------------------------------------------
 8677: @node Class Implementation,  , Class Declaration, OOF
 8678: @subsubsection Class Implementation
 8679: @cindex class implementation
 8680: 
 8681: @c -------------------------------------------------------------
 8682: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
 8683: @subsection The @file{mini-oof.fs} model
 8684: @cindex mini-oof
 8685: 
 8686: Gforth's third object oriented Forth package is a 12-liner. It uses a
 8687: mixture of the @file{object.fs} and the @file{oof.fs} syntax,
 8688: and reduces to the bare minimum of features. This is based on a posting
 8689: of Bernd Paysan in comp.arch.
 8690: 
 8691: @menu
 8692: * Basic Mini-OOF Usage::
 8693: * Mini-OOF Example::
 8694: * Mini-OOF Implementation::
 8695: @end menu
 8696: 
 8697: @c -------------------------------------------------------------
 8698: @node Basic Mini-OOF Usage, Mini-OOF Example, , Mini-OOF
 8699: @subsubsection Basic @file{mini-oof.fs} Usage
 8700: @cindex mini-oof usage
 8701: 
 8702: There is a base class (@code{class}, which allocates one cell for the
 8703: object pointer) plus seven other words: to define a method, a variable,
 8704: a class; to end a class, to resolve binding, to allocate an object and
 8705: to compile a class method.
 8706: @comment TODO better description of the last one
 8707: 
 8708: 
 8709: doc-object
 8710: doc-method
 8711: doc-var
 8712: doc-class
 8713: doc-end-class
 8714: doc-defines
 8715: doc-new
 8716: doc-::
 8717: 
 8718: 
 8719: 
 8720: @c -------------------------------------------------------------
 8721: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
 8722: @subsubsection Mini-OOF Example
 8723: @cindex mini-oof example
 8724: 
 8725: A short example shows how to use this package. This example, in slightly
 8726: extended form, is supplied as @file{moof-exm.fs}
 8727: @comment TODO could flesh this out with some comments from the Forthwrite article
 8728: 
 8729: @example
 8730: object class
 8731:   method init
 8732:   method draw
 8733: end-class graphical
 8734: @end example
 8735: 
 8736: This code defines a class @code{graphical} with an
 8737: operation @code{draw}.  We can perform the operation
 8738: @code{draw} on any @code{graphical} object, e.g.:
 8739: 
 8740: @example
 8741: 100 100 t-rex draw
 8742: @end example
 8743: 
 8744: where @code{t-rex} is an object or object pointer, created with e.g.
 8745: @code{graphical new Constant t-rex}.
 8746: 
 8747: For concrete graphical objects, we define child classes of the
 8748: class @code{graphical}, e.g.:
 8749: 
 8750: @example
 8751: graphical class
 8752:   cell var circle-radius
 8753: end-class circle \ "graphical" is the parent class
 8754: 
 8755: :noname ( x y -- )
 8756:   circle-radius @@ draw-circle ; circle defines draw
 8757: :noname ( r -- )
 8758:   circle-radius ! ; circle defines init
 8759: @end example
 8760: 
 8761: There is no implicit init method, so we have to define one. The creation
 8762: code of the object now has to call init explicitely.
 8763: 
 8764: @example
 8765: circle new Constant my-circle
 8766: 50 my-circle init
 8767: @end example
 8768: 
 8769: It is also possible to add a function to create named objects with
 8770: automatic call of @code{init}, given that all objects have @code{init}
 8771: on the same place:
 8772: 
 8773: @example
 8774: : new: ( .. o "name" -- )
 8775:     new dup Constant init ;
 8776: 80 circle new: large-circle
 8777: @end example
 8778: 
 8779: We can draw this new circle at (100,100) with:
 8780: 
 8781: @example
 8782: 100 100 my-circle draw
 8783: @end example
 8784: 
 8785: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
 8786: @subsubsection @file{mini-oof.fs} Implementation
 8787: 
 8788: Object-oriented systems with late binding typically use a
 8789: ``vtable''-approach: the first variable in each object is a pointer to a
 8790: table, which contains the methods as function pointers. The vtable
 8791: may also contain other information.
 8792: 
 8793: So first, let's declare methods:
 8794: 
 8795: @example
 8796: : method ( m v -- m' v ) Create  over , swap cell+ swap
 8797:   DOES> ( ... o -- ... ) @ over @ + @ execute ;
 8798: @end example
 8799: 
 8800: During method declaration, the number of methods and instance
 8801: variables is on the stack (in address units). @code{method} creates
 8802: one method and increments the method number. To execute a method, it
 8803: takes the object, fetches the vtable pointer, adds the offset, and
 8804: executes the @i{xt} stored there. Each method takes the object it is
 8805: invoked from as top of stack parameter. The method itself should
 8806: consume that object.
 8807: 
 8808: Now, we also have to declare instance variables
 8809: 
 8810: @example
 8811: : var ( m v size -- m v' ) Create  over , +
 8812:   DOES> ( o -- addr ) @ + ;
 8813: @end example
 8814: 
 8815: As before, a word is created with the current offset. Instance
 8816: variables can have different sizes (cells, floats, doubles, chars), so
 8817: all we do is take the size and add it to the offset. If your machine
 8818: has alignment restrictions, put the proper @code{aligned} or
 8819: @code{faligned} before the variable, to adjust the variable
 8820: offset. That's why it is on the top of stack.
 8821: 
 8822: We need a starting point (the base object) and some syntactic sugar:
 8823: 
 8824: @example
 8825: Create object  1 cells , 2 cells ,
 8826: : class ( class -- class methods vars ) dup 2@ ;
 8827: @end example
 8828: 
 8829: For inheritance, the vtable of the parent object has to be
 8830: copied when a new, derived class is declared. This gives all the
 8831: methods of the parent class, which can be overridden, though.
 8832: 
 8833: @example
 8834: : end-class  ( class methods vars -- )
 8835:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
 8836:   cell+ dup cell+ r> rot @ 2 cells /string move ;
 8837: @end example
 8838: 
 8839: The first line creates the vtable, initialized with
 8840: @code{noop}s. The second line is the inheritance mechanism, it
 8841: copies the xts from the parent vtable.
 8842: 
 8843: We still have no way to define new methods, let's do that now:
 8844: 
 8845: @example
 8846: : defines ( xt class -- ) ' >body @ + ! ;
 8847: @end example
 8848: 
 8849: To allocate a new object, we need a word, too:
 8850: 
 8851: @example
 8852: : new ( class -- o )  here over @ allot swap over ! ;
 8853: @end example
 8854: 
 8855: Sometimes derived classes want to access the method of the
 8856: parent object. There are two ways to achieve this with Mini-OOF:
 8857: first, you could use named words, and second, you could look up the
 8858: vtable of the parent object.
 8859: 
 8860: @example
 8861: : :: ( class "name" -- ) ' >body @ + @ compile, ;
 8862: @end example
 8863: 
 8864: 
 8865: Nothing can be more confusing than a good example, so here is
 8866: one. First let's declare a text object (called
 8867: @code{button}), that stores text and position:
 8868: 
 8869: @example
 8870: object class
 8871:   cell var text
 8872:   cell var len
 8873:   cell var x
 8874:   cell var y
 8875:   method init
 8876:   method draw
 8877: end-class button
 8878: @end example
 8879: 
 8880: @noindent
 8881: Now, implement the two methods, @code{draw} and @code{init}:
 8882: 
 8883: @example
 8884: :noname ( o -- )
 8885:  >r r@ x @ r@ y @ at-xy  r@ text @ r> len @ type ;
 8886:  button defines draw
 8887: :noname ( addr u o -- )
 8888:  >r 0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
 8889:  button defines init
 8890: @end example
 8891: 
 8892: @noindent
 8893: To demonstrate inheritance, we define a class @code{bold-button}, with no
 8894: new data and no new methods:
 8895: 
 8896: @example
 8897: button class
 8898: end-class bold-button
 8899: 
 8900: : bold   27 emit ." [1m" ;
 8901: : normal 27 emit ." [0m" ;
 8902: @end example
 8903: 
 8904: @noindent
 8905: The class @code{bold-button} has a different draw method to
 8906: @code{button}, but the new method is defined in terms of the draw method
 8907: for @code{button}:
 8908: 
 8909: @example
 8910: :noname bold [ button :: draw ] normal ; bold-button defines draw
 8911: @end example
 8912: 
 8913: @noindent
 8914: Finally, create two objects and apply methods:
 8915: 
 8916: @example
 8917: button new Constant foo
 8918: s" thin foo" foo init
 8919: page
 8920: foo draw
 8921: bold-button new Constant bar
 8922: s" fat bar" bar init
 8923: 1 bar y !
 8924: bar draw
 8925: @end example
 8926: 
 8927: 
 8928: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
 8929: @subsubsection Comparison with other object models
 8930: @cindex comparison of object models
 8931: @cindex object models, comparison
 8932: 
 8933: Many object-oriented Forth extensions have been proposed (@cite{A survey
 8934: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
 8935: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
 8936: relation of the object models described here to two well-known and two
 8937: closely-related (by the use of method maps) models.
 8938: 
 8939: @cindex Neon model
 8940: The most popular model currently seems to be the Neon model (see
 8941: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
 8942: 1997) by Andrew McKewan) but this model has a number of limitations
 8943: @footnote{A longer version of this critique can be
 8944: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
 8945: Dimensions, May 1997) by Anton Ertl.}:
 8946: 
 8947: @itemize @bullet
 8948: @item
 8949: It uses a @code{@emph{selector
 8950: object}} syntax, which makes it unnatural to pass objects on the
 8951: stack.
 8952: 
 8953: @item
 8954: It requires that the selector parses the input stream (at
 8955: compile time); this leads to reduced extensibility and to bugs that are+
 8956: hard to find.
 8957: 
 8958: @item
 8959: It allows using every selector to every object;
 8960: this eliminates the need for classes, but makes it harder to create
 8961: efficient implementations. 
 8962: @end itemize
 8963: 
 8964: @cindex Pountain's object-oriented model
 8965: Another well-known publication is @cite{Object-Oriented Forth} (Academic
 8966: Press, London, 1987) by Dick Pountain. However, it is not really about
 8967: object-oriented programming, because it hardly deals with late
 8968: binding. Instead, it focuses on features like information hiding and
 8969: overloading that are characteristic of modular languages like Ada (83).
 8970: 
 8971: @cindex Zsoter's object-oriented model
 8972: In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1) 1996, pages 31-35)
 8973: Andras Zsoter describes a model that makes heavy use of an active object
 8974: (like @code{this} in @file{objects.fs}): The active object is not only
 8975: used for accessing all fields, but also specifies the receiving object
 8976: of every selector invocation; you have to change the active object
 8977: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
 8978: changes more or less implicitly at @code{m: ... ;m}. Such a change at
 8979: the method entry point is unnecessary with the Zsoter's model, because
 8980: the receiving object is the active object already. On the other hand, the explicit
 8981: change is absolutely necessary in that model, because otherwise no one
 8982: could ever change the active object. An ANS Forth implementation of this
 8983: model is available at @url{http://www.forth.org/fig/oopf.html}.
 8984: 
 8985: @cindex @file{oof.fs}, differences to other models
 8986: The @file{oof.fs} model combines information hiding and overloading
 8987: resolution (by keeping names in various word lists) with object-oriented
 8988: programming. It sets the active object implicitly on method entry, but
 8989: also allows explicit changing (with @code{>o...o>} or with
 8990: @code{with...endwith}). It uses parsing and state-smart objects and
 8991: classes for resolving overloading and for early binding: the object or
 8992: class parses the selector and determines the method from this. If the
 8993: selector is not parsed by an object or class, it performs a call to the
 8994: selector for the active object (late binding), like Zsoter's model.
 8995: Fields are always accessed through the active object. The big
 8996: disadvantage of this model is the parsing and the state-smartness, which
 8997: reduces extensibility and increases the opportunities for subtle bugs;
 8998: essentially, you are only safe if you never tick or @code{postpone} an
 8999: object or class (Bernd disagrees, but I (Anton) am not convinced).
 9000: 
 9001: @cindex @file{mini-oof.fs}, differences to other models
 9002: The @file{mini-oof.fs} model is quite similar to a very stripped-down version of
 9003: the @file{objects.fs} model, but syntactically it is a mixture of the @file{objects.fs} and
 9004: @file{oof.fs} models.
 9005: 
 9006: @c -------------------------------------------------------------
 9007: @node Passing Commands to the OS, Miscellaneous Words, Object-oriented Forth, Words
 9008: @section Passing Commands to the Operating System
 9009: @cindex operating system - passing commands
 9010: @cindex shell commands
 9011: 
 9012: Gforth allows you to pass an arbitrary string to the host operating
 9013: system shell (if such a thing exists) for execution.
 9014: 
 9015: 
 9016: doc-sh
 9017: doc-system
 9018: doc-$?
 9019: doc-getenv
 9020: 
 9021: 
 9022: @c -------------------------------------------------------------
 9023: @node Miscellaneous Words,  , Passing Commands to the OS, Words
 9024: @section Miscellaneous Words
 9025: @cindex miscellaneous words
 9026: 
 9027: @comment TODO find homes for these
 9028: 
 9029: These section lists the ANS Forth words that are not documented
 9030: elsewhere in this manual. Ultimately, they all need proper homes.
 9031: 
 9032: 
 9033: doc-ms
 9034: doc-time&date
 9035: 
 9036: 
 9037: 
 9038: doc-[compile]
 9039: 
 9040: 
 9041: The following ANS Forth words are not currently supported by Gforth 
 9042: (@pxref{ANS conformance}):
 9043: 
 9044: @code{EDITOR} 
 9045: @code{EMIT?} 
 9046: @code{FORGET} 
 9047: 
 9048: @c ******************************************************************
 9049: @node Error messages, Tools, Words, Top
 9050: @chapter Error messages
 9051: @cindex error messages
 9052: @cindex backtrace
 9053: 
 9054: A typical Gforth error message looks like this:
 9055: 
 9056: @example
 9057: in file included from :-1
 9058: in file included from ./yyy.fs:1
 9059: ./xxx.fs:4: Invalid memory address
 9060: bar
 9061: ^^^
 9062: $400E664C @@
 9063: $400E6664 foo
 9064: @end example
 9065: 
 9066: The message identifying the error is @code{Invalid memory address}.  The
 9067: error happened when text-interpreting line 4 of the file
 9068: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
 9069: word on the line where the error happened, is pointed out (with
 9070: @code{^^^}).
 9071: 
 9072: The file containing the error was included in line 1 of @file{./yyy.fs},
 9073: and @file{yyy.fs} was included from a non-file (in this case, by giving
 9074: @file{yyy.fs} as command-line parameter to Gforth).
 9075: 
 9076: At the end of the error message you find a return stack dump that can be
 9077: interpreted as a backtrace (possibly empty). On top you find the top of
 9078: the return stack when the @code{throw} happened, and at the bottom you
 9079: find the return stack entry just above the return stack of the topmost
 9080: text interpreter.
 9081: 
 9082: To the right of most return stack entries you see a guess for the word
 9083: that pushed that return stack entry as its return address. This gives a
 9084: backtrace. In our case we see that @code{bar} called @code{foo}, and
 9085: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
 9086: address} exception).
 9087: 
 9088: Note that the backtrace is not perfect: We don't know which return stack
 9089: entries are return addresses (so we may get false positives); and in
 9090: some cases (e.g., for @code{abort"}) we cannot determine from the return
 9091: address the word that pushed the return address, so for some return
 9092: addresses you see no names in the return stack dump.
 9093: 
 9094: @cindex @code{catch} and backtraces
 9095: The return stack dump represents the return stack at the time when a
 9096: specific @code{throw} was executed.  In programs that make use of
 9097: @code{catch}, it is not necessarily clear which @code{throw} should be
 9098: used for the return stack dump (e.g., consider one @code{throw} that
 9099: indicates an error, which is caught, and during recovery another error
 9100: happens; which @code{throw} should be used for the stack dump?).  Gforth
 9101: presents the return stack dump for the first @code{throw} after the last
 9102: executed (not returned-to) @code{catch}; this works well in the usual
 9103: case.
 9104: 
 9105: @cindex @code{gforth-fast} and backtraces
 9106: @cindex @code{gforth-fast}, difference from @code{gforth}
 9107: @cindex backtraces with @code{gforth-fast}
 9108: @cindex return stack dump with @code{gforth-fast}
 9109: @code{gforth} is able to do a return stack dump for throws generated
 9110: from primitives (e.g., invalid memory address, stack empty etc.);
 9111: @code{gforth-fast} is only able to do a return stack dump from a
 9112: directly called @code{throw} (including @code{abort} etc.).  This is the
 9113: only difference (apart from a speed factor of between 1.15 (K6-2) and
 9114: 1.6 (21164A)) between @code{gforth} and @code{gforth-fast}.  Given an
 9115: exception caused by a primitive in @code{gforth-fast}, you will
 9116: typically see no return stack dump at all; however, if the exception is
 9117: caught by @code{catch} (e.g., for restoring some state), and then
 9118: @code{throw}n again, the return stack dump will be for the first such
 9119: @code{throw}.
 9120: 
 9121: @c ******************************************************************
 9122: @node Tools, ANS conformance, Error messages, Top
 9123: @chapter Tools
 9124: 
 9125: @menu
 9126: * ANS Report::                  Report the words used, sorted by wordset.
 9127: @end menu
 9128: 
 9129: See also @ref{Emacs and Gforth}.
 9130: 
 9131: @node ANS Report,  , Tools, Tools
 9132: @section @file{ans-report.fs}: Report the words used, sorted by wordset
 9133: @cindex @file{ans-report.fs}
 9134: @cindex report the words used in your program
 9135: @cindex words used in your program
 9136: 
 9137: If you want to label a Forth program as ANS Forth Program, you must
 9138: document which wordsets the program uses; for extension wordsets, it is
 9139: helpful to list the words the program requires from these wordsets
 9140: (because Forth systems are allowed to provide only some words of them).
 9141: 
 9142: The @file{ans-report.fs} tool makes it easy for you to determine which
 9143: words from which wordset and which non-ANS words your application
 9144: uses. You simply have to include @file{ans-report.fs} before loading the
 9145: program you want to check. After loading your program, you can get the
 9146: report with @code{print-ans-report}. A typical use is to run this as
 9147: batch job like this:
 9148: @example
 9149: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
 9150: @end example
 9151: 
 9152: The output looks like this (for @file{compat/control.fs}):
 9153: @example
 9154: The program uses the following words
 9155: from CORE :
 9156: : POSTPONE THEN ; immediate ?dup IF 0= 
 9157: from BLOCK-EXT :
 9158: \ 
 9159: from FILE :
 9160: ( 
 9161: @end example
 9162: 
 9163: @subsection Caveats
 9164: 
 9165: Note that @file{ans-report.fs} just checks which words are used, not whether
 9166: they are used in an ANS Forth conforming way!
 9167: 
 9168: Some words are defined in several wordsets in the
 9169: standard. @file{ans-report.fs} reports them for only one of the
 9170: wordsets, and not necessarily the one you expect. It depends on usage
 9171: which wordset is the right one to specify. E.g., if you only use the
 9172: compilation semantics of @code{S"}, it is a Core word; if you also use
 9173: its interpretation semantics, it is a File word.
 9174: 
 9175: @c ******************************************************************
 9176: @node ANS conformance, Model, Tools, Top
 9177: @chapter ANS conformance
 9178: @cindex ANS conformance of Gforth
 9179: 
 9180: To the best of our knowledge, Gforth is an
 9181: 
 9182: ANS Forth System
 9183: @itemize @bullet
 9184: @item providing the Core Extensions word set
 9185: @item providing the Block word set
 9186: @item providing the Block Extensions word set
 9187: @item providing the Double-Number word set
 9188: @item providing the Double-Number Extensions word set
 9189: @item providing the Exception word set
 9190: @item providing the Exception Extensions word set
 9191: @item providing the Facility word set
 9192: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
 9193: @item providing the File Access word set
 9194: @item providing the File Access Extensions word set
 9195: @item providing the Floating-Point word set
 9196: @item providing the Floating-Point Extensions word set
 9197: @item providing the Locals word set
 9198: @item providing the Locals Extensions word set
 9199: @item providing the Memory-Allocation word set
 9200: @item providing the Memory-Allocation Extensions word set (that one's easy)
 9201: @item providing the Programming-Tools word set
 9202: @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
 9203: @item providing the Search-Order word set
 9204: @item providing the Search-Order Extensions word set
 9205: @item providing the String word set
 9206: @item providing the String Extensions word set (another easy one)
 9207: @end itemize
 9208: 
 9209: @cindex system documentation
 9210: In addition, ANS Forth systems are required to document certain
 9211: implementation choices. This chapter tries to meet these
 9212: requirements. In many cases it gives a way to ask the system for the
 9213: information instead of providing the information directly, in
 9214: particular, if the information depends on the processor, the operating
 9215: system or the installation options chosen, or if they are likely to
 9216: change during the maintenance of Gforth.
 9217: 
 9218: @comment The framework for the rest has been taken from pfe.
 9219: 
 9220: @menu
 9221: * The Core Words::              
 9222: * The optional Block word set::  
 9223: * The optional Double Number word set::  
 9224: * The optional Exception word set::  
 9225: * The optional Facility word set::  
 9226: * The optional File-Access word set::  
 9227: * The optional Floating-Point word set::  
 9228: * The optional Locals word set::  
 9229: * The optional Memory-Allocation word set::  
 9230: * The optional Programming-Tools word set::  
 9231: * The optional Search-Order word set::  
 9232: @end menu
 9233: 
 9234: 
 9235: @c =====================================================================
 9236: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
 9237: @comment  node-name,  next,  previous,  up
 9238: @section The Core Words
 9239: @c =====================================================================
 9240: @cindex core words, system documentation
 9241: @cindex system documentation, core words
 9242: 
 9243: @menu
 9244: * core-idef::                   Implementation Defined Options                   
 9245: * core-ambcond::                Ambiguous Conditions                
 9246: * core-other::                  Other System Documentation                  
 9247: @end menu
 9248: 
 9249: @c ---------------------------------------------------------------------
 9250: @node core-idef, core-ambcond, The Core Words, The Core Words
 9251: @subsection Implementation Defined Options
 9252: @c ---------------------------------------------------------------------
 9253: @cindex core words, implementation-defined options
 9254: @cindex implementation-defined options, core words
 9255: 
 9256: 
 9257: @table @i
 9258: @item (Cell) aligned addresses:
 9259: @cindex cell-aligned addresses
 9260: @cindex aligned addresses
 9261: processor-dependent. Gforth's alignment words perform natural alignment
 9262: (e.g., an address aligned for a datum of size 8 is divisible by
 9263: 8). Unaligned accesses usually result in a @code{-23 THROW}.
 9264: 
 9265: @item @code{EMIT} and non-graphic characters:
 9266: @cindex @code{EMIT} and non-graphic characters
 9267: @cindex non-graphic characters and @code{EMIT}
 9268: The character is output using the C library function (actually, macro)
 9269: @code{putc}.
 9270: 
 9271: @item character editing of @code{ACCEPT} and @code{EXPECT}:
 9272: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
 9273: @cindex editing in @code{ACCEPT} and @code{EXPECT}
 9274: @cindex @code{ACCEPT}, editing
 9275: @cindex @code{EXPECT}, editing
 9276: This is modeled on the GNU readline library (@pxref{Readline
 9277: Interaction, , Command Line Editing, readline, The GNU Readline
 9278: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
 9279: producing a full word completion every time you type it (instead of
 9280: producing the common prefix of all completions). @xref{Command-line editing}.
 9281: 
 9282: @item character set:
 9283: @cindex character set
 9284: The character set of your computer and display device. Gforth is
 9285: 8-bit-clean (but some other component in your system may make trouble).
 9286: 
 9287: @item Character-aligned address requirements:
 9288: @cindex character-aligned address requirements
 9289: installation-dependent. Currently a character is represented by a C
 9290: @code{unsigned char}; in the future we might switch to @code{wchar_t}
 9291: (Comments on that requested).
 9292: 
 9293: @item character-set extensions and matching of names:
 9294: @cindex character-set extensions and matching of names
 9295: @cindex case-sensitivity for name lookup
 9296: @cindex name lookup, case-sensitivity
 9297: @cindex locale and case-sensitivity
 9298: Any character except the ASCII NUL character can be used in a
 9299: name. Matching is case-insensitive (except in @code{TABLE}s). The
 9300: matching is performed using the C function @code{strncasecmp}, whose
 9301: function is probably influenced by the locale. E.g., the @code{C} locale
 9302: does not know about accents and umlauts, so they are matched
 9303: case-sensitively in that locale. For portability reasons it is best to
 9304: write programs such that they work in the @code{C} locale. Then one can
 9305: use libraries written by a Polish programmer (who might use words
 9306: containing ISO Latin-2 encoded characters) and by a French programmer
 9307: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
 9308: funny results for some of the words (which ones, depends on the font you
 9309: are using)). Also, the locale you prefer may not be available in other
 9310: operating systems. Hopefully, Unicode will solve these problems one day.
 9311: 
 9312: @item conditions under which control characters match a space delimiter:
 9313: @cindex space delimiters
 9314: @cindex control characters as delimiters
 9315: If @code{WORD} is called with the space character as a delimiter, all
 9316: white-space characters (as identified by the C macro @code{isspace()})
 9317: are delimiters. @code{PARSE}, on the other hand, treats space like other
 9318: delimiters. @code{SWORD} treats space like @code{WORD}, but behaves
 9319: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
 9320: interpreter (aka text interpreter) by default, treats all white-space
 9321: characters as delimiters.
 9322: 
 9323: @item format of the control-flow stack:
 9324: @cindex control-flow stack, format
 9325: The data stack is used as control-flow stack. The size of a control-flow
 9326: stack item in cells is given by the constant @code{cs-item-size}. At the
 9327: time of this writing, an item consists of a (pointer to a) locals list
 9328: (third), an address in the code (second), and a tag for identifying the
 9329: item (TOS). The following tags are used: @code{defstart},
 9330: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
 9331: @code{scopestart}.
 9332: 
 9333: @item conversion of digits > 35
 9334: @cindex digits > 35
 9335: The characters @code{[\]^_'} are the digits with the decimal value
 9336: 36@minus{}41. There is no way to input many of the larger digits.
 9337: 
 9338: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
 9339: @cindex @code{EXPECT}, display after end of input
 9340: @cindex @code{ACCEPT}, display after end of input
 9341: The cursor is moved to the end of the entered string. If the input is
 9342: terminated using the @kbd{Return} key, a space is typed.
 9343: 
 9344: @item exception abort sequence of @code{ABORT"}:
 9345: @cindex exception abort sequence of @code{ABORT"}
 9346: @cindex @code{ABORT"}, exception abort sequence
 9347: The error string is stored into the variable @code{"error} and a
 9348: @code{-2 throw} is performed.
 9349: 
 9350: @item input line terminator:
 9351: @cindex input line terminator
 9352: @cindex line terminator on input
 9353: @cindex newline character on input
 9354: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
 9355: lines. One of these characters is typically produced when you type the
 9356: @kbd{Enter} or @kbd{Return} key.
 9357: 
 9358: @item maximum size of a counted string:
 9359: @cindex maximum size of a counted string
 9360: @cindex counted string, maximum size
 9361: @code{s" /counted-string" environment? drop .}. Currently 255 characters
 9362: on all ports, but this may change.
 9363: 
 9364: @item maximum size of a parsed string:
 9365: @cindex maximum size of a parsed string
 9366: @cindex parsed string, maximum size
 9367: Given by the constant @code{/line}. Currently 255 characters.
 9368: 
 9369: @item maximum size of a definition name, in characters:
 9370: @cindex maximum size of a definition name, in characters
 9371: @cindex name, maximum length
 9372: 31
 9373: 
 9374: @item maximum string length for @code{ENVIRONMENT?}, in characters:
 9375: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
 9376: @cindex @code{ENVIRONMENT?} string length, maximum
 9377: 31
 9378: 
 9379: @item method of selecting the user input device:
 9380: @cindex user input device, method of selecting
 9381: The user input device is the standard input. There is currently no way to
 9382: change it from within Gforth. However, the input can typically be
 9383: redirected in the command line that starts Gforth.
 9384: 
 9385: @item method of selecting the user output device:
 9386: @cindex user output device, method of selecting
 9387: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
 9388: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
 9389: output when the user output device is a terminal, otherwise the output
 9390: is buffered.
 9391: 
 9392: @item methods of dictionary compilation:
 9393: What are we expected to document here?
 9394: 
 9395: @item number of bits in one address unit:
 9396: @cindex number of bits in one address unit
 9397: @cindex address unit, size in bits
 9398: @code{s" address-units-bits" environment? drop .}. 8 in all current
 9399: ports.
 9400: 
 9401: @item number representation and arithmetic:
 9402: @cindex number representation and arithmetic
 9403: Processor-dependent. Binary two's complement on all current ports.
 9404: 
 9405: @item ranges for integer types:
 9406: @cindex ranges for integer types
 9407: @cindex integer types, ranges
 9408: Installation-dependent. Make environmental queries for @code{MAX-N},
 9409: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
 9410: unsigned (and positive) types is 0. The lower bound for signed types on
 9411: two's complement and one's complement machines machines can be computed
 9412: by adding 1 to the upper bound.
 9413: 
 9414: @item read-only data space regions:
 9415: @cindex read-only data space regions
 9416: @cindex data-space, read-only regions
 9417: The whole Forth data space is writable.
 9418: 
 9419: @item size of buffer at @code{WORD}:
 9420: @cindex size of buffer at @code{WORD}
 9421: @cindex @code{WORD} buffer size
 9422: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
 9423: shared with the pictured numeric output string. If overwriting
 9424: @code{PAD} is acceptable, it is as large as the remaining dictionary
 9425: space, although only as much can be sensibly used as fits in a counted
 9426: string.
 9427: 
 9428: @item size of one cell in address units:
 9429: @cindex cell size
 9430: @code{1 cells .}.
 9431: 
 9432: @item size of one character in address units:
 9433: @cindex char size
 9434: @code{1 chars .}. 1 on all current ports.
 9435: 
 9436: @item size of the keyboard terminal buffer:
 9437: @cindex size of the keyboard terminal buffer
 9438: @cindex terminal buffer, size
 9439: Varies. You can determine the size at a specific time using @code{lp@@
 9440: tib - .}. It is shared with the locals stack and TIBs of files that
 9441: include the current file. You can change the amount of space for TIBs
 9442: and locals stack at Gforth startup with the command line option
 9443: @code{-l}.
 9444: 
 9445: @item size of the pictured numeric output buffer:
 9446: @cindex size of the pictured numeric output buffer
 9447: @cindex pictured numeric output buffer, size
 9448: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
 9449: shared with @code{WORD}.
 9450: 
 9451: @item size of the scratch area returned by @code{PAD}:
 9452: @cindex size of the scratch area returned by @code{PAD}
 9453: @cindex @code{PAD} size
 9454: The remainder of dictionary space. @code{unused pad here - - .}.
 9455: 
 9456: @item system case-sensitivity characteristics:
 9457: @cindex case-sensitivity characteristics
 9458: Dictionary searches are case-insensitive (except in
 9459: @code{TABLE}s). However, as explained above under @i{character-set
 9460: extensions}, the matching for non-ASCII characters is determined by the
 9461: locale you are using. In the default @code{C} locale all non-ASCII
 9462: characters are matched case-sensitively.
 9463: 
 9464: @item system prompt:
 9465: @cindex system prompt
 9466: @cindex prompt
 9467: @code{ ok} in interpret state, @code{ compiled} in compile state.
 9468: 
 9469: @item division rounding:
 9470: @cindex division rounding
 9471: installation dependent. @code{s" floored" environment? drop .}. We leave
 9472: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
 9473: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
 9474: 
 9475: @item values of @code{STATE} when true:
 9476: @cindex @code{STATE} values
 9477: -1.
 9478: 
 9479: @item values returned after arithmetic overflow:
 9480: On two's complement machines, arithmetic is performed modulo
 9481: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
 9482: arithmetic (with appropriate mapping for signed types). Division by zero
 9483: typically results in a @code{-55 throw} (Floating-point unidentified
 9484: fault), although a @code{-10 throw} (divide by zero) would be more
 9485: appropriate.
 9486: 
 9487: @item whether the current definition can be found after @t{DOES>}:
 9488: @cindex @t{DOES>}, visibility of current definition
 9489: No.
 9490: 
 9491: @end table
 9492: 
 9493: @c ---------------------------------------------------------------------
 9494: @node core-ambcond, core-other, core-idef, The Core Words
 9495: @subsection Ambiguous conditions
 9496: @c ---------------------------------------------------------------------
 9497: @cindex core words, ambiguous conditions
 9498: @cindex ambiguous conditions, core words
 9499: 
 9500: @table @i
 9501: 
 9502: @item a name is neither a word nor a number:
 9503: @cindex name not found
 9504: @cindex undefined word
 9505: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
 9506: preserves the data and FP stack, so you don't lose more work than
 9507: necessary.
 9508: 
 9509: @item a definition name exceeds the maximum length allowed:
 9510: @cindex word name too long
 9511: @code{-19 throw} (Word name too long)
 9512: 
 9513: @item addressing a region not inside the various data spaces of the forth system:
 9514: @cindex Invalid memory address
 9515: The stacks, code space and header space are accessible. Machine code space is
 9516: typically readable. Accessing other addresses gives results dependent on
 9517: the operating system. On decent systems: @code{-9 throw} (Invalid memory
 9518: address).
 9519: 
 9520: @item argument type incompatible with parameter:
 9521: @cindex argument type mismatch
 9522: This is usually not caught. Some words perform checks, e.g., the control
 9523: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
 9524: mismatch).
 9525: 
 9526: @item attempting to obtain the execution token of a word with undefined execution semantics:
 9527: @cindex Interpreting a compile-only word, for @code{'} etc.
 9528: @cindex execution token of words with undefined execution semantics
 9529: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
 9530: get an execution token for @code{compile-only-error} (which performs a
 9531: @code{-14 throw} when executed).
 9532: 
 9533: @item dividing by zero:
 9534: @cindex dividing by zero
 9535: @cindex floating point unidentified fault, integer division
 9536: On better platforms, this produces a @code{-10 throw} (Division by
 9537: zero); on other systems, this typically results in a @code{-55 throw}
 9538: (Floating-point unidentified fault).
 9539: 
 9540: @item insufficient data stack or return stack space:
 9541: @cindex insufficient data stack or return stack space
 9542: @cindex stack overflow
 9543: @cindex address alignment exception, stack overflow
 9544: @cindex Invalid memory address, stack overflow
 9545: Depending on the operating system, the installation, and the invocation
 9546: of Gforth, this is either checked by the memory management hardware, or
 9547: it is not checked. If it is checked, you typically get a @code{-3 throw}
 9548: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
 9549: throw} (Invalid memory address) (depending on the platform and how you
 9550: achieved the overflow) as soon as the overflow happens. If it is not
 9551: checked, overflows typically result in mysterious illegal memory
 9552: accesses, producing @code{-9 throw} (Invalid memory address) or
 9553: @code{-23 throw} (Address alignment exception); they might also destroy
 9554: the internal data structure of @code{ALLOCATE} and friends, resulting in
 9555: various errors in these words.
 9556: 
 9557: @item insufficient space for loop control parameters:
 9558: @cindex insufficient space for loop control parameters
 9559: like other return stack overflows.
 9560: 
 9561: @item insufficient space in the dictionary:
 9562: @cindex insufficient space in the dictionary
 9563: @cindex dictionary overflow
 9564: If you try to allot (either directly with @code{allot}, or indirectly
 9565: with @code{,}, @code{create} etc.) more memory than available in the
 9566: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
 9567: to access memory beyond the end of the dictionary, the results are
 9568: similar to stack overflows.
 9569: 
 9570: @item interpreting a word with undefined interpretation semantics:
 9571: @cindex interpreting a word with undefined interpretation semantics
 9572: @cindex Interpreting a compile-only word
 9573: For some words, we have defined interpretation semantics. For the
 9574: others: @code{-14 throw} (Interpreting a compile-only word).
 9575: 
 9576: @item modifying the contents of the input buffer or a string literal:
 9577: @cindex modifying the contents of the input buffer or a string literal
 9578: These are located in writable memory and can be modified.
 9579: 
 9580: @item overflow of the pictured numeric output string:
 9581: @cindex overflow of the pictured numeric output string
 9582: @cindex pictured numeric output string, overflow
 9583: @code{-17 throw} (Pictured numeric ouput string overflow).
 9584: 
 9585: @item parsed string overflow:
 9586: @cindex parsed string overflow
 9587: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
 9588: 
 9589: @item producing a result out of range:
 9590: @cindex result out of range
 9591: On two's complement machines, arithmetic is performed modulo
 9592: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
 9593: arithmetic (with appropriate mapping for signed types). Division by zero
 9594: typically results in a @code{-10 throw} (divide by zero) or @code{-55
 9595: throw} (floating point unidentified fault). @code{convert} and
 9596: @code{>number} currently overflow silently.
 9597: 
 9598: @item reading from an empty data or return stack:
 9599: @cindex stack empty
 9600: @cindex stack underflow
 9601: @cindex return stack underflow
 9602: The data stack is checked by the outer (aka text) interpreter after
 9603: every word executed. If it has underflowed, a @code{-4 throw} (Stack
 9604: underflow) is performed. Apart from that, stacks may be checked or not,
 9605: depending on operating system, installation, and invocation. If they are
 9606: caught by a check, they typically result in @code{-4 throw} (Stack
 9607: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
 9608: (Invalid memory address), depending on the platform and which stack
 9609: underflows and by how much. Note that even if the system uses checking
 9610: (through the MMU), your program may have to underflow by a significant
 9611: number of stack items to trigger the reaction (the reason for this is
 9612: that the MMU, and therefore the checking, works with a page-size
 9613: granularity).  If there is no checking, the symptoms resulting from an
 9614: underflow are similar to those from an overflow.  Unbalanced return
 9615: stack errors result in a variaty of symptoms, including @code{-9 throw}
 9616: (Invalid memory address) and Illegal Instruction (typically @code{-260
 9617: throw}).
 9618: 
 9619: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
 9620: @cindex unexpected end of the input buffer
 9621: @cindex zero-length string as a name
 9622: @cindex Attempt to use zero-length string as a name
 9623: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
 9624: use zero-length string as a name). Words like @code{'} probably will not
 9625: find what they search. Note that it is possible to create zero-length
 9626: names with @code{nextname} (should it not?).
 9627: 
 9628: @item @code{>IN} greater than input buffer:
 9629: @cindex @code{>IN} greater than input buffer
 9630: The next invocation of a parsing word returns a string with length 0.
 9631: 
 9632: @item @code{RECURSE} appears after @code{DOES>}:
 9633: @cindex @code{RECURSE} appears after @code{DOES>}
 9634: Compiles a recursive call to the defining word, not to the defined word.
 9635: 
 9636: @item argument input source different than current input source for @code{RESTORE-INPUT}:
 9637: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
 9638: @cindex argument type mismatch, @code{RESTORE-INPUT}
 9639: @cindex @code{RESTORE-INPUT}, Argument type mismatch
 9640: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
 9641: the end of the file was reached), its source-id may be
 9642: reused. Therefore, restoring an input source specification referencing a
 9643: closed file may lead to unpredictable results instead of a @code{-12
 9644: THROW}.
 9645: 
 9646: In the future, Gforth may be able to restore input source specifications
 9647: from other than the current input source.
 9648: 
 9649: @item data space containing definitions gets de-allocated:
 9650: @cindex data space containing definitions gets de-allocated
 9651: Deallocation with @code{allot} is not checked. This typically results in
 9652: memory access faults or execution of illegal instructions.
 9653: 
 9654: @item data space read/write with incorrect alignment:
 9655: @cindex data space read/write with incorrect alignment
 9656: @cindex alignment faults
 9657: @cindex address alignment exception
 9658: Processor-dependent. Typically results in a @code{-23 throw} (Address
 9659: alignment exception). Under Linux-Intel on a 486 or later processor with
 9660: alignment turned on, incorrect alignment results in a @code{-9 throw}
 9661: (Invalid memory address). There are reportedly some processors with
 9662: alignment restrictions that do not report violations.
 9663: 
 9664: @item data space pointer not properly aligned, @code{,}, @code{C,}:
 9665: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
 9666: Like other alignment errors.
 9667: 
 9668: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
 9669: Like other stack underflows.
 9670: 
 9671: @item loop control parameters not available:
 9672: @cindex loop control parameters not available
 9673: Not checked. The counted loop words simply assume that the top of return
 9674: stack items are loop control parameters and behave accordingly.
 9675: 
 9676: @item most recent definition does not have a name (@code{IMMEDIATE}):
 9677: @cindex most recent definition does not have a name (@code{IMMEDIATE})
 9678: @cindex last word was headerless
 9679: @code{abort" last word was headerless"}.
 9680: 
 9681: @item name not defined by @code{VALUE} used by @code{TO}:
 9682: @cindex name not defined by @code{VALUE} used by @code{TO}
 9683: @cindex @code{TO} on non-@code{VALUE}s
 9684: @cindex Invalid name argument, @code{TO}
 9685: @code{-32 throw} (Invalid name argument) (unless name is a local or was
 9686: defined by @code{CONSTANT}; in the latter case it just changes the constant).
 9687: 
 9688: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
 9689: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
 9690: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
 9691: @code{-13 throw} (Undefined word)
 9692: 
 9693: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
 9694: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
 9695: Gforth behaves as if they were of the same type. I.e., you can predict
 9696: the behaviour by interpreting all parameters as, e.g., signed.
 9697: 
 9698: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
 9699: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
 9700: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
 9701: compilation semantics of @code{TO}.
 9702: 
 9703: @item String longer than a counted string returned by @code{WORD}:
 9704: @cindex string longer than a counted string returned by @code{WORD}
 9705: @cindex @code{WORD}, string overflow
 9706: Not checked. The string will be ok, but the count will, of course,
 9707: contain only the least significant bits of the length.
 9708: 
 9709: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
 9710: @cindex @code{LSHIFT}, large shift counts
 9711: @cindex @code{RSHIFT}, large shift counts
 9712: Processor-dependent. Typical behaviours are returning 0 and using only
 9713: the low bits of the shift count.
 9714: 
 9715: @item word not defined via @code{CREATE}:
 9716: @cindex @code{>BODY} of non-@code{CREATE}d words
 9717: @code{>BODY} produces the PFA of the word no matter how it was defined.
 9718: 
 9719: @cindex @code{DOES>} of non-@code{CREATE}d words
 9720: @code{DOES>} changes the execution semantics of the last defined word no
 9721: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
 9722: @code{CREATE , DOES>}.
 9723: 
 9724: @item words improperly used outside @code{<#} and @code{#>}:
 9725: Not checked. As usual, you can expect memory faults.
 9726: 
 9727: @end table
 9728: 
 9729: 
 9730: @c ---------------------------------------------------------------------
 9731: @node core-other,  , core-ambcond, The Core Words
 9732: @subsection Other system documentation
 9733: @c ---------------------------------------------------------------------
 9734: @cindex other system documentation, core words
 9735: @cindex core words, other system documentation
 9736: 
 9737: @table @i
 9738: @item nonstandard words using @code{PAD}:
 9739: @cindex @code{PAD} use by nonstandard words
 9740: None.
 9741: 
 9742: @item operator's terminal facilities available:
 9743: @cindex operator's terminal facilities available
 9744: After processing the command line, Gforth goes into interactive mode,
 9745: and you can give commands to Gforth interactively. The actual facilities
 9746: available depend on how you invoke Gforth.
 9747: 
 9748: @item program data space available:
 9749: @cindex program data space available
 9750: @cindex data space available
 9751: @code{UNUSED .} gives the remaining dictionary space. The total
 9752: dictionary space can be specified with the @code{-m} switch
 9753: (@pxref{Invoking Gforth}) when Gforth starts up.
 9754: 
 9755: @item return stack space available:
 9756: @cindex return stack space available
 9757: You can compute the total return stack space in cells with
 9758: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
 9759: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
 9760: 
 9761: @item stack space available:
 9762: @cindex stack space available
 9763: You can compute the total data stack space in cells with
 9764: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
 9765: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
 9766: 
 9767: @item system dictionary space required, in address units:
 9768: @cindex system dictionary space required, in address units
 9769: Type @code{here forthstart - .} after startup. At the time of this
 9770: writing, this gives 80080 (bytes) on a 32-bit system.
 9771: @end table
 9772: 
 9773: 
 9774: @c =====================================================================
 9775: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
 9776: @section The optional Block word set
 9777: @c =====================================================================
 9778: @cindex system documentation, block words
 9779: @cindex block words, system documentation
 9780: 
 9781: @menu
 9782: * block-idef::                  Implementation Defined Options
 9783: * block-ambcond::               Ambiguous Conditions               
 9784: * block-other::                 Other System Documentation                 
 9785: @end menu
 9786: 
 9787: 
 9788: @c ---------------------------------------------------------------------
 9789: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
 9790: @subsection Implementation Defined Options
 9791: @c ---------------------------------------------------------------------
 9792: @cindex implementation-defined options, block words
 9793: @cindex block words, implementation-defined options
 9794: 
 9795: @table @i
 9796: @item the format for display by @code{LIST}:
 9797: @cindex @code{LIST} display format
 9798: First the screen number is displayed, then 16 lines of 64 characters,
 9799: each line preceded by the line number.
 9800: 
 9801: @item the length of a line affected by @code{\}:
 9802: @cindex length of a line affected by @code{\}
 9803: @cindex @code{\}, line length in blocks
 9804: 64 characters.
 9805: @end table
 9806: 
 9807: 
 9808: @c ---------------------------------------------------------------------
 9809: @node block-ambcond, block-other, block-idef, The optional Block word set
 9810: @subsection Ambiguous conditions
 9811: @c ---------------------------------------------------------------------
 9812: @cindex block words, ambiguous conditions
 9813: @cindex ambiguous conditions, block words
 9814: 
 9815: @table @i
 9816: @item correct block read was not possible:
 9817: @cindex block read not possible
 9818: Typically results in a @code{throw} of some OS-derived value (between
 9819: -512 and -2048). If the blocks file was just not long enough, blanks are
 9820: supplied for the missing portion.
 9821: 
 9822: @item I/O exception in block transfer:
 9823: @cindex I/O exception in block transfer
 9824: @cindex block transfer, I/O exception
 9825: Typically results in a @code{throw} of some OS-derived value (between
 9826: -512 and -2048).
 9827: 
 9828: @item invalid block number:
 9829: @cindex invalid block number
 9830: @cindex block number invalid
 9831: @code{-35 throw} (Invalid block number)
 9832: 
 9833: @item a program directly alters the contents of @code{BLK}:
 9834: @cindex @code{BLK}, altering @code{BLK}
 9835: The input stream is switched to that other block, at the same
 9836: position. If the storing to @code{BLK} happens when interpreting
 9837: non-block input, the system will get quite confused when the block ends.
 9838: 
 9839: @item no current block buffer for @code{UPDATE}:
 9840: @cindex @code{UPDATE}, no current block buffer
 9841: @code{UPDATE} has no effect.
 9842: 
 9843: @end table
 9844: 
 9845: @c ---------------------------------------------------------------------
 9846: @node block-other,  , block-ambcond, The optional Block word set
 9847: @subsection Other system documentation
 9848: @c ---------------------------------------------------------------------
 9849: @cindex other system documentation, block words
 9850: @cindex block words, other system documentation
 9851: 
 9852: @table @i
 9853: @item any restrictions a multiprogramming system places on the use of buffer addresses:
 9854: No restrictions (yet).
 9855: 
 9856: @item the number of blocks available for source and data:
 9857: depends on your disk space.
 9858: 
 9859: @end table
 9860: 
 9861: 
 9862: @c =====================================================================
 9863: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
 9864: @section The optional Double Number word set
 9865: @c =====================================================================
 9866: @cindex system documentation, double words
 9867: @cindex double words, system documentation
 9868: 
 9869: @menu
 9870: * double-ambcond::              Ambiguous Conditions              
 9871: @end menu
 9872: 
 9873: 
 9874: @c ---------------------------------------------------------------------
 9875: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
 9876: @subsection Ambiguous conditions
 9877: @c ---------------------------------------------------------------------
 9878: @cindex double words, ambiguous conditions
 9879: @cindex ambiguous conditions, double words
 9880: 
 9881: @table @i
 9882: @item @i{d} outside of range of @i{n} in @code{D>S}:
 9883: @cindex @code{D>S}, @i{d} out of range of @i{n} 
 9884: The least significant cell of @i{d} is produced.
 9885: 
 9886: @end table
 9887: 
 9888: 
 9889: @c =====================================================================
 9890: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
 9891: @section The optional Exception word set
 9892: @c =====================================================================
 9893: @cindex system documentation, exception words
 9894: @cindex exception words, system documentation
 9895: 
 9896: @menu
 9897: * exception-idef::              Implementation Defined Options              
 9898: @end menu
 9899: 
 9900: 
 9901: @c ---------------------------------------------------------------------
 9902: @node exception-idef,  , The optional Exception word set, The optional Exception word set
 9903: @subsection Implementation Defined Options
 9904: @c ---------------------------------------------------------------------
 9905: @cindex implementation-defined options, exception words
 9906: @cindex exception words, implementation-defined options
 9907: 
 9908: @table @i
 9909: @item @code{THROW}-codes used in the system:
 9910: @cindex @code{THROW}-codes used in the system
 9911: The codes -256@minus{}-511 are used for reporting signals. The mapping
 9912: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
 9913: codes -512@minus{}-2047 are used for OS errors (for file and memory
 9914: allocation operations). The mapping from OS error numbers to throw codes
 9915: is -512@minus{}@code{errno}. One side effect of this mapping is that
 9916: undefined OS errors produce a message with a strange number; e.g.,
 9917: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
 9918: @end table
 9919: 
 9920: @c =====================================================================
 9921: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
 9922: @section The optional Facility word set
 9923: @c =====================================================================
 9924: @cindex system documentation, facility words
 9925: @cindex facility words, system documentation
 9926: 
 9927: @menu
 9928: * facility-idef::               Implementation Defined Options               
 9929: * facility-ambcond::            Ambiguous Conditions            
 9930: @end menu
 9931: 
 9932: 
 9933: @c ---------------------------------------------------------------------
 9934: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
 9935: @subsection Implementation Defined Options
 9936: @c ---------------------------------------------------------------------
 9937: @cindex implementation-defined options, facility words
 9938: @cindex facility words, implementation-defined options
 9939: 
 9940: @table @i
 9941: @item encoding of keyboard events (@code{EKEY}):
 9942: @cindex keyboard events, encoding in @code{EKEY}
 9943: @cindex @code{EKEY}, encoding of keyboard events
 9944: Keys corresponding to ASCII characters are encoded as ASCII characters.
 9945: Other keys are encoded with the constants @code{k-left}, @code{k-right},
 9946: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
 9947: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
 9948: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
 9949: 
 9950: 
 9951: @item duration of a system clock tick:
 9952: @cindex duration of a system clock tick
 9953: @cindex clock tick duration
 9954: System dependent. With respect to @code{MS}, the time is specified in
 9955: microseconds. How well the OS and the hardware implement this, is
 9956: another question.
 9957: 
 9958: @item repeatability to be expected from the execution of @code{MS}:
 9959: @cindex repeatability to be expected from the execution of @code{MS}
 9960: @cindex @code{MS}, repeatability to be expected
 9961: System dependent. On Unix, a lot depends on load. If the system is
 9962: lightly loaded, and the delay is short enough that Gforth does not get
 9963: swapped out, the performance should be acceptable. Under MS-DOS and
 9964: other single-tasking systems, it should be good.
 9965: 
 9966: @end table
 9967: 
 9968: 
 9969: @c ---------------------------------------------------------------------
 9970: @node facility-ambcond,  , facility-idef, The optional Facility word set
 9971: @subsection Ambiguous conditions
 9972: @c ---------------------------------------------------------------------
 9973: @cindex facility words, ambiguous conditions
 9974: @cindex ambiguous conditions, facility words
 9975: 
 9976: @table @i
 9977: @item @code{AT-XY} can't be performed on user output device:
 9978: @cindex @code{AT-XY} can't be performed on user output device
 9979: Largely terminal dependent. No range checks are done on the arguments.
 9980: No errors are reported. You may see some garbage appearing, you may see
 9981: simply nothing happen.
 9982: 
 9983: @end table
 9984: 
 9985: 
 9986: @c =====================================================================
 9987: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
 9988: @section The optional File-Access word set
 9989: @c =====================================================================
 9990: @cindex system documentation, file words
 9991: @cindex file words, system documentation
 9992: 
 9993: @menu
 9994: * file-idef::                   Implementation Defined Options
 9995: * file-ambcond::                Ambiguous Conditions                
 9996: @end menu
 9997: 
 9998: @c ---------------------------------------------------------------------
 9999: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
10000: @subsection Implementation Defined Options
10001: @c ---------------------------------------------------------------------
10002: @cindex implementation-defined options, file words
10003: @cindex file words, implementation-defined options
10004: 
10005: @table @i
10006: @item file access methods used:
10007: @cindex file access methods used
10008: @code{R/O}, @code{R/W} and @code{BIN} work as you would
10009: expect. @code{W/O} translates into the C file opening mode @code{w} (or
10010: @code{wb}): The file is cleared, if it exists, and created, if it does
10011: not (with both @code{open-file} and @code{create-file}).  Under Unix
10012: @code{create-file} creates a file with 666 permissions modified by your
10013: umask.
10014: 
10015: @item file exceptions:
10016: @cindex file exceptions
10017: The file words do not raise exceptions (except, perhaps, memory access
10018: faults when you pass illegal addresses or file-ids).
10019: 
10020: @item file line terminator:
10021: @cindex file line terminator
10022: System-dependent. Gforth uses C's newline character as line
10023: terminator. What the actual character code(s) of this are is
10024: system-dependent.
10025: 
10026: @item file name format:
10027: @cindex file name format
10028: System dependent. Gforth just uses the file name format of your OS.
10029: 
10030: @item information returned by @code{FILE-STATUS}:
10031: @cindex @code{FILE-STATUS}, returned information
10032: @code{FILE-STATUS} returns the most powerful file access mode allowed
10033: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
10034: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
10035: along with the returned mode.
10036: 
10037: @item input file state after an exception when including source:
10038: @cindex exception when including source
10039: All files that are left via the exception are closed.
10040: 
10041: @item @i{ior} values and meaning:
10042: @cindex @i{ior} values and meaning
10043: The @i{ior}s returned by the file and memory allocation words are
10044: intended as throw codes. They typically are in the range
10045: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
10046: @i{ior}s is -512@minus{}@i{errno}.
10047: 
10048: @item maximum depth of file input nesting:
10049: @cindex maximum depth of file input nesting
10050: @cindex file input nesting, maximum depth
10051: limited by the amount of return stack, locals/TIB stack, and the number
10052: of open files available. This should not give you troubles.
10053: 
10054: @item maximum size of input line:
10055: @cindex maximum size of input line
10056: @cindex input line size, maximum
10057: @code{/line}. Currently 255.
10058: 
10059: @item methods of mapping block ranges to files:
10060: @cindex mapping block ranges to files
10061: @cindex files containing blocks
10062: @cindex blocks in files
10063: By default, blocks are accessed in the file @file{blocks.fb} in the
10064: current working directory. The file can be switched with @code{USE}.
10065: 
10066: @item number of string buffers provided by @code{S"}:
10067: @cindex @code{S"}, number of string buffers
10068: 1
10069: 
10070: @item size of string buffer used by @code{S"}:
10071: @cindex @code{S"}, size of string buffer
10072: @code{/line}. currently 255.
10073: 
10074: @end table
10075: 
10076: @c ---------------------------------------------------------------------
10077: @node file-ambcond,  , file-idef, The optional File-Access word set
10078: @subsection Ambiguous conditions
10079: @c ---------------------------------------------------------------------
10080: @cindex file words, ambiguous conditions
10081: @cindex ambiguous conditions, file words
10082: 
10083: @table @i
10084: @item attempting to position a file outside its boundaries:
10085: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
10086: @code{REPOSITION-FILE} is performed as usual: Afterwards,
10087: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
10088: 
10089: @item attempting to read from file positions not yet written:
10090: @cindex reading from file positions not yet written
10091: End-of-file, i.e., zero characters are read and no error is reported.
10092: 
10093: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
10094: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
10095: An appropriate exception may be thrown, but a memory fault or other
10096: problem is more probable.
10097: 
10098: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
10099: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
10100: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
10101: The @i{ior} produced by the operation, that discovered the problem, is
10102: thrown.
10103: 
10104: @item named file cannot be opened (@code{INCLUDED}):
10105: @cindex @code{INCLUDED}, named file cannot be opened
10106: The @i{ior} produced by @code{open-file} is thrown.
10107: 
10108: @item requesting an unmapped block number:
10109: @cindex unmapped block numbers
10110: There are no unmapped legal block numbers. On some operating systems,
10111: writing a block with a large number may overflow the file system and
10112: have an error message as consequence.
10113: 
10114: @item using @code{source-id} when @code{blk} is non-zero:
10115: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
10116: @code{source-id} performs its function. Typically it will give the id of
10117: the source which loaded the block. (Better ideas?)
10118: 
10119: @end table
10120: 
10121: 
10122: @c =====================================================================
10123: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
10124: @section The optional Floating-Point word set
10125: @c =====================================================================
10126: @cindex system documentation, floating-point words
10127: @cindex floating-point words, system documentation
10128: 
10129: @menu
10130: * floating-idef::               Implementation Defined Options
10131: * floating-ambcond::            Ambiguous Conditions            
10132: @end menu
10133: 
10134: 
10135: @c ---------------------------------------------------------------------
10136: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
10137: @subsection Implementation Defined Options
10138: @c ---------------------------------------------------------------------
10139: @cindex implementation-defined options, floating-point words
10140: @cindex floating-point words, implementation-defined options
10141: 
10142: @table @i
10143: @item format and range of floating point numbers:
10144: @cindex format and range of floating point numbers
10145: @cindex floating point numbers, format and range
10146: System-dependent; the @code{double} type of C.
10147: 
10148: @item results of @code{REPRESENT} when @i{float} is out of range:
10149: @cindex  @code{REPRESENT}, results when @i{float} is out of range
10150: System dependent; @code{REPRESENT} is implemented using the C library
10151: function @code{ecvt()} and inherits its behaviour in this respect.
10152: 
10153: @item rounding or truncation of floating-point numbers:
10154: @cindex rounding of floating-point numbers
10155: @cindex truncation of floating-point numbers
10156: @cindex floating-point numbers, rounding or truncation
10157: System dependent; the rounding behaviour is inherited from the hosting C
10158: compiler. IEEE-FP-based (i.e., most) systems by default round to
10159: nearest, and break ties by rounding to even (i.e., such that the last
10160: bit of the mantissa is 0).
10161: 
10162: @item size of floating-point stack:
10163: @cindex floating-point stack size
10164: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
10165: the floating-point stack (in floats). You can specify this on startup
10166: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
10167: 
10168: @item width of floating-point stack:
10169: @cindex floating-point stack width 
10170: @code{1 floats}.
10171: 
10172: @end table
10173: 
10174: 
10175: @c ---------------------------------------------------------------------
10176: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
10177: @subsection Ambiguous conditions
10178: @c ---------------------------------------------------------------------
10179: @cindex floating-point words, ambiguous conditions
10180: @cindex ambiguous conditions, floating-point words
10181: 
10182: @table @i
10183: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
10184: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
10185: System-dependent. Typically results in a @code{-23 THROW} like other
10186: alignment violations.
10187: 
10188: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
10189: @cindex @code{f@@} used with an address that is not float aligned
10190: @cindex @code{f!} used with an address that is not float aligned
10191: System-dependent. Typically results in a @code{-23 THROW} like other
10192: alignment violations.
10193: 
10194: @item floating-point result out of range:
10195: @cindex floating-point result out of range
10196: System-dependent. Can result in a @code{-55 THROW} (Floating-point
10197: unidentified fault), or can produce a special value representing, e.g.,
10198: Infinity.
10199: 
10200: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
10201: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
10202: System-dependent. Typically results in an alignment fault like other
10203: alignment violations.
10204: 
10205: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
10206: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
10207: The floating-point number is converted into decimal nonetheless.
10208: 
10209: @item Both arguments are equal to zero (@code{FATAN2}):
10210: @cindex @code{FATAN2}, both arguments are equal to zero
10211: System-dependent. @code{FATAN2} is implemented using the C library
10212: function @code{atan2()}.
10213: 
10214: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
10215: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
10216: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
10217: because of small errors and the tan will be a very large (or very small)
10218: but finite number.
10219: 
10220: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
10221: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
10222: The result is rounded to the nearest float.
10223: 
10224: @item dividing by zero:
10225: @cindex dividing by zero, floating-point
10226: @cindex floating-point dividing by zero
10227: @cindex floating-point unidentified fault, FP divide-by-zero
10228: @code{-55 throw} (Floating-point unidentified fault)
10229: 
10230: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
10231: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
10232: System dependent. On IEEE-FP based systems the number is converted into
10233: an infinity.
10234: 
10235: @item @i{float}<1 (@code{FACOSH}):
10236: @cindex @code{FACOSH}, @i{float}<1
10237: @cindex floating-point unidentified fault, @code{FACOSH}
10238: @code{-55 throw} (Floating-point unidentified fault)
10239: 
10240: @item @i{float}=<-1 (@code{FLNP1}):
10241: @cindex @code{FLNP1}, @i{float}=<-1
10242: @cindex floating-point unidentified fault, @code{FLNP1}
10243: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
10244: negative infinity is typically produced for @i{float}=-1.
10245: 
10246: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
10247: @cindex @code{FLN}, @i{float}=<0
10248: @cindex @code{FLOG}, @i{float}=<0
10249: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
10250: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
10251: negative infinity is typically produced for @i{float}=0.
10252: 
10253: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
10254: @cindex @code{FASINH}, @i{float}<0
10255: @cindex @code{FSQRT}, @i{float}<0
10256: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
10257: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
10258: produces values for these inputs on my Linux box (Bug in the C library?)
10259: 
10260: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
10261: @cindex @code{FACOS}, |@i{float}|>1
10262: @cindex @code{FASIN}, |@i{float}|>1
10263: @cindex @code{FATANH}, |@i{float}|>1
10264: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
10265: @code{-55 throw} (Floating-point unidentified fault).
10266: 
10267: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
10268: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
10269: @cindex floating-point unidentified fault, @code{F>D}
10270: @code{-55 throw} (Floating-point unidentified fault).
10271: 
10272: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
10273: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
10274: This does not happen.
10275: @end table
10276: 
10277: @c =====================================================================
10278: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
10279: @section The optional Locals word set
10280: @c =====================================================================
10281: @cindex system documentation, locals words
10282: @cindex locals words, system documentation
10283: 
10284: @menu
10285: * locals-idef::                 Implementation Defined Options                 
10286: * locals-ambcond::              Ambiguous Conditions              
10287: @end menu
10288: 
10289: 
10290: @c ---------------------------------------------------------------------
10291: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
10292: @subsection Implementation Defined Options
10293: @c ---------------------------------------------------------------------
10294: @cindex implementation-defined options, locals words
10295: @cindex locals words, implementation-defined options
10296: 
10297: @table @i
10298: @item maximum number of locals in a definition:
10299: @cindex maximum number of locals in a definition
10300: @cindex locals, maximum number in a definition
10301: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
10302: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
10303: characters. The number of locals in a definition is bounded by the size
10304: of locals-buffer, which contains the names of the locals.
10305: 
10306: @end table
10307: 
10308: 
10309: @c ---------------------------------------------------------------------
10310: @node locals-ambcond,  , locals-idef, The optional Locals word set
10311: @subsection Ambiguous conditions
10312: @c ---------------------------------------------------------------------
10313: @cindex locals words, ambiguous conditions
10314: @cindex ambiguous conditions, locals words
10315: 
10316: @table @i
10317: @item executing a named local in interpretation state:
10318: @cindex local in interpretation state
10319: @cindex Interpreting a compile-only word, for a local
10320: Locals have no interpretation semantics. If you try to perform the
10321: interpretation semantics, you will get a @code{-14 throw} somewhere
10322: (Interpreting a compile-only word). If you perform the compilation
10323: semantics, the locals access will be compiled (irrespective of state).
10324: 
10325: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
10326: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
10327: @cindex @code{TO} on non-@code{VALUE}s and non-locals
10328: @cindex Invalid name argument, @code{TO}
10329: @code{-32 throw} (Invalid name argument)
10330: 
10331: @end table
10332: 
10333: 
10334: @c =====================================================================
10335: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
10336: @section The optional Memory-Allocation word set
10337: @c =====================================================================
10338: @cindex system documentation, memory-allocation words
10339: @cindex memory-allocation words, system documentation
10340: 
10341: @menu
10342: * memory-idef::                 Implementation Defined Options                 
10343: @end menu
10344: 
10345: 
10346: @c ---------------------------------------------------------------------
10347: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
10348: @subsection Implementation Defined Options
10349: @c ---------------------------------------------------------------------
10350: @cindex implementation-defined options, memory-allocation words
10351: @cindex memory-allocation words, implementation-defined options
10352: 
10353: @table @i
10354: @item values and meaning of @i{ior}:
10355: @cindex  @i{ior} values and meaning
10356: The @i{ior}s returned by the file and memory allocation words are
10357: intended as throw codes. They typically are in the range
10358: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
10359: @i{ior}s is -512@minus{}@i{errno}.
10360: 
10361: @end table
10362: 
10363: @c =====================================================================
10364: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
10365: @section The optional Programming-Tools word set
10366: @c =====================================================================
10367: @cindex system documentation, programming-tools words
10368: @cindex programming-tools words, system documentation
10369: 
10370: @menu
10371: * programming-idef::            Implementation Defined Options            
10372: * programming-ambcond::         Ambiguous Conditions         
10373: @end menu
10374: 
10375: 
10376: @c ---------------------------------------------------------------------
10377: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
10378: @subsection Implementation Defined Options
10379: @c ---------------------------------------------------------------------
10380: @cindex implementation-defined options, programming-tools words
10381: @cindex programming-tools words, implementation-defined options
10382: 
10383: @table @i
10384: @item ending sequence for input following @code{;CODE} and @code{CODE}:
10385: @cindex @code{;CODE} ending sequence
10386: @cindex @code{CODE} ending sequence
10387: @code{END-CODE}
10388: 
10389: @item manner of processing input following @code{;CODE} and @code{CODE}:
10390: @cindex @code{;CODE}, processing input
10391: @cindex @code{CODE}, processing input
10392: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
10393: the input is processed by the text interpreter, (starting) in interpret
10394: state.
10395: 
10396: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
10397: @cindex @code{ASSEMBLER}, search order capability
10398: The ANS Forth search order word set.
10399: 
10400: @item source and format of display by @code{SEE}:
10401: @cindex @code{SEE}, source and format of output
10402: The source for @code{see} is the intermediate code used by the inner
10403: interpreter.  The current @code{see} tries to output Forth source code
10404: as well as possible.
10405: 
10406: @end table
10407: 
10408: @c ---------------------------------------------------------------------
10409: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
10410: @subsection Ambiguous conditions
10411: @c ---------------------------------------------------------------------
10412: @cindex programming-tools words, ambiguous conditions
10413: @cindex ambiguous conditions, programming-tools words
10414: 
10415: @table @i
10416: 
10417: @item deleting the compilation word list (@code{FORGET}):
10418: @cindex @code{FORGET}, deleting the compilation word list
10419: Not implemented (yet).
10420: 
10421: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
10422: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
10423: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
10424: @cindex control-flow stack underflow
10425: This typically results in an @code{abort"} with a descriptive error
10426: message (may change into a @code{-22 throw} (Control structure mismatch)
10427: in the future). You may also get a memory access error. If you are
10428: unlucky, this ambiguous condition is not caught.
10429: 
10430: @item @i{name} can't be found (@code{FORGET}):
10431: @cindex @code{FORGET}, @i{name} can't be found
10432: Not implemented (yet).
10433: 
10434: @item @i{name} not defined via @code{CREATE}:
10435: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
10436: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
10437: the execution semantics of the last defined word no matter how it was
10438: defined.
10439: 
10440: @item @code{POSTPONE} applied to @code{[IF]}:
10441: @cindex @code{POSTPONE} applied to @code{[IF]}
10442: @cindex @code{[IF]} and @code{POSTPONE}
10443: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
10444: equivalent to @code{[IF]}.
10445: 
10446: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
10447: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
10448: Continue in the same state of conditional compilation in the next outer
10449: input source. Currently there is no warning to the user about this.
10450: 
10451: @item removing a needed definition (@code{FORGET}):
10452: @cindex @code{FORGET}, removing a needed definition
10453: Not implemented (yet).
10454: 
10455: @end table
10456: 
10457: 
10458: @c =====================================================================
10459: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
10460: @section The optional Search-Order word set
10461: @c =====================================================================
10462: @cindex system documentation, search-order words
10463: @cindex search-order words, system documentation
10464: 
10465: @menu
10466: * search-idef::                 Implementation Defined Options                 
10467: * search-ambcond::              Ambiguous Conditions              
10468: @end menu
10469: 
10470: 
10471: @c ---------------------------------------------------------------------
10472: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
10473: @subsection Implementation Defined Options
10474: @c ---------------------------------------------------------------------
10475: @cindex implementation-defined options, search-order words
10476: @cindex search-order words, implementation-defined options
10477: 
10478: @table @i
10479: @item maximum number of word lists in search order:
10480: @cindex maximum number of word lists in search order
10481: @cindex search order, maximum depth
10482: @code{s" wordlists" environment? drop .}. Currently 16.
10483: 
10484: @item minimum search order:
10485: @cindex minimum search order
10486: @cindex search order, minimum
10487: @code{root root}.
10488: 
10489: @end table
10490: 
10491: @c ---------------------------------------------------------------------
10492: @node search-ambcond,  , search-idef, The optional Search-Order word set
10493: @subsection Ambiguous conditions
10494: @c ---------------------------------------------------------------------
10495: @cindex search-order words, ambiguous conditions
10496: @cindex ambiguous conditions, search-order words
10497: 
10498: @table @i
10499: @item changing the compilation word list (during compilation):
10500: @cindex changing the compilation word list (during compilation)
10501: @cindex compilation word list, change before definition ends
10502: The word is entered into the word list that was the compilation word list
10503: at the start of the definition. Any changes to the name field (e.g.,
10504: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
10505: are applied to the latest defined word (as reported by @code{last} or
10506: @code{lastxt}), if possible, irrespective of the compilation word list.
10507: 
10508: @item search order empty (@code{previous}):
10509: @cindex @code{previous}, search order empty
10510: @cindex vocstack empty, @code{previous}
10511: @code{abort" Vocstack empty"}.
10512: 
10513: @item too many word lists in search order (@code{also}):
10514: @cindex @code{also}, too many word lists in search order
10515: @cindex vocstack full, @code{also}
10516: @code{abort" Vocstack full"}.
10517: 
10518: @end table
10519: 
10520: @c ***************************************************************
10521: @node Model, Integrating Gforth, ANS conformance, Top
10522: @chapter Model
10523: 
10524: This chapter has yet to be written. It will contain information, on
10525: which internal structures you can rely.
10526: 
10527: @c ***************************************************************
10528: @node Integrating Gforth, Emacs and Gforth, Model, Top
10529: @chapter Integrating Gforth into C programs
10530: 
10531: This is not yet implemented.
10532: 
10533: Several people like to use Forth as scripting language for applications
10534: that are otherwise written in C, C++, or some other language.
10535: 
10536: The Forth system ATLAST provides facilities for embedding it into
10537: applications; unfortunately it has several disadvantages: most
10538: importantly, it is not based on ANS Forth, and it is apparently dead
10539: (i.e., not developed further and not supported). The facilities
10540: provided by Gforth in this area are inspired by ATLAST's facilities, so
10541: making the switch should not be hard.
10542: 
10543: We also tried to design the interface such that it can easily be
10544: implemented by other Forth systems, so that we may one day arrive at a
10545: standardized interface. Such a standard interface would allow you to
10546: replace the Forth system without having to rewrite C code.
10547: 
10548: You embed the Gforth interpreter by linking with the library
10549: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
10550: global symbols in this library that belong to the interface, have the
10551: prefix @code{forth_}. (Global symbols that are used internally have the
10552: prefix @code{gforth_}).
10553: 
10554: You can include the declarations of Forth types and the functions and
10555: variables of the interface with @code{#include <forth.h>}.
10556: 
10557: Types.
10558: 
10559: Variables.
10560: 
10561: Data and FP Stack pointer. Area sizes.
10562: 
10563: functions.
10564: 
10565: forth_init(imagefile)
10566: forth_evaluate(string) exceptions?
10567: forth_goto(address) (or forth_execute(xt)?)
10568: forth_continue() (a corountining mechanism)
10569: 
10570: Adding primitives.
10571: 
10572: No checking.
10573: 
10574: Signals?
10575: 
10576: Accessing the Stacks
10577: 
10578: @c ******************************************************************
10579: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
10580: @chapter Emacs and Gforth
10581: @cindex Emacs and Gforth
10582: 
10583: @cindex @file{gforth.el}
10584: @cindex @file{forth.el}
10585: @cindex Rydqvist, Goran
10586: @cindex comment editing commands
10587: @cindex @code{\}, editing with Emacs
10588: @cindex debug tracer editing commands
10589: @cindex @code{~~}, removal with Emacs
10590: @cindex Forth mode in Emacs
10591: Gforth comes with @file{gforth.el}, an improved version of
10592: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
10593: improvements are:
10594: 
10595: @itemize @bullet
10596: @item
10597: A better (but still not perfect) handling of indentation.
10598: @item
10599: Comment paragraph filling (@kbd{M-q})
10600: @item
10601: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
10602: @item
10603: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
10604: @item
10605: Support of the @code{info-lookup} feature for looking up the
10606: documentation of a word.
10607: @end itemize
10608: 
10609: I left the stuff I do not use alone, even though some of it only makes
10610: sense for TILE. To get a description of these features, enter Forth mode
10611: and type @kbd{C-h m}.
10612: 
10613: @cindex source location of error or debugging output in Emacs
10614: @cindex error output, finding the source location in Emacs
10615: @cindex debugging output, finding the source location in Emacs
10616: In addition, Gforth supports Emacs quite well: The source code locations
10617: given in error messages, debugging output (from @code{~~}) and failed
10618: assertion messages are in the right format for Emacs' compilation mode
10619: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
10620: Manual}) so the source location corresponding to an error or other
10621: message is only a few keystrokes away (@kbd{C-x `} for the next error,
10622: @kbd{C-c C-c} for the error under the cursor).
10623: 
10624: @cindex @file{TAGS} file
10625: @cindex @file{etags.fs}
10626: @cindex viewing the source of a word in Emacs
10627: @cindex @code{require}, placement in files
10628: @cindex @code{include}, placement in files
10629: Also, if you @code{require} @file{etags.fs}, a new @file{TAGS} file will
10630: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
10631: contains the definitions of all words defined afterwards. You can then
10632: find the source for a word using @kbd{M-.}. Note that emacs can use
10633: several tags files at the same time (e.g., one for the Gforth sources
10634: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
10635: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
10636: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
10637: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
10638: with @file{etags.fs}, you should avoid putting definitions both before
10639: and after @code{require} etc., otherwise you will see the same file
10640: visited several times by commands like @code{tags-search}.
10641: 
10642: @cindex viewing the documentation of a word in Emacs
10643: @cindex context-sensitive help
10644: Moreover, for words documented in this manual, you can look up the
10645: glossary entry quickly by using @kbd{C-h TAB}
10646: (@code{info-lookup-symbol}, see @pxref{Documentation, ,Documentation
10647: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
10648: later and does not work for words containing @code{:}.
10649: 
10650: 
10651: @cindex @file{.emacs}
10652: To get all these benefits, add the following lines to your @file{.emacs}
10653: file:
10654: 
10655: @example
10656: (autoload 'forth-mode "gforth.el")
10657: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
10658: @end example
10659: 
10660: @c ******************************************************************
10661: @node Image Files, Engine, Emacs and Gforth, Top
10662: @chapter Image Files
10663: @cindex image file
10664: @cindex @file{.fi} files
10665: @cindex precompiled Forth code
10666: @cindex dictionary in persistent form
10667: @cindex persistent form of dictionary
10668: 
10669: An image file is a file containing an image of the Forth dictionary,
10670: i.e., compiled Forth code and data residing in the dictionary.  By
10671: convention, we use the extension @code{.fi} for image files.
10672: 
10673: @menu
10674: * Image Licensing Issues::      Distribution terms for images.
10675: * Image File Background::       Why have image files?
10676: * Non-Relocatable Image Files::   don't always work.
10677: * Data-Relocatable Image Files::  are better.
10678: * Fully Relocatable Image Files:: better yet.
10679: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
10680: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
10681: * Modifying the Startup Sequence::  and turnkey applications.
10682: @end menu
10683: 
10684: @node Image Licensing Issues, Image File Background, Image Files, Image Files
10685: @section Image Licensing Issues
10686: @cindex license for images
10687: @cindex image license
10688: 
10689: An image created with @code{gforthmi} (@pxref{gforthmi}) or
10690: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
10691: original image; i.e., according to copyright law it is a derived work of
10692: the original image.
10693: 
10694: Since Gforth is distributed under the GNU GPL, the newly created image
10695: falls under the GNU GPL, too. In particular, this means that if you
10696: distribute the image, you have to make all of the sources for the image
10697: available, including those you wrote.  For details see @ref{License, ,
10698: GNU General Public License (Section 3)}.
10699: 
10700: If you create an image with @code{cross} (@pxref{cross.fs}), the image
10701: contains only code compiled from the sources you gave it; if none of
10702: these sources is under the GPL, the terms discussed above do not apply
10703: to the image. However, if your image needs an engine (a gforth binary)
10704: that is under the GPL, you should make sure that you distribute both in
10705: a way that is at most a @emph{mere aggregation}, if you don't want the
10706: terms of the GPL to apply to the image.
10707: 
10708: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
10709: @section Image File Background
10710: @cindex image file background
10711: 
10712: Our Forth system consists not only of primitives, but also of
10713: definitions written in Forth. Since the Forth compiler itself belongs to
10714: those definitions, it is not possible to start the system with the
10715: primitives and the Forth source alone. Therefore we provide the Forth
10716: code as an image file in nearly executable form. When Gforth starts up,
10717: a C routine loads the image file into memory, optionally relocates the
10718: addresses, then sets up the memory (stacks etc.) according to
10719: information in the image file, and (finally) starts executing Forth
10720: code.
10721: 
10722: The image file variants represent different compromises between the
10723: goals of making it easy to generate image files and making them
10724: portable.
10725: 
10726: @cindex relocation at run-time
10727: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
10728: run-time. This avoids many of the complications discussed below (image
10729: files are data relocatable without further ado), but costs performance
10730: (one addition per memory access).
10731: 
10732: @cindex relocation at load-time
10733: By contrast, the Gforth loader performs relocation at image load time. The
10734: loader also has to replace tokens that represent primitive calls with the
10735: appropriate code-field addresses (or code addresses in the case of
10736: direct threading).
10737: 
10738: There are three kinds of image files, with different degrees of
10739: relocatability: non-relocatable, data-relocatable, and fully relocatable
10740: image files.
10741: 
10742: @cindex image file loader
10743: @cindex relocating loader
10744: @cindex loader for image files
10745: These image file variants have several restrictions in common; they are
10746: caused by the design of the image file loader:
10747: 
10748: @itemize @bullet
10749: @item
10750: There is only one segment; in particular, this means, that an image file
10751: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
10752: them). The contents of the stacks are not represented, either.
10753: 
10754: @item
10755: The only kinds of relocation supported are: adding the same offset to
10756: all cells that represent data addresses; and replacing special tokens
10757: with code addresses or with pieces of machine code.
10758: 
10759: If any complex computations involving addresses are performed, the
10760: results cannot be represented in the image file. Several applications that
10761: use such computations come to mind:
10762: @itemize @minus
10763: @item
10764: Hashing addresses (or data structures which contain addresses) for table
10765: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
10766: purpose, you will have no problem, because the hash tables are
10767: recomputed automatically when the system is started. If you use your own
10768: hash tables, you will have to do something similar.
10769: 
10770: @item
10771: There's a cute implementation of doubly-linked lists that uses
10772: @code{XOR}ed addresses. You could represent such lists as singly-linked
10773: in the image file, and restore the doubly-linked representation on
10774: startup.@footnote{In my opinion, though, you should think thrice before
10775: using a doubly-linked list (whatever implementation).}
10776: 
10777: @item
10778: The code addresses of run-time routines like @code{docol:} cannot be
10779: represented in the image file (because their tokens would be replaced by
10780: machine code in direct threaded implementations). As a workaround,
10781: compute these addresses at run-time with @code{>code-address} from the
10782: executions tokens of appropriate words (see the definitions of
10783: @code{docol:} and friends in @file{kernel.fs}).
10784: 
10785: @item
10786: On many architectures addresses are represented in machine code in some
10787: shifted or mangled form. You cannot put @code{CODE} words that contain
10788: absolute addresses in this form in a relocatable image file. Workarounds
10789: are representing the address in some relative form (e.g., relative to
10790: the CFA, which is present in some register), or loading the address from
10791: a place where it is stored in a non-mangled form.
10792: @end itemize
10793: @end itemize
10794: 
10795: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
10796: @section Non-Relocatable Image Files
10797: @cindex non-relocatable image files
10798: @cindex image file, non-relocatable
10799: 
10800: These files are simple memory dumps of the dictionary. They are specific
10801: to the executable (i.e., @file{gforth} file) they were created
10802: with. What's worse, they are specific to the place on which the
10803: dictionary resided when the image was created. Now, there is no
10804: guarantee that the dictionary will reside at the same place the next
10805: time you start Gforth, so there's no guarantee that a non-relocatable
10806: image will work the next time (Gforth will complain instead of crashing,
10807: though).
10808: 
10809: You can create a non-relocatable image file with
10810: 
10811: 
10812: doc-savesystem
10813: 
10814: 
10815: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
10816: @section Data-Relocatable Image Files
10817: @cindex data-relocatable image files
10818: @cindex image file, data-relocatable
10819: 
10820: These files contain relocatable data addresses, but fixed code addresses
10821: (instead of tokens). They are specific to the executable (i.e.,
10822: @file{gforth} file) they were created with. For direct threading on some
10823: architectures (e.g., the i386), data-relocatable images do not work. You
10824: get a data-relocatable image, if you use @file{gforthmi} with a
10825: Gforth binary that is not doubly indirect threaded (@pxref{Fully
10826: Relocatable Image Files}).
10827: 
10828: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
10829: @section Fully Relocatable Image Files
10830: @cindex fully relocatable image files
10831: @cindex image file, fully relocatable
10832: 
10833: @cindex @file{kern*.fi}, relocatability
10834: @cindex @file{gforth.fi}, relocatability
10835: These image files have relocatable data addresses, and tokens for code
10836: addresses. They can be used with different binaries (e.g., with and
10837: without debugging) on the same machine, and even across machines with
10838: the same data formats (byte order, cell size, floating point
10839: format). However, they are usually specific to the version of Gforth
10840: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
10841: are fully relocatable.
10842: 
10843: There are two ways to create a fully relocatable image file:
10844: 
10845: @menu
10846: * gforthmi::                    The normal way
10847: * cross.fs::                    The hard way
10848: @end menu
10849: 
10850: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
10851: @subsection @file{gforthmi}
10852: @cindex @file{comp-i.fs}
10853: @cindex @file{gforthmi}
10854: 
10855: You will usually use @file{gforthmi}. If you want to create an
10856: image @i{file} that contains everything you would load by invoking
10857: Gforth with @code{gforth @i{options}}, you simply say:
10858: @example
10859: gforthmi @i{file} @i{options}
10860: @end example
10861: 
10862: E.g., if you want to create an image @file{asm.fi} that has the file
10863: @file{asm.fs} loaded in addition to the usual stuff, you could do it
10864: like this:
10865: 
10866: @example
10867: gforthmi asm.fi asm.fs
10868: @end example
10869: 
10870: @file{gforthmi} is implemented as a sh script and works like this: It
10871: produces two non-relocatable images for different addresses and then
10872: compares them. Its output reflects this: first you see the output (if
10873: any) of the two Gforth invocations that produce the nonrelocatable image
10874: files, then you see the output of the comparing program: It displays the
10875: offset used for data addresses and the offset used for code addresses;
10876: moreover, for each cell that cannot be represented correctly in the
10877: image files, it displays a line like this:
10878: 
10879: @example
10880:      78DC         BFFFFA50         BFFFFA40
10881: @end example
10882: 
10883: This means that at offset $78dc from @code{forthstart}, one input image
10884: contains $bffffa50, and the other contains $bffffa40. Since these cells
10885: cannot be represented correctly in the output image, you should examine
10886: these places in the dictionary and verify that these cells are dead
10887: (i.e., not read before they are written).
10888: 
10889: @cindex --application, @code{gforthmi} option
10890: If you insert the option @code{--application} in front of the image file
10891: name, you will get an image that uses the @code{--appl-image} option
10892: instead of the @code{--image-file} option (@pxref{Invoking
10893: Gforth}). When you execute such an image on Unix (by typing the image
10894: name as command), the Gforth engine will pass all options to the image
10895: instead of trying to interpret them as engine options.
10896: 
10897: If you type @file{gforthmi} with no arguments, it prints some usage
10898: instructions.
10899: 
10900: @cindex @code{savesystem} during @file{gforthmi}
10901: @cindex @code{bye} during @file{gforthmi}
10902: @cindex doubly indirect threaded code
10903: @cindex environment variables
10904: @cindex @code{GFORTHD} -- environment variable
10905: @cindex @code{GFORTH} -- environment variable
10906: @cindex @code{gforth-ditc}
10907: There are a few wrinkles: After processing the passed @i{options}, the
10908: words @code{savesystem} and @code{bye} must be visible. A special doubly
10909: indirect threaded version of the @file{gforth} executable is used for
10910: creating the nonrelocatable images; you can pass the exact filename of
10911: this executable through the environment variable @code{GFORTHD}
10912: (default: @file{gforth-ditc}); if you pass a version that is not doubly
10913: indirect threaded, you will not get a fully relocatable image, but a
10914: data-relocatable image (because there is no code address offset). The
10915: normal @file{gforth} executable is used for creating the relocatable
10916: image; you can pass the exact filename of this executable through the
10917: environment variable @code{GFORTH}.
10918: 
10919: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
10920: @subsection @file{cross.fs}
10921: @cindex @file{cross.fs}
10922: @cindex cross-compiler
10923: @cindex metacompiler
10924: 
10925: You can also use @code{cross}, a batch compiler that accepts a Forth-like
10926: programming language. This @code{cross} language has to be documented
10927: yet.
10928: 
10929: @cindex target compiler
10930: @code{cross} also allows you to create image files for machines with
10931: different data sizes and data formats than the one used for generating
10932: the image file. You can also use it to create an application image that
10933: does not contain a Forth compiler. These features are bought with
10934: restrictions and inconveniences in programming. E.g., addresses have to
10935: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
10936: order to make the code relocatable.
10937: 
10938: 
10939: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
10940: @section Stack and Dictionary Sizes
10941: @cindex image file, stack and dictionary sizes
10942: @cindex dictionary size default
10943: @cindex stack size default
10944: 
10945: If you invoke Gforth with a command line flag for the size
10946: (@pxref{Invoking Gforth}), the size you specify is stored in the
10947: dictionary. If you save the dictionary with @code{savesystem} or create
10948: an image with @file{gforthmi}, this size will become the default
10949: for the resulting image file. E.g., the following will create a
10950: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
10951: 
10952: @example
10953: gforthmi gforth.fi -m 1M
10954: @end example
10955: 
10956: In other words, if you want to set the default size for the dictionary
10957: and the stacks of an image, just invoke @file{gforthmi} with the
10958: appropriate options when creating the image.
10959: 
10960: @cindex stack size, cache-friendly
10961: Note: For cache-friendly behaviour (i.e., good performance), you should
10962: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
10963: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
10964: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
10965: 
10966: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
10967: @section Running Image Files
10968: @cindex running image files
10969: @cindex invoking image files
10970: @cindex image file invocation
10971: 
10972: @cindex -i, invoke image file
10973: @cindex --image file, invoke image file
10974: You can invoke Gforth with an image file @i{image} instead of the
10975: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
10976: @example
10977: gforth -i @i{image}
10978: @end example
10979: 
10980: @cindex executable image file
10981: @cindex image file, executable
10982: If your operating system supports starting scripts with a line of the
10983: form @code{#! ...}, you just have to type the image file name to start
10984: Gforth with this image file (note that the file extension @code{.fi} is
10985: just a convention). I.e., to run Gforth with the image file @i{image},
10986: you can just type @i{image} instead of @code{gforth -i @i{image}}.
10987: This works because every @code{.fi} file starts with a line of this
10988: format:
10989: 
10990: @example
10991: #! /usr/local/bin/gforth-0.4.0 -i
10992: @end example
10993: 
10994: The file and pathname for the Gforth engine specified on this line is
10995: the specific Gforth executable that it was built against; i.e. the value
10996: of the environment variable @code{GFORTH} at the time that
10997: @file{gforthmi} was executed.
10998: 
10999: You can make use of the same shell capability to make a Forth source
11000: file into an executable. For example, if you place this text in a file:
11001: 
11002: @example
11003: #! /usr/local/bin/gforth
11004: 
11005: ." Hello, world" CR
11006: bye
11007: @end example
11008: 
11009: @noindent
11010: and then make the file executable (chmod +x in Unix), you can run it
11011: directly from the command line. The sequence @code{#!} is used in two
11012: ways; firstly, it is recognised as a ``magic sequence'' by the operating
11013: system@footnote{The Unix kernel actually recognises two types of files:
11014: executable files and files of data, where the data is processed by an
11015: interpreter that is specified on the ``interpreter line'' -- the first
11016: line of the file, starting with the sequence #!. There may be a small
11017: limit (e.g., 32) on the number of characters that may be specified on
11018: the interpreter line.} secondly it is treated as a comment character by
11019: Gforth. Because of the second usage, a space is required between
11020: @code{#!} and the path to the executable.
11021: 
11022: The disadvantage of this latter technique, compared with using
11023: @file{gforthmi}, is that it is slower; the Forth source code is compiled
11024: on-the-fly, each time the program is invoked.
11025: 
11026: 
11027: doc-#!
11028: 
11029: 
11030: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
11031: @section Modifying the Startup Sequence
11032: @cindex startup sequence for image file
11033: @cindex image file initialization sequence
11034: @cindex initialization sequence of image file
11035: 
11036: You can add your own initialization to the startup sequence through the
11037: deferred word @code{'cold}. @code{'cold} is invoked just before the
11038: image-specific command line processing (by default, loading files and
11039: evaluating (@code{-e}) strings) starts.
11040: 
11041: A sequence for adding your initialization usually looks like this:
11042: 
11043: @example
11044: :noname
11045:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
11046:     ... \ your stuff
11047: ; IS 'cold
11048: @end example
11049: 
11050: @cindex turnkey image files
11051: @cindex image file, turnkey applications
11052: You can make a turnkey image by letting @code{'cold} execute a word
11053: (your turnkey application) that never returns; instead, it exits Gforth
11054: via @code{bye} or @code{throw}.
11055: 
11056: @cindex command-line arguments, access
11057: @cindex arguments on the command line, access
11058: You can access the (image-specific) command-line arguments through the
11059: variables @code{argc} and @code{argv}. @code{arg} provides convenient
11060: access to @code{argv}.
11061: 
11062: If @code{'cold} exits normally, Gforth processes the command-line
11063: arguments as files to be loaded and strings to be evaluated.  Therefore,
11064: @code{'cold} should remove the arguments it has used in this case.
11065: 
11066: 
11067: 
11068: doc-'cold
11069: doc-argc
11070: doc-argv
11071: doc-arg
11072: 
11073: 
11074: 
11075: @c ******************************************************************
11076: @node Engine, Binding to System Library, Image Files, Top
11077: @chapter Engine
11078: @cindex engine
11079: @cindex virtual machine
11080: 
11081: Reading this chapter is not necessary for programming with Gforth. It
11082: may be helpful for finding your way in the Gforth sources.
11083: 
11084: The ideas in this section have also been published in the papers
11085: @cite{ANS fig/GNU/??? Forth} (in German) by Bernd Paysan, presented at
11086: the Forth-Tagung '93 and @cite{A Portable Forth Engine} by M. Anton
11087: Ertl, presented at EuroForth '93; the latter is available at
11088: @*@url{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z}.
11089: 
11090: @menu
11091: * Portability::                 
11092: * Threading::                   
11093: * Primitives::                  
11094: * Performance::                 
11095: @end menu
11096: 
11097: @node Portability, Threading, Engine, Engine
11098: @section Portability
11099: @cindex engine portability
11100: 
11101: An important goal of the Gforth Project is availability across a wide
11102: range of personal machines. fig-Forth, and, to a lesser extent, F83,
11103: achieved this goal by manually coding the engine in assembly language
11104: for several then-popular processors. This approach is very
11105: labor-intensive and the results are short-lived due to progress in
11106: computer architecture.
11107: 
11108: @cindex C, using C for the engine
11109: Others have avoided this problem by coding in C, e.g., Mitch Bradley
11110: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
11111: particularly popular for UNIX-based Forths due to the large variety of
11112: architectures of UNIX machines. Unfortunately an implementation in C
11113: does not mix well with the goals of efficiency and with using
11114: traditional techniques: Indirect or direct threading cannot be expressed
11115: in C, and switch threading, the fastest technique available in C, is
11116: significantly slower. Another problem with C is that it is very
11117: cumbersome to express double integer arithmetic.
11118: 
11119: @cindex GNU C for the engine
11120: @cindex long long
11121: Fortunately, there is a portable language that does not have these
11122: limitations: GNU C, the version of C processed by the GNU C compiler
11123: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
11124: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
11125: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
11126: threading possible, its @code{long long} type (@pxref{Long Long, ,
11127: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
11128: double numbers@footnote{Unfortunately, long longs are not implemented
11129: properly on all machines (e.g., on alpha-osf1, long longs are only 64
11130: bits, the same size as longs (and pointers), but they should be twice as
11131: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
11132: C Manual}). So, we had to implement doubles in C after all. Still, on
11133: most machines we can use long longs and achieve better performance than
11134: with the emulation package.}. GNU C is available for free on all
11135: important (and many unimportant) UNIX machines, VMS, 80386s running
11136: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
11137: on all these machines.
11138: 
11139: Writing in a portable language has the reputation of producing code that
11140: is slower than assembly. For our Forth engine we repeatedly looked at
11141: the code produced by the compiler and eliminated most compiler-induced
11142: inefficiencies by appropriate changes in the source code.
11143: 
11144: @cindex explicit register declarations
11145: @cindex --enable-force-reg, configuration flag
11146: @cindex -DFORCE_REG
11147: However, register allocation cannot be portably influenced by the
11148: programmer, leading to some inefficiencies on register-starved
11149: machines. We use explicit register declarations (@pxref{Explicit Reg
11150: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
11151: improve the speed on some machines. They are turned on by using the
11152: configuration flag @code{--enable-force-reg} (@code{gcc} switch
11153: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
11154: machine, but also on the compiler version: On some machines some
11155: compiler versions produce incorrect code when certain explicit register
11156: declarations are used. So by default @code{-DFORCE_REG} is not used.
11157: 
11158: @node Threading, Primitives, Portability, Engine
11159: @section Threading
11160: @cindex inner interpreter implementation
11161: @cindex threaded code implementation
11162: 
11163: @cindex labels as values
11164: GNU C's labels as values extension (available since @code{gcc-2.0},
11165: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
11166: makes it possible to take the address of @i{label} by writing
11167: @code{&&@i{label}}.  This address can then be used in a statement like
11168: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
11169: @code{goto x}.
11170: 
11171: @cindex @code{NEXT}, indirect threaded
11172: @cindex indirect threaded inner interpreter
11173: @cindex inner interpreter, indirect threaded
11174: With this feature an indirect threaded @code{NEXT} looks like:
11175: @example
11176: cfa = *ip++;
11177: ca = *cfa;
11178: goto *ca;
11179: @end example
11180: @cindex instruction pointer
11181: For those unfamiliar with the names: @code{ip} is the Forth instruction
11182: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
11183: execution token and points to the code field of the next word to be
11184: executed; The @code{ca} (code address) fetched from there points to some
11185: executable code, e.g., a primitive or the colon definition handler
11186: @code{docol}.
11187: 
11188: @cindex @code{NEXT}, direct threaded
11189: @cindex direct threaded inner interpreter
11190: @cindex inner interpreter, direct threaded
11191: Direct threading is even simpler:
11192: @example
11193: ca = *ip++;
11194: goto *ca;
11195: @end example
11196: 
11197: Of course we have packaged the whole thing neatly in macros called
11198: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
11199: 
11200: @menu
11201: * Scheduling::                  
11202: * Direct or Indirect Threaded?::  
11203: * DOES>::                       
11204: @end menu
11205: 
11206: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
11207: @subsection Scheduling
11208: @cindex inner interpreter optimization
11209: 
11210: There is a little complication: Pipelined and superscalar processors,
11211: i.e., RISC and some modern CISC machines can process independent
11212: instructions while waiting for the results of an instruction. The
11213: compiler usually reorders (schedules) the instructions in a way that
11214: achieves good usage of these delay slots. However, on our first tries
11215: the compiler did not do well on scheduling primitives. E.g., for
11216: @code{+} implemented as
11217: @example
11218: n=sp[0]+sp[1];
11219: sp++;
11220: sp[0]=n;
11221: NEXT;
11222: @end example
11223: the @code{NEXT} comes strictly after the other code, i.e., there is nearly no
11224: scheduling. After a little thought the problem becomes clear: The
11225: compiler cannot know that @code{sp} and @code{ip} point to different
11226: addresses (and the version of @code{gcc} we used would not know it even
11227: if it was possible), so it could not move the load of the cfa above the
11228: store to the TOS. Indeed the pointers could be the same, if code on or
11229: very near the top of stack were executed. In the interest of speed we
11230: chose to forbid this probably unused ``feature'' and helped the compiler
11231: in scheduling: @code{NEXT} is divided into the loading part (@code{NEXT_P1})
11232: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
11233: @example
11234: n=sp[0]+sp[1];
11235: sp++;
11236: NEXT_P1;
11237: sp[0]=n;
11238: NEXT_P2;
11239: @end example
11240: This can be scheduled optimally by the compiler.
11241: 
11242: This division can be turned off with the switch @code{-DCISC_NEXT}. This
11243: switch is on by default on machines that do not profit from scheduling
11244: (e.g., the 80386), in order to preserve registers.
11245: 
11246: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
11247: @subsection Direct or Indirect Threaded?
11248: @cindex threading, direct or indirect?
11249: 
11250: @cindex -DDIRECT_THREADED
11251: Both! After packaging the nasty details in macro definitions we
11252: realized that we could switch between direct and indirect threading by
11253: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
11254: defining a few machine-specific macros for the direct-threading case.
11255: On the Forth level we also offer access words that hide the
11256: differences between the threading methods (@pxref{Threading Words}).
11257: 
11258: Indirect threading is implemented completely machine-independently.
11259: Direct threading needs routines for creating jumps to the executable
11260: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
11261: machine-dependent, but they do not amount to many source lines. Therefore,
11262: even porting direct threading to a new machine requires little effort.
11263: 
11264: @cindex --enable-indirect-threaded, configuration flag
11265: @cindex --enable-direct-threaded, configuration flag
11266: The default threading method is machine-dependent. You can enforce a
11267: specific threading method when building Gforth with the configuration
11268: flag @code{--enable-direct-threaded} or
11269: @code{--enable-indirect-threaded}. Note that direct threading is not
11270: supported on all machines.
11271: 
11272: @node DOES>,  , Direct or Indirect Threaded?, Threading
11273: @subsection DOES>
11274: @cindex @code{DOES>} implementation
11275: 
11276: @cindex @code{dodoes} routine
11277: @cindex @code{DOES>}-code
11278: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
11279: the chunk of code executed by every word defined by a
11280: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
11281: the Forth code to be executed, i.e. the code after the
11282: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
11283: 
11284: In fig-Forth the code field points directly to the @code{dodoes} and the
11285: @code{DOES>}-code address is stored in the cell after the code address (i.e. at
11286: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
11287: the Forth-79 and all later standards, because in fig-Forth this address
11288: lies in the body (which is illegal in these standards). However, by
11289: making the code field larger for all words this solution becomes legal
11290: again. We use this approach for the indirect threaded version and for
11291: direct threading on some machines. Leaving a cell unused in most words
11292: is a bit wasteful, but on the machines we are targeting this is hardly a
11293: problem. The other reason for having a code field size of two cells is
11294: to avoid having different image files for direct and indirect threaded
11295: systems (direct threaded systems require two-cell code fields on many
11296: machines).
11297: 
11298: @cindex @code{DOES>}-handler
11299: The other approach is that the code field points or jumps to the cell
11300: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
11301: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
11302: @code{DOES>}-code address by computing the code address, i.e., the address of
11303: the jump to @code{dodoes}, and add the length of that jump field. A variant of
11304: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
11305: return address (which can be found in the return register on RISCs) is
11306: the @code{DOES>}-code address. Since the two cells available in the code field
11307: are used up by the jump to the code address in direct threading on many
11308: architectures, we use this approach for direct threading on these
11309: architectures. We did not want to add another cell to the code field.
11310: 
11311: @node Primitives, Performance, Threading, Engine
11312: @section Primitives
11313: @cindex primitives, implementation
11314: @cindex virtual machine instructions, implementation
11315: 
11316: @menu
11317: * Automatic Generation::        
11318: * TOS Optimization::            
11319: * Produced code::               
11320: @end menu
11321: 
11322: @node Automatic Generation, TOS Optimization, Primitives, Primitives
11323: @subsection Automatic Generation
11324: @cindex primitives, automatic generation
11325: 
11326: @cindex @file{prims2x.fs}
11327: Since the primitives are implemented in a portable language, there is no
11328: longer any need to minimize the number of primitives. On the contrary,
11329: having many primitives has an advantage: speed. In order to reduce the
11330: number of errors in primitives and to make programming them easier, we
11331: provide a tool, the primitive generator (@file{prims2x.fs}), that
11332: automatically generates most (and sometimes all) of the C code for a
11333: primitive from the stack effect notation.  The source for a primitive
11334: has the following form:
11335: 
11336: @cindex primitive source format
11337: @format
11338: @i{Forth-name}	@i{stack-effect}	@i{category}	[@i{pronounc.}]
11339: [@code{""}@i{glossary entry}@code{""}]
11340: @i{C code}
11341: [@code{:}
11342: @i{Forth code}]
11343: @end format
11344: 
11345: The items in brackets are optional. The category and glossary fields
11346: are there for generating the documentation, the Forth code is there
11347: for manual implementations on machines without GNU C. E.g., the source
11348: for the primitive @code{+} is:
11349: @example
11350: +    n1 n2 -- n    core    plus
11351: n = n1+n2;
11352: @end example
11353: 
11354: This looks like a specification, but in fact @code{n = n1+n2} is C
11355: code. Our primitive generation tool extracts a lot of information from
11356: the stack effect notations@footnote{We use a one-stack notation, even
11357: though we have separate data and floating-point stacks; The separate
11358: notation can be generated easily from the unified notation.}: The number
11359: of items popped from and pushed on the stack, their type, and by what
11360: name they are referred to in the C code. It then generates a C code
11361: prelude and postlude for each primitive. The final C code for @code{+}
11362: looks like this:
11363: 
11364: @example
11365: I_plus:	/* + ( n1 n2 -- n ) */  /* label, stack effect */
11366: /*  */                          /* documentation */
11367: @{
11368: DEF_CA                          /* definition of variable ca (indirect threading) */
11369: Cell n1;                        /* definitions of variables */
11370: Cell n2;
11371: Cell n;
11372: n1 = (Cell) sp[1];              /* input */
11373: n2 = (Cell) TOS;
11374: sp += 1;                        /* stack adjustment */
11375: NAME("+")                       /* debugging output (with -DDEBUG) */
11376: @{
11377: n = n1+n2;                      /* C code taken from the source */
11378: @}
11379: NEXT_P1;                        /* NEXT part 1 */
11380: TOS = (Cell)n;                  /* output */
11381: NEXT_P2;                        /* NEXT part 2 */
11382: @}
11383: @end example
11384: 
11385: This looks long and inefficient, but the GNU C compiler optimizes quite
11386: well and produces optimal code for @code{+} on, e.g., the R3000 and the
11387: HP RISC machines: Defining the @code{n}s does not produce any code, and
11388: using them as intermediate storage also adds no cost.
11389: 
11390: There are also other optimizations that are not illustrated by this
11391: example: assignments between simple variables are usually for free (copy
11392: propagation). If one of the stack items is not used by the primitive
11393: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
11394: (dead code elimination). On the other hand, there are some things that
11395: the compiler does not do, therefore they are performed by
11396: @file{prims2x.fs}: The compiler does not optimize code away that stores
11397: a stack item to the place where it just came from (e.g., @code{over}).
11398: 
11399: While programming a primitive is usually easy, there are a few cases
11400: where the programmer has to take the actions of the generator into
11401: account, most notably @code{?dup}, but also words that do not (always)
11402: fall through to @code{NEXT}.
11403: 
11404: @node TOS Optimization, Produced code, Automatic Generation, Primitives
11405: @subsection TOS Optimization
11406: @cindex TOS optimization for primitives
11407: @cindex primitives, keeping the TOS in a register
11408: 
11409: An important optimization for stack machine emulators, e.g., Forth
11410: engines, is keeping  one or more of the top stack items in
11411: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
11412: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
11413: @itemize @bullet
11414: @item
11415: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
11416: due to fewer loads from and stores to the stack.
11417: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
11418: @i{y<n}, due to additional moves between registers.
11419: @end itemize
11420: 
11421: @cindex -DUSE_TOS
11422: @cindex -DUSE_NO_TOS
11423: In particular, keeping one item in a register is never a disadvantage,
11424: if there are enough registers. Keeping two items in registers is a
11425: disadvantage for frequent words like @code{?branch}, constants,
11426: variables, literals and @code{i}. Therefore our generator only produces
11427: code that keeps zero or one items in registers. The generated C code
11428: covers both cases; the selection between these alternatives is made at
11429: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
11430: code for @code{+} is just a simple variable name in the one-item case,
11431: otherwise it is a macro that expands into @code{sp[0]}. Note that the
11432: GNU C compiler tries to keep simple variables like @code{TOS} in
11433: registers, and it usually succeeds, if there are enough registers.
11434: 
11435: @cindex -DUSE_FTOS
11436: @cindex -DUSE_NO_FTOS
11437: The primitive generator performs the TOS optimization for the
11438: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
11439: operations the benefit of this optimization is even larger:
11440: floating-point operations take quite long on most processors, but can be
11441: performed in parallel with other operations as long as their results are
11442: not used. If the FP-TOS is kept in a register, this works. If
11443: it is kept on the stack, i.e., in memory, the store into memory has to
11444: wait for the result of the floating-point operation, lengthening the
11445: execution time of the primitive considerably.
11446: 
11447: The TOS optimization makes the automatic generation of primitives a
11448: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
11449: @code{TOS} is not sufficient. There are some special cases to
11450: consider:
11451: @itemize @bullet
11452: @item In the case of @code{dup ( w -- w w )} the generator must not
11453: eliminate the store to the original location of the item on the stack,
11454: if the TOS optimization is turned on.
11455: @item Primitives with stack effects of the form @code{--}
11456: @i{out1}...@i{outy} must store the TOS to the stack at the start.
11457: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
11458: must load the TOS from the stack at the end. But for the null stack
11459: effect @code{--} no stores or loads should be generated.
11460: @end itemize
11461: 
11462: @node Produced code,  , TOS Optimization, Primitives
11463: @subsection Produced code
11464: @cindex primitives, assembly code listing
11465: 
11466: @cindex @file{engine.s}
11467: To see what assembly code is produced for the primitives on your machine
11468: with your compiler and your flag settings, type @code{make engine.s} and
11469: look at the resulting file @file{engine.s}.
11470: 
11471: @node  Performance,  , Primitives, Engine
11472: @section Performance
11473: @cindex performance of some Forth interpreters
11474: @cindex engine performance
11475: @cindex benchmarking Forth systems
11476: @cindex Gforth performance
11477: 
11478: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
11479: impossible to write a significantly faster engine.
11480: 
11481: On register-starved machines like the 386 architecture processors
11482: improvements are possible, because @code{gcc} does not utilize the
11483: registers as well as a human, even with explicit register declarations;
11484: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
11485: and hand-tuned it for the 486; this system is 1.19 times faster on the
11486: Sieve benchmark on a 486DX2/66 than Gforth compiled with
11487: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
11488: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
11489: registers fit in real registers (and we can even afford to use the TOS
11490: optimization), resulting in a speedup of 1.14 on the sieve over the
11491: earlier results.
11492: 
11493: @cindex Win32Forth performance
11494: @cindex NT Forth performance
11495: @cindex eforth performance
11496: @cindex ThisForth performance
11497: @cindex PFE performance
11498: @cindex TILE performance
11499: The potential advantage of assembly language implementations
11500: is not necessarily realized in complete Forth systems: We compared
11501: Gforth-0.4.9 (direct threaded, compiled with @code{gcc-2.95.1} and
11502: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
11503: 1994) and Eforth (with and without peephole (aka pinhole) optimization
11504: of the threaded code); all these systems were written in assembly
11505: language. We also compared Gforth with three systems written in C:
11506: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
11507: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
11508: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
11509: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
11510: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
11511: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
11512: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
11513: 486DX2/66 with similar memory performance under Windows NT. Marcel
11514: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
11515: added the peephole optimizer, ran the benchmarks and reported the
11516: results.
11517: 
11518: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
11519: matrix multiplication come from the Stanford integer benchmarks and have
11520: been translated into Forth by Martin Fraeman; we used the versions
11521: included in the TILE Forth package, but with bigger data set sizes; and
11522: a recursive Fibonacci number computation for benchmarking calling
11523: performance. The following table shows the time taken for the benchmarks
11524: scaled by the time taken by Gforth (in other words, it shows the speedup
11525: factor that Gforth achieved over the other systems).
11526: 
11527: @example
11528: relative      Win32-    NT       eforth       This-      
11529:   time  Gforth Forth Forth eforth  +opt   PFE Forth  TILE
11530: sieve     1.00  1.58  1.30   1.58  0.97  1.80  3.63  9.79
11531: bubble    1.00  1.55  1.67   1.75  1.04  1.78        4.59
11532: matmul    1.00  1.67  1.53   1.66  0.84  1.79        4.63
11533: fib       1.00  1.75  1.53   1.40  0.99  1.99  3.43  4.93
11534: @end example
11535: 
11536: You may be quite surprised by the good performance of Gforth when
11537: compared with systems written in assembly language. One important reason
11538: for the disappointing performance of these other systems is probably
11539: that they are not written optimally for the 486 (e.g., they use the
11540: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
11541: but costly method for relocating the Forth image: like @code{cforth}, it
11542: computes the actual addresses at run time, resulting in two address
11543: computations per @code{NEXT} (@pxref{Image File Background}).
11544: 
11545: Only Eforth with the peephole optimizer performs comparable to
11546: Gforth. The speedups achieved with peephole optimization of threaded
11547: code are quite remarkable. Adding a peephole optimizer to Gforth should
11548: cause similar speedups.
11549: 
11550: The speedup of Gforth over PFE, ThisForth and TILE can be easily
11551: explained with the self-imposed restriction of the latter systems to
11552: standard C, which makes efficient threading impossible (however, the
11553: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
11554: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
11555: Moreover, current C compilers have a hard time optimizing other aspects
11556: of the ThisForth and the TILE source.
11557: 
11558: The performance of Gforth on 386 architecture processors varies widely
11559: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
11560: allocate any of the virtual machine registers into real machine
11561: registers by itself and would not work correctly with explicit register
11562: declarations, giving a 1.5 times slower engine (on a 486DX2/66 running
11563: the Sieve) than the one measured above.
11564: 
11565: Note that there have been several releases of Win32Forth since the
11566: release presented here, so the results presented above may have little
11567: predictive value for the performance of Win32Forth today (results for
11568: the current release on an i486DX2/66 are welcome).
11569: 
11570: @cindex @file{Benchres}
11571: In @cite{Translating Forth to Efficient C} by M. Anton Ertl and Martin
11572: Maierhofer (presented at EuroForth '95), an indirect threaded version of
11573: Gforth is compared with Win32Forth, NT Forth, PFE, and ThisForth; that
11574: version of Gforth is slower on a 486 than the direct threaded version
11575: used here. The paper available at
11576: @*@url{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz};
11577: it also contains numbers for some native code systems. You can find a
11578: newer version of these measurements at
11579: @url{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
11580: find numbers for Gforth on various machines in @file{Benchres}.
11581: 
11582: @c ******************************************************************
11583: @node Binding to System Library, Cross Compiler, Engine, Top
11584: @chapter Binding to System Library
11585: 
11586: @node Cross Compiler, Bugs, Binding to System Library, Top
11587: @chapter Cross Compiler
11588: 
11589: Cross Compiler
11590: 
11591: @menu
11592: * Using the Cross Compiler::
11593: * How the Cross Compiler Works::
11594: @end menu
11595: 
11596: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
11597: @section Using the Cross Compiler
11598: 
11599: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
11600: @section How the Cross Compiler Works
11601: 
11602: @node Bugs, Origin, Cross Compiler, Top
11603: @appendix Bugs
11604: @cindex bug reporting
11605: 
11606: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
11607: 
11608: If you find a bug, please send a bug report to
11609: @email{bug-gforth@@gnu.org}. A bug report should include this
11610: information:
11611: 
11612: @itemize @bullet
11613: @item
11614: The Gforth version used (it is announced at the start of an
11615: interactive Gforth session).
11616: @item
11617: The machine and operating system (on Unix
11618: systems @code{uname -a} will report this information).
11619: @item
11620: The installation options (send the file @file{config.status}).
11621: @item
11622: A complete list of changes (if any) you (or your installer) have made to the
11623: Gforth sources.
11624: @item
11625: A program (or a sequence of keyboard commands) that reproduces the bug.
11626: @item
11627: A description of what you think constitutes the buggy behaviour.
11628: @end itemize
11629: 
11630: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
11631: to Report Bugs, gcc.info, GNU C Manual}.
11632: 
11633: 
11634: @node Origin, Forth-related information, Bugs, Top
11635: @appendix Authors and Ancestors of Gforth
11636: 
11637: @section Authors and Contributors
11638: @cindex authors of Gforth
11639: @cindex contributors to Gforth
11640: 
11641: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
11642: Ertl. The third major author was Jens Wilke.  Lennart Benschop (who was
11643: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
11644: with their continuous feedback. Lennart Benshop contributed
11645: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
11646: support for calling C libraries. Helpful comments also came from Paul
11647: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
11648: Wavrik, Barrie Stott, Marc de Groot, and Jorge Acerada. Since the
11649: release of Gforth-0.2.1 there were also helpful comments from many
11650: others; thank you all, sorry for not listing you here (but digging
11651: through my mailbox to extract your names is on my to-do list). Since the
11652: release of Gforth-0.4.0 Neal Crook worked on the manual.
11653: 
11654: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
11655: and autoconf, among others), and to the creators of the Internet: Gforth
11656: was developed across the Internet, and its authors did not meet
11657: physically for the first 4 years of development.
11658: 
11659: @section Pedigree
11660: @cindex pedigree of Gforth
11661: 
11662: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
11663: Dirk Zoller) will cross-fertilize each other. Of course, a significant
11664: part of the design of Gforth was prescribed by ANS Forth.
11665: 
11666: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
11667: 32 bit native code version of VolksForth for the Atari ST, written
11668: mostly by Dietrich Weineck.
11669: 
11670: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
11671: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
11672: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
11673: 
11674: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
11675: Forth-83 standard. !! Pedigree? When?
11676: 
11677: A team led by Bill Ragsdale implemented fig-Forth on many processors in
11678: 1979. Robert Selzer and Bill Ragsdale developed the original
11679: implementation of fig-Forth for the 6502 based on microForth.
11680: 
11681: The principal architect of microForth was Dean Sanderson. microForth was
11682: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
11683: the 1802, and subsequently implemented on the 8080, the 6800 and the
11684: Z80.
11685: 
11686: All earlier Forth systems were custom-made, usually by Charles Moore,
11687: who discovered (as he puts it) Forth during the late 60s. The first full
11688: Forth existed in 1971.
11689: 
11690: A part of the information in this section comes from @cite{The Evolution
11691: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
11692: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
11693: Notices 28(3), 1993.  You can find more historical and genealogical
11694: information about Forth there.
11695: 
11696: @node Forth-related information, Word Index, Origin, Top
11697: @appendix Other Forth-related information
11698: @cindex Forth-related information
11699: 
11700: @menu
11701: * Internet resources::
11702: * Books::
11703: * The Forth Interest Group::
11704: * Conferences::
11705: @end menu
11706: 
11707: 
11708: @node Internet resources, Books, Forth-related information, Forth-related information
11709: @section Internet resources
11710: @cindex internet resources
11711: 
11712: @cindex comp.lang.forth
11713: @cindex frequently asked questions
11714: There is an active news group (comp.lang.forth) discussing Forth and
11715: Forth-related issues. A frequently-asked-questions (FAQ) list
11716: is posted to the news group regularly, and archived at these sites:
11717: 
11718: @itemize @bullet
11719: @item
11720: @url{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
11721: @item
11722: @url{ftp://ftp.forth.org/pub/Forth/FAQ/}
11723: @end itemize
11724: 
11725: The FAQ list should be considered mandatory reading before posting to
11726: the news group.
11727: 
11728: Here are some other web sites holding Forth-related material:
11729: 
11730: @itemize @bullet
11731: @item
11732: @url{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
11733: @item
11734: @url{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
11735: @item
11736: @url{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
11737: @item
11738: @url{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
11739: Research page, including links to the Journal of Forth Application and
11740: Research (JFAR) and a searchable Forth bibliography.
11741: @end itemize
11742: 
11743: 
11744: @node Books, The Forth Interest Group, Internet resources, Forth-related information
11745: @section Books
11746: @cindex books on Forth
11747: 
11748: As the Standard is relatively new, there are not many books out yet. It
11749: is not recommended to learn Forth by using Gforth and a book that is not
11750: written for ANS Forth, as you will not know your mistakes from the
11751: deviations of the book. However, books based on the Forth-83 standard
11752: should be ok, because ANS Forth is primarily an extension of Forth-83.
11753: Refer to the Forth FAQ for details of Forth-related books.
11754: 
11755: @cindex standard document for ANS Forth
11756: @cindex ANS Forth document
11757: The definite reference if you want to write ANS Forth programs is, of
11758: course, the ANS Forth document. It is available in printed form from the
11759: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
11760: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
11761: $200. You can also get it from Global Engineering Documents (Tel.: USA
11762: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
11763: 
11764: @cite{dpANS6}, the last draft of the standard, which was then submitted
11765: to ANSI for publication is available electronically and for free in some
11766: MS Word format, and it has been converted to HTML
11767: (@url{http://www.taygeta.com/forth/dpans.html}; this HTML version also
11768: includes the answers to Requests for Interpretation (RFIs). Some
11769: pointers to these versions can be found through
11770: @*@url{http://www.complang.tuwien.ac.at/projects/forth.html}.
11771: 
11772: 
11773: @node The Forth Interest Group, Conferences, Books, Forth-related information
11774: @section The Forth Interest Group
11775: @cindex Forth interest group (FIG)
11776: 
11777: The Forth Interest Group (FIG) is a world-wide, non-profit,
11778: member-supported organisation. It publishes a regular magazine,
11779: @var{FORTH Dimensions}, and offers other benefits of membership. You can
11780: contact the FIG through their office email address:
11781: @email{office@@forth.org} or by visiting their web site at
11782: @url{http://www.forth.org/}. This web site also includes links to FIG
11783: chapters in other countries and American cities
11784: (@url{http://www.forth.org/chapters.html}).
11785: 
11786: @node Conferences, , The Forth Interest Group, Forth-related information
11787: @section Conferences
11788: @cindex Conferences
11789: 
11790: There are several regular conferences related to Forth. They are all
11791: well-publicised in @var{FORTH Dimensions} and on the comp.lang.forth
11792: news group:
11793: 
11794: @itemize @bullet
11795: @item
11796: FORML -- the Forth modification laboratory convenes every year near
11797: Monterey, California.
11798: @item
11799: The Rochester Forth Conference -- an annual conference traditionally
11800: held in Rochester, New York.
11801: @item
11802: EuroForth -- this European conference takes place annually.
11803: @end itemize
11804: 
11805: 
11806: @node Word Index, Name Index, Forth-related information, Top
11807: @unnumbered Word Index
11808: 
11809: This index is a list of Forth words that have ``glossary'' entries
11810: within this manual. Each word is listed with its stack effect and
11811: wordset.
11812: 
11813: @printindex fn
11814: 
11815: @node Name Index, Concept Index, Word Index, Top
11816: @unnumbered Name Index
11817: 
11818: This index is a list of Forth words that have ``glossary'' entries
11819: within this manual.
11820: 
11821: @printindex ky
11822: 
11823: @node Concept Index,  , Name Index, Top
11824: @unnumbered Concept and Word Index
11825: 
11826: Not all entries listed in this index are present verbatim in the
11827: text. This index also duplicates, in abbreviated form, all of the words
11828: listed in the Word Index (only the names are listed for the words here).
11829: 
11830: @printindex cp
11831: 
11832: @contents
11833: @bye
11834: 

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