File:  [gforth] / gforth / doc / gforth.ds
Revision 1.7: download - view: text, annotated - select for diffs
Sun Aug 3 20:21:54 1997 UTC (26 years, 8 months ago) by pazsan
Branches: MAIN
CVS tags: HEAD
Added OOF documentation
Added scope prefix to glossary generator to document different occurances
of the same word

    1: \input texinfo   @c -*-texinfo-*-
    2: @comment The source is gforth.ds, from which gforth.texi is generated
    3: @comment %**start of header (This is for running Texinfo on a region.)
    4: @setfilename gforth.info
    5: @settitle Gforth Manual
    6: @dircategory GNU programming tools
    7: @direntry
    8: * Gforth: (gforth).             A fast interpreter for the Forth language.
    9: @end direntry
   10: @comment @setchapternewpage odd
   11: @macro progstyle {TEXT}
   12: @quotation
   13: {Programming style note:} \TEXT\
   14: @end quotation
   15: @end macro
   16: @comment %**end of header (This is for running Texinfo on a region.)
   17: 
   18: @ifinfo
   19: This file documents Gforth 0.4
   20: 
   21: Copyright @copyright{} 1995-1997 Free Software Foundation, Inc.
   22: 
   23:      Permission is granted to make and distribute verbatim copies of
   24:      this manual provided the copyright notice and this permission notice
   25:      are preserved on all copies.
   26:      
   27: @ignore
   28:      Permission is granted to process this file through TeX and print the
   29:      results, provided the printed document carries a copying permission
   30:      notice identical to this one except for the removal of this paragraph
   31:      (this paragraph not being relevant to the printed manual).
   32:      
   33: @end ignore
   34:      Permission is granted to copy and distribute modified versions of this
   35:      manual under the conditions for verbatim copying, provided also that the
   36:      sections entitled "Distribution" and "General Public License" are
   37:      included exactly as in the original, and provided that the entire
   38:      resulting derived work is distributed under the terms of a permission
   39:      notice identical to this one.
   40:      
   41:      Permission is granted to copy and distribute translations of this manual
   42:      into another language, under the above conditions for modified versions,
   43:      except that the sections entitled "Distribution" and "General Public
   44:      License" may be included in a translation approved by the author instead
   45:      of in the original English.
   46: @end ifinfo
   47: 
   48: @finalout
   49: @titlepage
   50: @sp 10
   51: @center @titlefont{Gforth Manual}
   52: @sp 2
   53: @center for version 0.4
   54: @sp 2
   55: @center Anton Ertl
   56: @center Bernd Paysan
   57: @center Jens Wilke
   58: @sp 3
   59: @center This manual is permanently under construction
   60: 
   61: @comment  The following two commands start the copyright page.
   62: @page
   63: @vskip 0pt plus 1filll
   64: Copyright @copyright{} 1995--1997 Free Software Foundation, Inc.
   65: 
   66: @comment !! Published by ... or You can get a copy of this manual ...
   67: 
   68:      Permission is granted to make and distribute verbatim copies of
   69:      this manual provided the copyright notice and this permission notice
   70:      are preserved on all copies.
   71:      
   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 titlepage
   85: 
   86: 
   87: @node Top, License, (dir), (dir)
   88: @ifinfo
   89: Gforth is a free implementation of ANS Forth available on many
   90: personal machines. This manual corresponds to version 0.4.
   91: @end ifinfo
   92: 
   93: @menu
   94: * License::                     
   95: * Goals::                       About the Gforth Project
   96: * Other Books::                 Things you might want to read
   97: * Invoking Gforth::             Starting Gforth
   98: * Words::                       Forth words available in Gforth
   99: * Tools::                       Programming tools
  100: * ANS conformance::             Implementation-defined options etc.
  101: * Model::                       The abstract machine of Gforth
  102: * Integrating Gforth::          Forth as scripting language for applications
  103: * Emacs and Gforth::            The Gforth Mode
  104: * Image Files::                 @code{.fi} files contain compiled code
  105: * Engine::                      The inner interpreter and the primitives
  106: * Bugs::                        How to report them
  107: * Origin::                      Authors and ancestors of Gforth
  108: * Word Index::                  An item for each Forth word
  109: * Concept Index::               A menu covering many topics
  110: @end menu
  111: 
  112: @node License, Goals, Top, Top
  113: @unnumbered GNU GENERAL PUBLIC LICENSE
  114: @center Version 2, June 1991
  115: 
  116: @display
  117: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
  118: 675 Mass Ave, Cambridge, MA 02139, USA
  119: 
  120: Everyone is permitted to copy and distribute verbatim copies
  121: of this license document, but changing it is not allowed.
  122: @end display
  123: 
  124: @unnumberedsec Preamble
  125: 
  126:   The licenses for most software are designed to take away your
  127: freedom to share and change it.  By contrast, the GNU General Public
  128: License is intended to guarantee your freedom to share and change free
  129: software---to make sure the software is free for all its users.  This
  130: General Public License applies to most of the Free Software
  131: Foundation's software and to any other program whose authors commit to
  132: using it.  (Some other Free Software Foundation software is covered by
  133: the GNU Library General Public License instead.)  You can apply it to
  134: your programs, too.
  135: 
  136:   When we speak of free software, we are referring to freedom, not
  137: price.  Our General Public Licenses are designed to make sure that you
  138: have the freedom to distribute copies of free software (and charge for
  139: this service if you wish), that you receive source code or can get it
  140: if you want it, that you can change the software or use pieces of it
  141: in new free programs; and that you know you can do these things.
  142: 
  143:   To protect your rights, we need to make restrictions that forbid
  144: anyone to deny you these rights or to ask you to surrender the rights.
  145: These restrictions translate to certain responsibilities for you if you
  146: distribute copies of the software, or if you modify it.
  147: 
  148:   For example, if you distribute copies of such a program, whether
  149: gratis or for a fee, you must give the recipients all the rights that
  150: you have.  You must make sure that they, too, receive or can get the
  151: source code.  And you must show them these terms so they know their
  152: rights.
  153: 
  154:   We protect your rights with two steps: (1) copyright the software, and
  155: (2) offer you this license which gives you legal permission to copy,
  156: distribute and/or modify the software.
  157: 
  158:   Also, for each author's protection and ours, we want to make certain
  159: that everyone understands that there is no warranty for this free
  160: software.  If the software is modified by someone else and passed on, we
  161: want its recipients to know that what they have is not the original, so
  162: that any problems introduced by others will not reflect on the original
  163: authors' reputations.
  164: 
  165:   Finally, any free program is threatened constantly by software
  166: patents.  We wish to avoid the danger that redistributors of a free
  167: program will individually obtain patent licenses, in effect making the
  168: program proprietary.  To prevent this, we have made it clear that any
  169: patent must be licensed for everyone's free use or not licensed at all.
  170: 
  171:   The precise terms and conditions for copying, distribution and
  172: modification follow.
  173: 
  174: @iftex
  175: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  176: @end iftex
  177: @ifinfo
  178: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  179: @end ifinfo
  180: 
  181: @enumerate 0
  182: @item
  183: This License applies to any program or other work which contains
  184: a notice placed by the copyright holder saying it may be distributed
  185: under the terms of this General Public License.  The ``Program'', below,
  186: refers to any such program or work, and a ``work based on the Program''
  187: means either the Program or any derivative work under copyright law:
  188: that is to say, a work containing the Program or a portion of it,
  189: either verbatim or with modifications and/or translated into another
  190: language.  (Hereinafter, translation is included without limitation in
  191: the term ``modification''.)  Each licensee is addressed as ``you''.
  192: 
  193: Activities other than copying, distribution and modification are not
  194: covered by this License; they are outside its scope.  The act of
  195: running the Program is not restricted, and the output from the Program
  196: is covered only if its contents constitute a work based on the
  197: Program (independent of having been made by running the Program).
  198: Whether that is true depends on what the Program does.
  199: 
  200: @item
  201: You may copy and distribute verbatim copies of the Program's
  202: source code as you receive it, in any medium, provided that you
  203: conspicuously and appropriately publish on each copy an appropriate
  204: copyright notice and disclaimer of warranty; keep intact all the
  205: notices that refer to this License and to the absence of any warranty;
  206: and give any other recipients of the Program a copy of this License
  207: along with the Program.
  208: 
  209: You may charge a fee for the physical act of transferring a copy, and
  210: you may at your option offer warranty protection in exchange for a fee.
  211: 
  212: @item
  213: You may modify your copy or copies of the Program or any portion
  214: of it, thus forming a work based on the Program, and copy and
  215: distribute such modifications or work under the terms of Section 1
  216: above, provided that you also meet all of these conditions:
  217: 
  218: @enumerate a
  219: @item
  220: You must cause the modified files to carry prominent notices
  221: stating that you changed the files and the date of any change.
  222: 
  223: @item
  224: You must cause any work that you distribute or publish, that in
  225: whole or in part contains or is derived from the Program or any
  226: part thereof, to be licensed as a whole at no charge to all third
  227: parties under the terms of this License.
  228: 
  229: @item
  230: If the modified program normally reads commands interactively
  231: when run, you must cause it, when started running for such
  232: interactive use in the most ordinary way, to print or display an
  233: announcement including an appropriate copyright notice and a
  234: notice that there is no warranty (or else, saying that you provide
  235: a warranty) and that users may redistribute the program under
  236: these conditions, and telling the user how to view a copy of this
  237: License.  (Exception: if the Program itself is interactive but
  238: does not normally print such an announcement, your work based on
  239: the Program is not required to print an announcement.)
  240: @end enumerate
  241: 
  242: These requirements apply to the modified work as a whole.  If
  243: identifiable sections of that work are not derived from the Program,
  244: and can be reasonably considered independent and separate works in
  245: themselves, then this License, and its terms, do not apply to those
  246: sections when you distribute them as separate works.  But when you
  247: distribute the same sections as part of a whole which is a work based
  248: on the Program, the distribution of the whole must be on the terms of
  249: this License, whose permissions for other licensees extend to the
  250: entire whole, and thus to each and every part regardless of who wrote it.
  251: 
  252: Thus, it is not the intent of this section to claim rights or contest
  253: your rights to work written entirely by you; rather, the intent is to
  254: exercise the right to control the distribution of derivative or
  255: collective works based on the Program.
  256: 
  257: In addition, mere aggregation of another work not based on the Program
  258: with the Program (or with a work based on the Program) on a volume of
  259: a storage or distribution medium does not bring the other work under
  260: the scope of this License.
  261: 
  262: @item
  263: You may copy and distribute the Program (or a work based on it,
  264: under Section 2) in object code or executable form under the terms of
  265: Sections 1 and 2 above provided that you also do one of the following:
  266: 
  267: @enumerate a
  268: @item
  269: Accompany it with the complete corresponding machine-readable
  270: source code, which must be distributed under the terms of Sections
  271: 1 and 2 above on a medium customarily used for software interchange; or,
  272: 
  273: @item
  274: Accompany it with a written offer, valid for at least three
  275: years, to give any third party, for a charge no more than your
  276: cost of physically performing source distribution, a complete
  277: machine-readable copy of the corresponding source code, to be
  278: distributed under the terms of Sections 1 and 2 above on a medium
  279: customarily used for software interchange; or,
  280: 
  281: @item
  282: Accompany it with the information you received as to the offer
  283: to distribute corresponding source code.  (This alternative is
  284: allowed only for noncommercial distribution and only if you
  285: received the program in object code or executable form with such
  286: an offer, in accord with Subsection b above.)
  287: @end enumerate
  288: 
  289: The source code for a work means the preferred form of the work for
  290: making modifications to it.  For an executable work, complete source
  291: code means all the source code for all modules it contains, plus any
  292: associated interface definition files, plus the scripts used to
  293: control compilation and installation of the executable.  However, as a
  294: special exception, the source code distributed need not include
  295: anything that is normally distributed (in either source or binary
  296: form) with the major components (compiler, kernel, and so on) of the
  297: operating system on which the executable runs, unless that component
  298: itself accompanies the executable.
  299: 
  300: If distribution of executable or object code is made by offering
  301: access to copy from a designated place, then offering equivalent
  302: access to copy the source code from the same place counts as
  303: distribution of the source code, even though third parties are not
  304: compelled to copy the source along with the object code.
  305: 
  306: @item
  307: You may not copy, modify, sublicense, or distribute the Program
  308: except as expressly provided under this License.  Any attempt
  309: otherwise to copy, modify, sublicense or distribute the Program is
  310: void, and will automatically terminate your rights under this License.
  311: However, parties who have received copies, or rights, from you under
  312: this License will not have their licenses terminated so long as such
  313: parties remain in full compliance.
  314: 
  315: @item
  316: You are not required to accept this License, since you have not
  317: signed it.  However, nothing else grants you permission to modify or
  318: distribute the Program or its derivative works.  These actions are
  319: prohibited by law if you do not accept this License.  Therefore, by
  320: modifying or distributing the Program (or any work based on the
  321: Program), you indicate your acceptance of this License to do so, and
  322: all its terms and conditions for copying, distributing or modifying
  323: the Program or works based on it.
  324: 
  325: @item
  326: Each time you redistribute the Program (or any work based on the
  327: Program), the recipient automatically receives a license from the
  328: original licensor to copy, distribute or modify the Program subject to
  329: these terms and conditions.  You may not impose any further
  330: restrictions on the recipients' exercise of the rights granted herein.
  331: You are not responsible for enforcing compliance by third parties to
  332: this License.
  333: 
  334: @item
  335: If, as a consequence of a court judgment or allegation of patent
  336: infringement or for any other reason (not limited to patent issues),
  337: conditions are imposed on you (whether by court order, agreement or
  338: otherwise) that contradict the conditions of this License, they do not
  339: excuse you from the conditions of this License.  If you cannot
  340: distribute so as to satisfy simultaneously your obligations under this
  341: License and any other pertinent obligations, then as a consequence you
  342: may not distribute the Program at all.  For example, if a patent
  343: license would not permit royalty-free redistribution of the Program by
  344: all those who receive copies directly or indirectly through you, then
  345: the only way you could satisfy both it and this License would be to
  346: refrain entirely from distribution of the Program.
  347: 
  348: If any portion of this section is held invalid or unenforceable under
  349: any particular circumstance, the balance of the section is intended to
  350: apply and the section as a whole is intended to apply in other
  351: circumstances.
  352: 
  353: It is not the purpose of this section to induce you to infringe any
  354: patents or other property right claims or to contest validity of any
  355: such claims; this section has the sole purpose of protecting the
  356: integrity of the free software distribution system, which is
  357: implemented by public license practices.  Many people have made
  358: generous contributions to the wide range of software distributed
  359: through that system in reliance on consistent application of that
  360: system; it is up to the author/donor to decide if he or she is willing
  361: to distribute software through any other system and a licensee cannot
  362: impose that choice.
  363: 
  364: This section is intended to make thoroughly clear what is believed to
  365: be a consequence of the rest of this License.
  366: 
  367: @item
  368: If the distribution and/or use of the Program is restricted in
  369: certain countries either by patents or by copyrighted interfaces, the
  370: original copyright holder who places the Program under this License
  371: may add an explicit geographical distribution limitation excluding
  372: those countries, so that distribution is permitted only in or among
  373: countries not thus excluded.  In such case, this License incorporates
  374: the limitation as if written in the body of this License.
  375: 
  376: @item
  377: The Free Software Foundation may publish revised and/or new versions
  378: of the General Public License from time to time.  Such new versions will
  379: be similar in spirit to the present version, but may differ in detail to
  380: address new problems or concerns.
  381: 
  382: Each version is given a distinguishing version number.  If the Program
  383: specifies a version number of this License which applies to it and ``any
  384: later version'', you have the option of following the terms and conditions
  385: either of that version or of any later version published by the Free
  386: Software Foundation.  If the Program does not specify a version number of
  387: this License, you may choose any version ever published by the Free Software
  388: Foundation.
  389: 
  390: @item
  391: If you wish to incorporate parts of the Program into other free
  392: programs whose distribution conditions are different, write to the author
  393: to ask for permission.  For software which is copyrighted by the Free
  394: Software Foundation, write to the Free Software Foundation; we sometimes
  395: make exceptions for this.  Our decision will be guided by the two goals
  396: of preserving the free status of all derivatives of our free software and
  397: of promoting the sharing and reuse of software generally.
  398: 
  399: @iftex
  400: @heading NO WARRANTY
  401: @end iftex
  402: @ifinfo
  403: @center NO WARRANTY
  404: @end ifinfo
  405: 
  406: @item
  407: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
  408: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
  409: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
  410: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
  411: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  412: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
  413: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
  414: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
  415: REPAIR OR CORRECTION.
  416: 
  417: @item
  418: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
  419: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
  420: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
  421: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
  422: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
  423: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
  424: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
  425: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
  426: POSSIBILITY OF SUCH DAMAGES.
  427: @end enumerate
  428: 
  429: @iftex
  430: @heading END OF TERMS AND CONDITIONS
  431: @end iftex
  432: @ifinfo
  433: @center END OF TERMS AND CONDITIONS
  434: @end ifinfo
  435: 
  436: @page
  437: @unnumberedsec How to Apply These Terms to Your New Programs
  438: 
  439:   If you develop a new program, and you want it to be of the greatest
  440: possible use to the public, the best way to achieve this is to make it
  441: free software which everyone can redistribute and change under these terms.
  442: 
  443:   To do so, attach the following notices to the program.  It is safest
  444: to attach them to the start of each source file to most effectively
  445: convey the exclusion of warranty; and each file should have at least
  446: the ``copyright'' line and a pointer to where the full notice is found.
  447: 
  448: @smallexample
  449: @var{one line to give the program's name and a brief idea of what it does.}
  450: Copyright (C) 19@var{yy}  @var{name of author}
  451: 
  452: This program is free software; you can redistribute it and/or modify 
  453: it under the terms of the GNU General Public License as published by 
  454: the Free Software Foundation; either version 2 of the License, or 
  455: (at your option) any later version.
  456: 
  457: This program is distributed in the hope that it will be useful,
  458: but WITHOUT ANY WARRANTY; without even the implied warranty of
  459: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  460: GNU General Public License for more details.
  461: 
  462: You should have received a copy of the GNU General Public License
  463: along with this program; if not, write to the Free Software
  464: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  465: @end smallexample
  466: 
  467: Also add information on how to contact you by electronic and paper mail.
  468: 
  469: If the program is interactive, make it output a short notice like this
  470: when it starts in an interactive mode:
  471: 
  472: @smallexample
  473: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
  474: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
  475: type `show w'.  
  476: This is free software, and you are welcome to redistribute it 
  477: under certain conditions; type `show c' for details.
  478: @end smallexample
  479: 
  480: The hypothetical commands @samp{show w} and @samp{show c} should show
  481: the appropriate parts of the General Public License.  Of course, the
  482: commands you use may be called something other than @samp{show w} and
  483: @samp{show c}; they could even be mouse-clicks or menu items---whatever
  484: suits your program.
  485: 
  486: You should also get your employer (if you work as a programmer) or your
  487: school, if any, to sign a ``copyright disclaimer'' for the program, if
  488: necessary.  Here is a sample; alter the names:
  489: 
  490: @smallexample
  491: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  492: `Gnomovision' (which makes passes at compilers) written by James Hacker.
  493: 
  494: @var{signature of Ty Coon}, 1 April 1989
  495: Ty Coon, President of Vice
  496: @end smallexample
  497: 
  498: This General Public License does not permit incorporating your program into
  499: proprietary programs.  If your program is a subroutine library, you may
  500: consider it more useful to permit linking proprietary applications with the
  501: library.  If this is what you want to do, use the GNU Library General
  502: Public License instead of this License.
  503: 
  504: @iftex
  505: @unnumbered Preface
  506: @cindex Preface
  507: This manual documents Gforth. The reader is expected to know
  508: Forth. This manual is primarily a reference manual. @xref{Other Books}
  509: for introductory material.
  510: @end iftex
  511: 
  512: @node    Goals, Other Books, License, Top
  513: @comment node-name,     next,           previous, up
  514: @chapter Goals of Gforth
  515: @cindex Goals
  516: The goal of the Gforth Project is to develop a standard model for
  517: ANS Forth. This can be split into several subgoals:
  518: 
  519: @itemize @bullet
  520: @item
  521: Gforth should conform to the Forth standard (ANS Forth).
  522: @item
  523: It should be a model, i.e. it should define all the
  524: implementation-dependent things.
  525: @item
  526: It should become standard, i.e. widely accepted and used. This goal
  527: is the most difficult one.
  528: @end itemize
  529: 
  530: To achieve these goals Gforth should be
  531: @itemize @bullet
  532: @item
  533: Similar to previous models (fig-Forth, F83)
  534: @item
  535: Powerful. It should provide for all the things that are considered
  536: necessary today and even some that are not yet considered necessary.
  537: @item
  538: Efficient. It should not get the reputation of being exceptionally
  539: slow.
  540: @item
  541: Free.
  542: @item
  543: Available on many machines/easy to port.
  544: @end itemize
  545: 
  546: Have we achieved these goals? Gforth conforms to the ANS Forth
  547: standard. It may be considered a model, but we have not yet documented
  548: which parts of the model are stable and which parts we are likely to
  549: change. It certainly has not yet become a de facto standard. It has some
  550: similarities and some differences to previous models. It has some
  551: powerful features, but not yet everything that we envisioned. We
  552: certainly have achieved our execution speed goals (@pxref{Performance}).
  553: It is free and available on many machines.
  554: 
  555: @node Other Books, Invoking Gforth, Goals, Top
  556: @chapter Other books on ANS Forth
  557: @cindex books on Forth
  558: 
  559: As the standard is relatively new, there are not many books out yet. It
  560: is not recommended to learn Forth by using Gforth and a book that is
  561: not written for ANS Forth, as you will not know your mistakes from the
  562: deviations of the book.
  563: 
  564: @cindex standard document for ANS Forth
  565: @cindex ANS Forth document
  566: There is, of course, the standard, the definite reference if you want to
  567: write ANS Forth programs. It is available in printed form from the
  568: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
  569: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about $200. You
  570: can also get it from Global Engineering Documents (Tel.: USA (800)
  571: 854-7179; Fax.: (303) 843-9880) for about $300.
  572: 
  573: @cite{dpANS6}, the last draft of the standard, which was then submitted to ANSI
  574: for publication is available electronically and for free in some MS Word
  575: format, and it has been converted to HTML. Some pointers to these
  576: versions can be found through
  577: @*@url{http://www.complang.tuwien.ac.at/projects/forth.html}.
  578: 
  579: @cindex introductory book
  580: @cindex book, introductory
  581: @cindex Woehr, Jack: @cite{Forth: The New Model}
  582: @cindex @cite{Forth: The new model} (book)
  583: @cite{Forth: The New Model} by Jack Woehr (Prentice-Hall, 1993) is an
  584: introductory book based on a draft version of the standard. It does not
  585: cover the whole standard. It also contains interesting background
  586: information (Jack Woehr was in the ANS Forth Technical Committee). It is
  587: not appropriate for complete newbies, but programmers experienced in
  588: other languages should find it ok.
  589: 
  590: @node Invoking Gforth, Words, Other Books, Top
  591: @chapter Invoking Gforth
  592: @cindex invoking Gforth
  593: @cindex running Gforth
  594: @cindex command-line options
  595: @cindex options on the command line
  596: @cindex flags on the command line
  597: 
  598: You will usually just say @code{gforth}. In many other cases the default
  599: Gforth image will be invoked like this:
  600: 
  601: @example
  602: gforth [files] [-e forth-code]
  603: @end example
  604: 
  605: executing the contents of the files and the Forth code in the order they
  606: are given.
  607: 
  608: In general, the command line looks like this:
  609: 
  610: @example
  611: gforth [initialization options] [image-specific options]
  612: @end example
  613: 
  614: The initialization options must come before the rest of the command
  615: line. They are:
  616: 
  617: @table @code
  618: @cindex -i, command-line option
  619: @cindex --image-file, command-line option
  620: @item --image-file @var{file}
  621: @itemx -i @var{file}
  622: Loads the Forth image @var{file} instead of the default
  623: @file{gforth.fi} (@pxref{Image Files}).
  624: 
  625: @cindex --path, command-line option
  626: @cindex -p, command-line option
  627: @item --path @var{path}
  628: @itemx -p @var{path}
  629: Uses @var{path} for searching the image file and Forth source code files
  630: instead of the default in the environment variable @code{GFORTHPATH} or
  631: the path specified at installation time (e.g.,
  632: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
  633: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
  634: 
  635: @cindex --dictionary-size, command-line option
  636: @cindex -m, command-line option
  637: @cindex @var{size} parameters for command-line options
  638: @cindex size of the dictionary and the stacks
  639: @item --dictionary-size @var{size}
  640: @itemx -m @var{size}
  641: Allocate @var{size} space for the Forth dictionary space instead of
  642: using the default specified in the image (typically 256K). The
  643: @var{size} specification consists of an integer and a unit (e.g.,
  644: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
  645: size, in this case Cells), @code{k} (kilobytes), and @code{M}
  646: (Megabytes). If no unit is specified, @code{e} is used.
  647: 
  648: @cindex --data-stack-size, command-line option
  649: @cindex -d, command-line option
  650: @item --data-stack-size @var{size}
  651: @itemx -d @var{size}
  652: Allocate @var{size} space for the data stack instead of using the
  653: default specified in the image (typically 16K).
  654: 
  655: @cindex --return-stack-size, command-line option
  656: @cindex -r, command-line option
  657: @item --return-stack-size @var{size}
  658: @itemx -r @var{size}
  659: Allocate @var{size} space for the return stack instead of using the
  660: default specified in the image (typically 15K).
  661: 
  662: @cindex --fp-stack-size, command-line option
  663: @cindex -f, command-line option
  664: @item --fp-stack-size @var{size}
  665: @itemx -f @var{size}
  666: Allocate @var{size} space for the floating point stack instead of
  667: using the default specified in the image (typically 15.5K). In this case
  668: the unit specifier @code{e} refers to floating point numbers.
  669: 
  670: @cindex --locals-stack-size, command-line option
  671: @cindex -l, command-line option
  672: @item --locals-stack-size @var{size}
  673: @itemx -l @var{size}
  674: Allocate @var{size} space for the locals stack instead of using the
  675: default specified in the image (typically 14.5K).
  676: 
  677: @cindex -h, command-line option
  678: @cindex --help, command-line option
  679: @item --help
  680: @itemx -h
  681: Print a message about the command-line options
  682: 
  683: @cindex -v, command-line option
  684: @cindex --version, command-line option
  685: @item --version
  686: @itemx -v
  687: Print version and exit
  688: 
  689: @cindex --debug, command-line option
  690: @item --debug
  691: Print some information useful for debugging on startup.
  692: 
  693: @cindex --offset-image, command-line option
  694: @item --offset-image
  695: Start the dictionary at a slightly different position than would be used
  696: otherwise (useful for creating data-relocatable images,
  697: @pxref{Data-Relocatable Image Files}).
  698: 
  699: @cindex --no-offset-im, command-line option
  700: @item --no-offset-im
  701: Start the dictionary at the normal position.
  702: 
  703: @cindex --clear-dictionary, command-line option
  704: @item --clear-dictionary
  705: Initialize all bytes in the dictionary to 0 before loading the image
  706: (@pxref{Data-Relocatable Image Files}).
  707: 
  708: @cindex --die-on-signal, command-line-option
  709: @item --die-on-signal
  710: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
  711: or the segmentation violation SIGSEGV) by translating it into a Forth
  712: @code{THROW}. With this option, Gforth exits if it receives such a
  713: signal. This option is useful when the engine and/or the image might be
  714: severely broken (such that it causes another signal before recovering
  715: from the first); this option avoids endless loops in such cases.
  716: @end table
  717: 
  718: @cindex loading files at startup
  719: @cindex executing code on startup
  720: @cindex batch processing with Gforth
  721: As explained above, the image-specific command-line arguments for the
  722: default image @file{gforth.fi} consist of a sequence of filenames and
  723: @code{-e @var{forth-code}} options that are interpreted in the sequence
  724: in which they are given. The @code{-e @var{forth-code}} or
  725: @code{--evaluate @var{forth-code}} option evaluates the forth
  726: code. This option takes only one argument; if you want to evaluate more
  727: Forth words, you have to quote them or use several @code{-e}s. To exit
  728: after processing the command line (instead of entering interactive mode)
  729: append @code{-e bye} to the command line.
  730: 
  731: @cindex versions, invoking other versions of Gforth
  732: If you have several versions of Gforth installed, @code{gforth} will
  733: invoke the version that was installed last. @code{gforth-@var{version}}
  734: invokes a specific version. You may want to use the option
  735: @code{--path}, if your environment contains the variable
  736: @code{GFORTHPATH}.
  737: 
  738: Not yet implemented:
  739: On startup the system first executes the system initialization file
  740: (unless the option @code{--no-init-file} is given; note that the system
  741: resulting from using this option may not be ANS Forth conformant). Then
  742: the user initialization file @file{.gforth.fs} is executed, unless the
  743: option @code{--no-rc} is given; this file is first searched in @file{.},
  744: then in @file{~}, then in the normal path (see above).
  745: 
  746: @node Words, Tools, Invoking Gforth, Top
  747: @chapter Forth Words
  748: @cindex Words
  749: 
  750: @menu
  751: * Notation::                    
  752: * Arithmetic::                  
  753: * Stack Manipulation::          
  754: * Memory::                      
  755: * Control Structures::          
  756: * Locals::                      
  757: * Defining Words::              
  758: * Structures::                  
  759: * Objects::
  760: * Object Oriented Forth::                     
  761: * Tokens for Words::            
  762: * Wordlists::                   
  763: * Files::                       
  764: * Blocks::                      
  765: * Other I/O::                   
  766: * Programming Tools::           
  767: * Assembler and Code Words::    
  768: * Threading Words::             
  769: * Including Files::             
  770: @end menu
  771: 
  772: @node Notation, Arithmetic, Words, Words
  773: @section Notation
  774: @cindex notation of glossary entries
  775: @cindex format of glossary entries
  776: @cindex glossary notation format
  777: @cindex word glossary entry format
  778: 
  779: The Forth words are described in this section in the glossary notation
  780: that has become a de-facto standard for Forth texts, i.e.,
  781: 
  782: @format
  783: @var{word}     @var{Stack effect}   @var{wordset}   @var{pronunciation}
  784: @end format
  785: @var{Description}
  786: 
  787: @table @var
  788: @item word
  789: @cindex case insensitivity
  790: The name of the word. BTW, Gforth is case insensitive, so you can
  791: type the words in in lower case (However, @pxref{core-idef}).
  792: 
  793: @item Stack effect
  794: @cindex stack effect
  795: The stack effect is written in the notation @code{@var{before} --
  796: @var{after}}, where @var{before} and @var{after} describe the top of
  797: stack entries before and after the execution of the word. The rest of
  798: the stack is not touched by the word. The top of stack is rightmost,
  799: i.e., a stack sequence is written as it is typed in. Note that Gforth
  800: uses a separate floating point stack, but a unified stack
  801: notation. Also, return stack effects are not shown in @var{stack
  802: effect}, but in @var{Description}. The name of a stack item describes
  803: the type and/or the function of the item. See below for a discussion of
  804: the types.
  805: 
  806: All words have two stack effects: A compile-time stack effect and a
  807: run-time stack effect. The compile-time stack-effect of most words is
  808: @var{ -- }. If the compile-time stack-effect of a word deviates from
  809: this standard behaviour, or the word does other unusual things at
  810: compile time, both stack effects are shown; otherwise only the run-time
  811: stack effect is shown.
  812: 
  813: @cindex pronounciation of words
  814: @item pronunciation
  815: How the word is pronounced.
  816: 
  817: @cindex wordset
  818: @item wordset
  819: The ANS Forth standard is divided into several wordsets. A standard
  820: system need not support all of them. So, the fewer wordsets your program
  821: uses the more portable it will be in theory. However, we suspect that
  822: most ANS Forth systems on personal machines will feature all
  823: wordsets. Words that are not defined in the ANS standard have
  824: @code{gforth} or @code{gforth-internal} as wordset. @code{gforth}
  825: describes words that will work in future releases of Gforth;
  826: @code{gforth-internal} words are more volatile. Environmental query
  827: strings are also displayed like words; you can recognize them by the
  828: @code{environment} in the wordset field.
  829: 
  830: @item Description
  831: A description of the behaviour of the word.
  832: @end table
  833: 
  834: @cindex types of stack items
  835: @cindex stack item types
  836: The type of a stack item is specified by the character(s) the name
  837: starts with:
  838: 
  839: @table @code
  840: @item f
  841: @cindex @code{f}, stack item type
  842: Boolean flags, i.e. @code{false} or @code{true}.
  843: @item c
  844: @cindex @code{c}, stack item type
  845: Char
  846: @item w
  847: @cindex @code{w}, stack item type
  848: Cell, can contain an integer or an address
  849: @item n
  850: @cindex @code{n}, stack item type
  851: signed integer
  852: @item u
  853: @cindex @code{u}, stack item type
  854: unsigned integer
  855: @item d
  856: @cindex @code{d}, stack item type
  857: double sized signed integer
  858: @item ud
  859: @cindex @code{ud}, stack item type
  860: double sized unsigned integer
  861: @item r
  862: @cindex @code{r}, stack item type
  863: Float (on the FP stack)
  864: @item a_
  865: @cindex @code{a_}, stack item type
  866: Cell-aligned address
  867: @item c_
  868: @cindex @code{c_}, stack item type
  869: Char-aligned address (note that a Char may have two bytes in Windows NT)
  870: @item f_
  871: @cindex @code{f_}, stack item type
  872: Float-aligned address
  873: @item df_
  874: @cindex @code{df_}, stack item type
  875: Address aligned for IEEE double precision float
  876: @item sf_
  877: @cindex @code{sf_}, stack item type
  878: Address aligned for IEEE single precision float
  879: @item xt
  880: @cindex @code{xt}, stack item type
  881: Execution token, same size as Cell
  882: @item wid
  883: @cindex @code{wid}, stack item type
  884: Wordlist ID, same size as Cell
  885: @item f83name
  886: @cindex @code{f83name}, stack item type
  887: Pointer to a name structure
  888: @item "
  889: @cindex @code{"}, stack item type
  890: string in the input stream (not the stack). The terminating character is
  891: a blank by default. If it is not a blank, it is shown in @code{<>}
  892: quotes.
  893: @end table
  894: 
  895: @node Arithmetic, Stack Manipulation, Notation, Words
  896: @section Arithmetic
  897: @cindex arithmetic words
  898: 
  899: @cindex division with potentially negative operands
  900: Forth arithmetic is not checked, i.e., you will not hear about integer
  901: overflow on addition or multiplication, you may hear about division by
  902: zero if you are lucky. The operator is written after the operands, but
  903: the operands are still in the original order. I.e., the infix @code{2-1}
  904: corresponds to @code{2 1 -}. Forth offers a variety of division
  905: operators. If you perform division with potentially negative operands,
  906: you do not want to use @code{/} or @code{/mod} with its undefined
  907: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
  908: former, @pxref{Mixed precision}).
  909: 
  910: @menu
  911: * Single precision::            
  912: * Bitwise operations::          
  913: * Mixed precision::             operations with single and double-cell integers
  914: * Double precision::            Double-cell integer arithmetic
  915: * Floating Point::              
  916: @end menu
  917: 
  918: @node Single precision, Bitwise operations, Arithmetic, Arithmetic
  919: @subsection Single precision
  920: @cindex single precision arithmetic words
  921: 
  922: doc-+
  923: doc--
  924: doc-*
  925: doc-/
  926: doc-mod
  927: doc-/mod
  928: doc-negate
  929: doc-abs
  930: doc-min
  931: doc-max
  932: 
  933: @node Bitwise operations, Mixed precision, Single precision, Arithmetic
  934: @subsection Bitwise operations
  935: @cindex bitwise operation words
  936: 
  937: doc-and
  938: doc-or
  939: doc-xor
  940: doc-invert
  941: doc-2*
  942: doc-2/
  943: 
  944: @node Mixed precision, Double precision, Bitwise operations, Arithmetic
  945: @subsection Mixed precision
  946: @cindex mixed precision arithmetic words
  947: 
  948: doc-m+
  949: doc-*/
  950: doc-*/mod
  951: doc-m*
  952: doc-um*
  953: doc-m*/
  954: doc-um/mod
  955: doc-fm/mod
  956: doc-sm/rem
  957: 
  958: @node Double precision, Floating Point, Mixed precision, Arithmetic
  959: @subsection Double precision
  960: @cindex double precision arithmetic words
  961: 
  962: @cindex double-cell numbers, input format
  963: @cindex input format for double-cell numbers
  964: The outer (aka text) interpreter converts numbers containing a dot into
  965: a double precision number. Note that only numbers with the dot as last
  966: character are standard-conforming.
  967: 
  968: doc-d+
  969: doc-d-
  970: doc-dnegate
  971: doc-dabs
  972: doc-dmin
  973: doc-dmax
  974: 
  975: @node Floating Point,  , Double precision, Arithmetic
  976: @subsection Floating Point
  977: @cindex floating point arithmetic words
  978: 
  979: @cindex floating-point numbers, input format
  980: @cindex input format for floating-point numbers
  981: The format of floating point numbers recognized by the outer (aka text)
  982: interpreter is: a signed decimal number, possibly containing a decimal
  983: point (@code{.}), followed by @code{E} or @code{e}, optionally followed
  984: by a signed integer (the exponent). E.g., @code{1e} is the same as
  985: @code{+1.0e+0}. Note that a number without @code{e}
  986: is not interpreted as floating-point number, but as double (if the
  987: number contains a @code{.}) or single precision integer. Also,
  988: conversions between string and floating point numbers always use base
  989: 10, irrespective of the value of @code{BASE}. If @code{BASE} contains a
  990: value greater then 14, the @code{E} may be interpreted as digit and the
  991: number will be interpreted as integer, unless it has a signed exponent
  992: (both @code{+} and @code{-} are allowed as signs).
  993: 
  994: @cindex angles in trigonometric operations
  995: @cindex trigonometric operations
  996: Angles in floating point operations are given in radians (a full circle
  997: has 2 pi radians). Note, that Gforth has a separate floating point
  998: stack, but we use the unified notation.
  999: 
 1000: @cindex floating-point arithmetic, pitfalls
 1001: Floating point numbers have a number of unpleasant surprises for the
 1002: unwary (e.g., floating point addition is not associative) and even a few
 1003: for the wary. You should not use them unless you know what you are doing
 1004: or you don't care that the results you get are totally bogus. If you
 1005: want to learn about the problems of floating point numbers (and how to
 1006: avoid them), you might start with @cite{David Goldberg, What Every
 1007: Computer Scientist Should Know About Floating-Point Arithmetic, ACM
 1008: Computing Surveys 23(1):5@minus{}48, March 1991}.
 1009: 
 1010: doc-f+
 1011: doc-f-
 1012: doc-f*
 1013: doc-f/
 1014: doc-fnegate
 1015: doc-fabs
 1016: doc-fmax
 1017: doc-fmin
 1018: doc-floor
 1019: doc-fround
 1020: doc-f**
 1021: doc-fsqrt
 1022: doc-fexp
 1023: doc-fexpm1
 1024: doc-fln
 1025: doc-flnp1
 1026: doc-flog
 1027: doc-falog
 1028: doc-fsin
 1029: doc-fcos
 1030: doc-fsincos
 1031: doc-ftan
 1032: doc-fasin
 1033: doc-facos
 1034: doc-fatan
 1035: doc-fatan2
 1036: doc-fsinh
 1037: doc-fcosh
 1038: doc-ftanh
 1039: doc-fasinh
 1040: doc-facosh
 1041: doc-fatanh
 1042: 
 1043: @node Stack Manipulation, Memory, Arithmetic, Words
 1044: @section Stack Manipulation
 1045: @cindex stack manipulation words
 1046: 
 1047: @cindex floating-point stack in the standard
 1048: Gforth has a data stack (aka parameter stack) for characters, cells,
 1049: addresses, and double cells, a floating point stack for floating point
 1050: numbers, a return stack for storing the return addresses of colon
 1051: definitions and other data, and a locals stack for storing local
 1052: variables. Note that while every sane Forth has a separate floating
 1053: point stack, this is not strictly required; an ANS Forth system could
 1054: theoretically keep floating point numbers on the data stack. As an
 1055: additional difficulty, you don't know how many cells a floating point
 1056: number takes. It is reportedly possible to write words in a way that
 1057: they work also for a unified stack model, but we do not recommend trying
 1058: it. Instead, just say that your program has an environmental dependency
 1059: on a separate FP stack.
 1060: 
 1061: @cindex return stack and locals
 1062: @cindex locals and return stack
 1063: Also, a Forth system is allowed to keep the local variables on the
 1064: return stack. This is reasonable, as local variables usually eliminate
 1065: the need to use the return stack explicitly. So, if you want to produce
 1066: a standard complying program and if you are using local variables in a
 1067: word, forget about return stack manipulations in that word (see the
 1068: standard document for the exact rules).
 1069: 
 1070: @menu
 1071: * Data stack::                  
 1072: * Floating point stack::        
 1073: * Return stack::                
 1074: * Locals stack::                
 1075: * Stack pointer manipulation::  
 1076: @end menu
 1077: 
 1078: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
 1079: @subsection Data stack
 1080: @cindex data stack manipulation words
 1081: @cindex stack manipulations words, data stack
 1082: 
 1083: doc-drop
 1084: doc-nip
 1085: doc-dup
 1086: doc-over
 1087: doc-tuck
 1088: doc-swap
 1089: doc-rot
 1090: doc--rot
 1091: doc-?dup
 1092: doc-pick
 1093: doc-roll
 1094: doc-2drop
 1095: doc-2nip
 1096: doc-2dup
 1097: doc-2over
 1098: doc-2tuck
 1099: doc-2swap
 1100: doc-2rot
 1101: 
 1102: @node Floating point stack, Return stack, Data stack, Stack Manipulation
 1103: @subsection Floating point stack
 1104: @cindex floating-point stack manipulation words
 1105: @cindex stack manipulation words, floating-point stack
 1106: 
 1107: doc-fdrop
 1108: doc-fnip
 1109: doc-fdup
 1110: doc-fover
 1111: doc-ftuck
 1112: doc-fswap
 1113: doc-frot
 1114: 
 1115: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
 1116: @subsection Return stack
 1117: @cindex return stack manipulation words
 1118: @cindex stack manipulation words, return stack
 1119: 
 1120: doc->r
 1121: doc-r>
 1122: doc-r@
 1123: doc-rdrop
 1124: doc-2>r
 1125: doc-2r>
 1126: doc-2r@
 1127: doc-2rdrop
 1128: 
 1129: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
 1130: @subsection Locals stack
 1131: 
 1132: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
 1133: @subsection Stack pointer manipulation
 1134: @cindex stack pointer manipulation words
 1135: 
 1136: doc-sp@
 1137: doc-sp!
 1138: doc-fp@
 1139: doc-fp!
 1140: doc-rp@
 1141: doc-rp!
 1142: doc-lp@
 1143: doc-lp!
 1144: 
 1145: @node Memory, Control Structures, Stack Manipulation, Words
 1146: @section Memory
 1147: @cindex Memory words
 1148: 
 1149: @menu
 1150: * Memory Access::      
 1151: * Address arithmetic::          
 1152: * Memory Blocks::         
 1153: @end menu
 1154: 
 1155: @node Memory Access, Address arithmetic, Memory, Memory
 1156: @subsection Memory Access
 1157: @cindex memory access words
 1158: 
 1159: doc-@
 1160: doc-!
 1161: doc-+!
 1162: doc-c@
 1163: doc-c!
 1164: doc-2@
 1165: doc-2!
 1166: doc-f@
 1167: doc-f!
 1168: doc-sf@
 1169: doc-sf!
 1170: doc-df@
 1171: doc-df!
 1172: 
 1173: @node Address arithmetic, Memory Blocks, Memory Access, Memory
 1174: @subsection Address arithmetic
 1175: @cindex address arithmetic words
 1176: 
 1177: ANS Forth does not specify the sizes of the data types. Instead, it
 1178: offers a number of words for computing sizes and doing address
 1179: arithmetic. Basically, address arithmetic is performed in terms of
 1180: address units (aus); on most systems the address unit is one byte. Note
 1181: that a character may have more than one au, so @code{chars} is no noop
 1182: (on systems where it is a noop, it compiles to nothing).
 1183: 
 1184: @cindex alignment of addresses for types
 1185: ANS Forth also defines words for aligning addresses for specific
 1186: types. Many computers require that accesses to specific data types
 1187: must only occur at specific addresses; e.g., that cells may only be
 1188: accessed at addresses divisible by 4. Even if a machine allows unaligned
 1189: accesses, it can usually perform aligned accesses faster. 
 1190: 
 1191: For the performance-conscious: alignment operations are usually only
 1192: necessary during the definition of a data structure, not during the
 1193: (more frequent) accesses to it.
 1194: 
 1195: ANS Forth defines no words for character-aligning addresses. This is not
 1196: an oversight, but reflects the fact that addresses that are not
 1197: char-aligned have no use in the standard and therefore will not be
 1198: created.
 1199: 
 1200: @cindex @code{CREATE} and alignment
 1201: The standard guarantees that addresses returned by @code{CREATE}d words
 1202: are cell-aligned; in addition, Gforth guarantees that these addresses
 1203: are aligned for all purposes.
 1204: 
 1205: Note that the standard defines a word @code{char}, which has nothing to
 1206: do with address arithmetic.
 1207: 
 1208: doc-chars
 1209: doc-char+
 1210: doc-cells
 1211: doc-cell+
 1212: doc-cell
 1213: doc-align
 1214: doc-aligned
 1215: doc-floats
 1216: doc-float+
 1217: doc-float
 1218: doc-falign
 1219: doc-faligned
 1220: doc-sfloats
 1221: doc-sfloat+
 1222: doc-sfalign
 1223: doc-sfaligned
 1224: doc-dfloats
 1225: doc-dfloat+
 1226: doc-dfalign
 1227: doc-dfaligned
 1228: doc-maxalign
 1229: doc-maxaligned
 1230: doc-cfalign
 1231: doc-cfaligned
 1232: doc-address-unit-bits
 1233: 
 1234: @node Memory Blocks,  , Address arithmetic, Memory
 1235: @subsection Memory Blocks
 1236: @cindex memory block words
 1237: 
 1238: doc-move
 1239: doc-erase
 1240: 
 1241: While the previous words work on address units, the rest works on
 1242: characters.
 1243: 
 1244: doc-cmove
 1245: doc-cmove>
 1246: doc-fill
 1247: doc-blank
 1248: 
 1249: @node Control Structures, Locals, Memory, Words
 1250: @section Control Structures
 1251: @cindex control structures
 1252: 
 1253: Control structures in Forth cannot be used in interpret state, only in
 1254: compile state@footnote{More precisely, they have no interpretation
 1255: semantics (@pxref{Interpretation and Compilation Semantics})}, i.e., in
 1256: a colon definition. We do not like this limitation, but have not seen a
 1257: satisfying way around it yet, although many schemes have been proposed.
 1258: 
 1259: @menu
 1260: * Selection::                   
 1261: * Simple Loops::                
 1262: * Counted Loops::               
 1263: * Arbitrary control structures::  
 1264: * Calls and returns::           
 1265: * Exception Handling::          
 1266: @end menu
 1267: 
 1268: @node Selection, Simple Loops, Control Structures, Control Structures
 1269: @subsection Selection
 1270: @cindex selection control structures
 1271: @cindex control structures for selection
 1272: 
 1273: @cindex @code{IF} control structure
 1274: @example
 1275: @var{flag}
 1276: IF
 1277:   @var{code}
 1278: ENDIF
 1279: @end example
 1280: or
 1281: @example
 1282: @var{flag}
 1283: IF
 1284:   @var{code1}
 1285: ELSE
 1286:   @var{code2}
 1287: ENDIF
 1288: @end example
 1289: 
 1290: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
 1291: standard, and @code{ENDIF} is not, although it is quite popular. We
 1292: recommend using @code{ENDIF}, because it is less confusing for people
 1293: who also know other languages (and is not prone to reinforcing negative
 1294: prejudices against Forth in these people). Adding @code{ENDIF} to a
 1295: system that only supplies @code{THEN} is simple:
 1296: @example
 1297: : endif   POSTPONE then ; immediate
 1298: @end example
 1299: 
 1300: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
 1301: (adv.)}  has the following meanings:
 1302: @quotation
 1303: ... 2b: following next after in order ... 3d: as a necessary consequence
 1304: (if you were there, then you saw them).
 1305: @end quotation
 1306: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
 1307: and many other programming languages has the meaning 3d.]
 1308: 
 1309: Gforth also provides the words @code{?dup-if} and @code{?dup-0=-if}, so
 1310: you can avoid using @code{?dup}. Using these alternatives is also more
 1311: efficient than using @code{?dup}. Definitions in plain standard Forth
 1312: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
 1313: @file{compat/control.fs}.
 1314: 
 1315: @cindex @code{CASE} control structure
 1316: @example
 1317: @var{n}
 1318: CASE
 1319:   @var{n1} OF @var{code1} ENDOF
 1320:   @var{n2} OF @var{code2} ENDOF
 1321:   @dots{}
 1322: ENDCASE
 1323: @end example
 1324: 
 1325: Executes the first @var{codei}, where the @var{ni} is equal to
 1326: @var{n}. A default case can be added by simply writing the code after
 1327: the last @code{ENDOF}. It may use @var{n}, which is on top of the stack,
 1328: but must not consume it.
 1329: 
 1330: @node Simple Loops, Counted Loops, Selection, Control Structures
 1331: @subsection Simple Loops
 1332: @cindex simple loops
 1333: @cindex loops without count 
 1334: 
 1335: @cindex @code{WHILE} loop
 1336: @example
 1337: BEGIN
 1338:   @var{code1}
 1339:   @var{flag}
 1340: WHILE
 1341:   @var{code2}
 1342: REPEAT
 1343: @end example
 1344: 
 1345: @var{code1} is executed and @var{flag} is computed. If it is true,
 1346: @var{code2} is executed and the loop is restarted; If @var{flag} is
 1347: false, execution continues after the @code{REPEAT}.
 1348: 
 1349: @cindex @code{UNTIL} loop
 1350: @example
 1351: BEGIN
 1352:   @var{code}
 1353:   @var{flag}
 1354: UNTIL
 1355: @end example
 1356: 
 1357: @var{code} is executed. The loop is restarted if @code{flag} is false.
 1358: 
 1359: @cindex endless loop
 1360: @cindex loops, endless
 1361: @example
 1362: BEGIN
 1363:   @var{code}
 1364: AGAIN
 1365: @end example
 1366: 
 1367: This is an endless loop.
 1368: 
 1369: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
 1370: @subsection Counted Loops
 1371: @cindex counted loops
 1372: @cindex loops, counted
 1373: @cindex @code{DO} loops
 1374: 
 1375: The basic counted loop is:
 1376: @example
 1377: @var{limit} @var{start}
 1378: ?DO
 1379:   @var{body}
 1380: LOOP
 1381: @end example
 1382: 
 1383: This performs one iteration for every integer, starting from @var{start}
 1384: and up to, but excluding @var{limit}. The counter, aka index, can be
 1385: accessed with @code{i}. E.g., the loop
 1386: @example
 1387: 10 0 ?DO
 1388:   i .
 1389: LOOP
 1390: @end example
 1391: prints
 1392: @example
 1393: 0 1 2 3 4 5 6 7 8 9
 1394: @end example
 1395: The index of the innermost loop can be accessed with @code{i}, the index
 1396: of the next loop with @code{j}, and the index of the third loop with
 1397: @code{k}.
 1398: 
 1399: doc-i
 1400: doc-j
 1401: doc-k
 1402: 
 1403: The loop control data are kept on the return stack, so there are some
 1404: restrictions on mixing return stack accesses and counted loop
 1405: words. E.g., if you put values on the return stack outside the loop, you
 1406: cannot read them inside the loop. If you put values on the return stack
 1407: within a loop, you have to remove them before the end of the loop and
 1408: before accessing the index of the loop.
 1409: 
 1410: There are several variations on the counted loop:
 1411: 
 1412: @code{LEAVE} leaves the innermost counted loop immediately.
 1413: 
 1414: If @var{start} is greater than @var{limit}, a @code{?DO} loop is entered
 1415: (and @code{LOOP} iterates until they become equal by wrap-around
 1416: arithmetic). This behaviour is usually not what you want. Therefore,
 1417: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
 1418: @code{?DO}), which do not enter the loop if @var{start} is greater than
 1419: @var{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
 1420: unsigned loop parameters.
 1421: 
 1422: @code{LOOP} can be replaced with @code{@var{n} +LOOP}; this updates the
 1423: index by @var{n} instead of by 1. The loop is terminated when the border
 1424: between @var{limit-1} and @var{limit} is crossed. E.g.:
 1425: 
 1426: @code{4 0 +DO  i .  2 +LOOP}   prints @code{0 2}
 1427: 
 1428: @code{4 1 +DO  i .  2 +LOOP}   prints @code{1 3}
 1429: 
 1430: @cindex negative increment for counted loops
 1431: @cindex counted loops with negative increment
 1432: The behaviour of @code{@var{n} +LOOP} is peculiar when @var{n} is negative:
 1433: 
 1434: @code{-1 0 ?DO  i .  -1 +LOOP}  prints @code{0 -1}
 1435: 
 1436: @code{ 0 0 ?DO  i .  -1 +LOOP}  prints nothing
 1437: 
 1438: Therefore we recommend avoiding @code{@var{n} +LOOP} with negative
 1439: @var{n}. One alternative is @code{@var{u} -LOOP}, which reduces the
 1440: index by @var{u} each iteration. The loop is terminated when the border
 1441: between @var{limit+1} and @var{limit} is crossed. Gforth also provides
 1442: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
 1443: 
 1444: @code{-2 0 -DO  i .  1 -LOOP}  prints @code{0 -1}
 1445: 
 1446: @code{-1 0 -DO  i .  1 -LOOP}  prints @code{0}
 1447: 
 1448: @code{ 0 0 -DO  i .  1 -LOOP}  prints nothing
 1449: 
 1450: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
 1451: @code{-LOOP} are not in the ANS Forth standard. However, an
 1452: implementation for these words that uses only standard words is provided
 1453: in @file{compat/loops.fs}.
 1454: 
 1455: @code{?DO} can also be replaced by @code{DO}. @code{DO} always enters
 1456: the loop, independent of the loop parameters. Do not use @code{DO}, even
 1457: if you know that the loop is entered in any case. Such knowledge tends
 1458: to become invalid during maintenance of a program, and then the
 1459: @code{DO} will make trouble.
 1460: 
 1461: @code{UNLOOP} is used to prepare for an abnormal loop exit, e.g., via
 1462: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
 1463: return stack so @code{EXIT} can get to its return address.
 1464: 
 1465: @cindex @code{FOR} loops
 1466: Another counted loop is
 1467: @example
 1468: @var{n}
 1469: FOR
 1470:   @var{body}
 1471: NEXT
 1472: @end example
 1473: This is the preferred loop of native code compiler writers who are too
 1474: lazy to optimize @code{?DO} loops properly. In Gforth, this loop
 1475: iterates @var{n+1} times; @code{i} produces values starting with @var{n}
 1476: and ending with 0. Other Forth systems may behave differently, even if
 1477: they support @code{FOR} loops. To avoid problems, don't use @code{FOR}
 1478: loops.
 1479: 
 1480: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
 1481: @subsection Arbitrary control structures
 1482: @cindex control structures, user-defined
 1483: 
 1484: @cindex control-flow stack
 1485: ANS Forth permits and supports using control structures in a non-nested
 1486: way. Information about incomplete control structures is stored on the
 1487: control-flow stack. This stack may be implemented on the Forth data
 1488: stack, and this is what we have done in Gforth.
 1489: 
 1490: @cindex @code{orig}, control-flow stack item
 1491: @cindex @code{dest}, control-flow stack item
 1492: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
 1493: entry represents a backward branch target. A few words are the basis for
 1494: building any control structure possible (except control structures that
 1495: need storage, like calls, coroutines, and backtracking).
 1496: 
 1497: doc-if
 1498: doc-ahead
 1499: doc-then
 1500: doc-begin
 1501: doc-until
 1502: doc-again
 1503: doc-cs-pick
 1504: doc-cs-roll
 1505: 
 1506: On many systems control-flow stack items take one word, in Gforth they
 1507: currently take three (this may change in the future). Therefore it is a
 1508: really good idea to manipulate the control flow stack with
 1509: @code{cs-pick} and @code{cs-roll}, not with data stack manipulation
 1510: words.
 1511: 
 1512: Some standard control structure words are built from these words:
 1513: 
 1514: doc-else
 1515: doc-while
 1516: doc-repeat
 1517: 
 1518: Gforth adds some more control-structure words:
 1519: 
 1520: doc-endif
 1521: doc-?dup-if
 1522: doc-?dup-0=-if
 1523: 
 1524: Counted loop words constitute a separate group of words:
 1525: 
 1526: doc-?do
 1527: doc-+do
 1528: doc-u+do
 1529: doc--do
 1530: doc-u-do
 1531: doc-do
 1532: doc-for
 1533: doc-loop
 1534: doc-+loop
 1535: doc--loop
 1536: doc-next
 1537: doc-leave
 1538: doc-?leave
 1539: doc-unloop
 1540: doc-done
 1541: 
 1542: The standard does not allow using @code{cs-pick} and @code{cs-roll} on
 1543: @i{do-sys}. Our system allows it, but it's your job to ensure that for
 1544: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
 1545: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
 1546: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
 1547: resolved (by using one of the loop-ending words or @code{DONE}).
 1548: 
 1549: Another group of control structure words are
 1550: 
 1551: doc-case
 1552: doc-endcase
 1553: doc-of
 1554: doc-endof
 1555: 
 1556: @i{case-sys} and @i{of-sys} cannot be processed using @code{cs-pick} and
 1557: @code{cs-roll}.
 1558: 
 1559: @subsubsection Programming Style
 1560: 
 1561: In order to ensure readability we recommend that you do not create
 1562: arbitrary control structures directly, but define new control structure
 1563: words for the control structure you want and use these words in your
 1564: program.
 1565: 
 1566: E.g., instead of writing
 1567: 
 1568: @example
 1569: begin
 1570:   ...
 1571: if [ 1 cs-roll ]
 1572:   ...
 1573: again then
 1574: @end example
 1575: 
 1576: we recommend defining control structure words, e.g.,
 1577: 
 1578: @example
 1579: : while ( dest -- orig dest )
 1580:  POSTPONE if
 1581:  1 cs-roll ; immediate
 1582: 
 1583: : repeat ( orig dest -- )
 1584:  POSTPONE again
 1585:  POSTPONE then ; immediate
 1586: @end example
 1587: 
 1588: and then using these to create the control structure:
 1589: 
 1590: @example
 1591: begin
 1592:   ...
 1593: while
 1594:   ...
 1595: repeat
 1596: @end example
 1597: 
 1598: That's much easier to read, isn't it? Of course, @code{REPEAT} and
 1599: @code{WHILE} are predefined, so in this example it would not be
 1600: necessary to define them.
 1601: 
 1602: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
 1603: @subsection Calls and returns
 1604: @cindex calling a definition
 1605: @cindex returning from a definition
 1606: 
 1607: @cindex recursive definitions
 1608: A definition can be called simply be writing the name of the definition
 1609: to be called. Note that normally a definition is invisible during its
 1610: definition. If you want to write a directly recursive definition, you
 1611: can use @code{recursive} to make the current definition visible.
 1612: 
 1613: doc-recursive
 1614: 
 1615: Another way to perform a recursive call is
 1616: 
 1617: doc-recurse
 1618: 
 1619: @c @progstyle{
 1620: I prefer using @code{recursive} to @code{recurse}, because
 1621: calling the definition by name is more descriptive (if the name is
 1622: well-chosen) than the somewhat cryptic @code{recurse}.  E.g., in a
 1623: quicksort implementation, it is much better to read (and think) ``now
 1624: sort the partitions'' than to read ``now do a recursive call''.
 1625: 
 1626: For mutual recursion, use @code{defer}red words, like this:
 1627: 
 1628: @example
 1629: defer foo
 1630: 
 1631: : bar ( ... -- ... )
 1632:  ... foo ... ;
 1633: 
 1634: :noname ( ... -- ... )
 1635:  ... bar ... ;
 1636: IS foo
 1637: @end example
 1638: 
 1639: When the end of the definition is reached, it returns. An earlier return
 1640: can be forced using
 1641: 
 1642: doc-exit
 1643: 
 1644: Don't forget to clean up the return stack and @code{UNLOOP} any
 1645: outstanding @code{?DO}...@code{LOOP}s before @code{EXIT}ing. The
 1646: primitive compiled by @code{EXIT} is
 1647: 
 1648: doc-;s
 1649: 
 1650: @node Exception Handling,  , Calls and returns, Control Structures
 1651: @subsection Exception Handling
 1652: @cindex Exceptions
 1653: 
 1654: doc-catch
 1655: doc-throw
 1656: 
 1657: @node Locals, Defining Words, Control Structures, Words
 1658: @section Locals
 1659: @cindex locals
 1660: 
 1661: Local variables can make Forth programming more enjoyable and Forth
 1662: programs easier to read. Unfortunately, the locals of ANS Forth are
 1663: laden with restrictions. Therefore, we provide not only the ANS Forth
 1664: locals wordset, but also our own, more powerful locals wordset (we
 1665: implemented the ANS Forth locals wordset through our locals wordset).
 1666: 
 1667: The ideas in this section have also been published in the paper
 1668: @cite{Automatic Scoping of Local Variables} by M. Anton Ertl, presented
 1669: at EuroForth '94; it is available at
 1670: @*@url{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz}.
 1671: 
 1672: @menu
 1673: * Gforth locals::               
 1674: * ANS Forth locals::            
 1675: @end menu
 1676: 
 1677: @node Gforth locals, ANS Forth locals, Locals, Locals
 1678: @subsection Gforth locals
 1679: @cindex Gforth locals
 1680: @cindex locals, Gforth style
 1681: 
 1682: Locals can be defined with
 1683: 
 1684: @example
 1685: @{ local1 local2 ... -- comment @}
 1686: @end example
 1687: or
 1688: @example
 1689: @{ local1 local2 ... @}
 1690: @end example
 1691: 
 1692: E.g.,
 1693: @example
 1694: : max @{ n1 n2 -- n3 @}
 1695:  n1 n2 > if
 1696:    n1
 1697:  else
 1698:    n2
 1699:  endif ;
 1700: @end example
 1701: 
 1702: The similarity of locals definitions with stack comments is intended. A
 1703: locals definition often replaces the stack comment of a word. The order
 1704: of the locals corresponds to the order in a stack comment and everything
 1705: after the @code{--} is really a comment.
 1706: 
 1707: This similarity has one disadvantage: It is too easy to confuse locals
 1708: declarations with stack comments, causing bugs and making them hard to
 1709: find. However, this problem can be avoided by appropriate coding
 1710: conventions: Do not use both notations in the same program. If you do,
 1711: they should be distinguished using additional means, e.g. by position.
 1712: 
 1713: @cindex types of locals
 1714: @cindex locals types
 1715: The name of the local may be preceded by a type specifier, e.g.,
 1716: @code{F:} for a floating point value:
 1717: 
 1718: @example
 1719: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
 1720: \ complex multiplication
 1721:  Ar Br f* Ai Bi f* f-
 1722:  Ar Bi f* Ai Br f* f+ ;
 1723: @end example
 1724: 
 1725: @cindex flavours of locals
 1726: @cindex locals flavours
 1727: @cindex value-flavoured locals
 1728: @cindex variable-flavoured locals
 1729: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
 1730: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
 1731: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
 1732: with @code{W:}, @code{D:} etc.) produces its value and can be changed
 1733: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
 1734: produces its address (which becomes invalid when the variable's scope is
 1735: left). E.g., the standard word @code{emit} can be defined in terms of
 1736: @code{type} like this:
 1737: 
 1738: @example
 1739: : emit @{ C^ char* -- @}
 1740:     char* 1 type ;
 1741: @end example
 1742: 
 1743: @cindex default type of locals
 1744: @cindex locals, default type
 1745: A local without type specifier is a @code{W:} local. Both flavours of
 1746: locals are initialized with values from the data or FP stack.
 1747: 
 1748: Currently there is no way to define locals with user-defined data
 1749: structures, but we are working on it.
 1750: 
 1751: Gforth allows defining locals everywhere in a colon definition. This
 1752: poses the following questions:
 1753: 
 1754: @menu
 1755: * Where are locals visible by name?::  
 1756: * How long do locals live?::    
 1757: * Programming Style::           
 1758: * Implementation::              
 1759: @end menu
 1760: 
 1761: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
 1762: @subsubsection Where are locals visible by name?
 1763: @cindex locals visibility
 1764: @cindex visibility of locals
 1765: @cindex scope of locals
 1766: 
 1767: Basically, the answer is that locals are visible where you would expect
 1768: it in block-structured languages, and sometimes a little longer. If you
 1769: want to restrict the scope of a local, enclose its definition in
 1770: @code{SCOPE}...@code{ENDSCOPE}.
 1771: 
 1772: doc-scope
 1773: doc-endscope
 1774: 
 1775: These words behave like control structure words, so you can use them
 1776: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
 1777: arbitrary ways.
 1778: 
 1779: If you want a more exact answer to the visibility question, here's the
 1780: basic principle: A local is visible in all places that can only be
 1781: reached through the definition of the local@footnote{In compiler
 1782: construction terminology, all places dominated by the definition of the
 1783: local.}. In other words, it is not visible in places that can be reached
 1784: without going through the definition of the local. E.g., locals defined
 1785: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
 1786: defined in @code{BEGIN}...@code{UNTIL} are visible after the
 1787: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
 1788: 
 1789: The reasoning behind this solution is: We want to have the locals
 1790: visible as long as it is meaningful. The user can always make the
 1791: visibility shorter by using explicit scoping. In a place that can
 1792: only be reached through the definition of a local, the meaning of a
 1793: local name is clear. In other places it is not: How is the local
 1794: initialized at the control flow path that does not contain the
 1795: definition? Which local is meant, if the same name is defined twice in
 1796: two independent control flow paths?
 1797: 
 1798: This should be enough detail for nearly all users, so you can skip the
 1799: rest of this section. If you really must know all the gory details and
 1800: options, read on.
 1801: 
 1802: In order to implement this rule, the compiler has to know which places
 1803: are unreachable. It knows this automatically after @code{AHEAD},
 1804: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
 1805: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
 1806: compiler that the control flow never reaches that place. If
 1807: @code{UNREACHABLE} is not used where it could, the only consequence is
 1808: that the visibility of some locals is more limited than the rule above
 1809: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
 1810: lie to the compiler), buggy code will be produced.
 1811: 
 1812: doc-unreachable
 1813: 
 1814: Another problem with this rule is that at @code{BEGIN}, the compiler
 1815: does not know which locals will be visible on the incoming
 1816: back-edge. All problems discussed in the following are due to this
 1817: ignorance of the compiler (we discuss the problems using @code{BEGIN}
 1818: loops as examples; the discussion also applies to @code{?DO} and other
 1819: loops). Perhaps the most insidious example is:
 1820: @example
 1821: AHEAD
 1822: BEGIN
 1823:   x
 1824: [ 1 CS-ROLL ] THEN
 1825:   @{ x @}
 1826:   ...
 1827: UNTIL
 1828: @end example
 1829: 
 1830: This should be legal according to the visibility rule. The use of
 1831: @code{x} can only be reached through the definition; but that appears
 1832: textually below the use.
 1833: 
 1834: From this example it is clear that the visibility rules cannot be fully
 1835: implemented without major headaches. Our implementation treats common
 1836: cases as advertised and the exceptions are treated in a safe way: The
 1837: compiler makes a reasonable guess about the locals visible after a
 1838: @code{BEGIN}; if it is too pessimistic, the
 1839: user will get a spurious error about the local not being defined; if the
 1840: compiler is too optimistic, it will notice this later and issue a
 1841: warning. In the case above the compiler would complain about @code{x}
 1842: being undefined at its use. You can see from the obscure examples in
 1843: this section that it takes quite unusual control structures to get the
 1844: compiler into trouble, and even then it will often do fine.
 1845: 
 1846: If the @code{BEGIN} is reachable from above, the most optimistic guess
 1847: is that all locals visible before the @code{BEGIN} will also be
 1848: visible after the @code{BEGIN}. This guess is valid for all loops that
 1849: are entered only through the @code{BEGIN}, in particular, for normal
 1850: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
 1851: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
 1852: compiler. When the branch to the @code{BEGIN} is finally generated by
 1853: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
 1854: warns the user if it was too optimistic:
 1855: @example
 1856: IF
 1857:   @{ x @}
 1858: BEGIN
 1859:   \ x ? 
 1860: [ 1 cs-roll ] THEN
 1861:   ...
 1862: UNTIL
 1863: @end example
 1864: 
 1865: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
 1866: optimistically assumes that it lives until the @code{THEN}. It notices
 1867: this difference when it compiles the @code{UNTIL} and issues a
 1868: warning. The user can avoid the warning, and make sure that @code{x}
 1869: is not used in the wrong area by using explicit scoping:
 1870: @example
 1871: IF
 1872:   SCOPE
 1873:   @{ x @}
 1874:   ENDSCOPE
 1875: BEGIN
 1876: [ 1 cs-roll ] THEN
 1877:   ...
 1878: UNTIL
 1879: @end example
 1880: 
 1881: Since the guess is optimistic, there will be no spurious error messages
 1882: about undefined locals.
 1883: 
 1884: If the @code{BEGIN} is not reachable from above (e.g., after
 1885: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
 1886: optimistic guess, as the locals visible after the @code{BEGIN} may be
 1887: defined later. Therefore, the compiler assumes that no locals are
 1888: visible after the @code{BEGIN}. However, the user can use
 1889: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
 1890: visible at the BEGIN as at the point where the top control-flow stack
 1891: item was created.
 1892: 
 1893: doc-assume-live
 1894: 
 1895: E.g.,
 1896: @example
 1897: @{ x @}
 1898: AHEAD
 1899: ASSUME-LIVE
 1900: BEGIN
 1901:   x
 1902: [ 1 CS-ROLL ] THEN
 1903:   ...
 1904: UNTIL
 1905: @end example
 1906: 
 1907: Other cases where the locals are defined before the @code{BEGIN} can be
 1908: handled by inserting an appropriate @code{CS-ROLL} before the
 1909: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
 1910: behind the @code{ASSUME-LIVE}).
 1911: 
 1912: Cases where locals are defined after the @code{BEGIN} (but should be
 1913: visible immediately after the @code{BEGIN}) can only be handled by
 1914: rearranging the loop. E.g., the ``most insidious'' example above can be
 1915: arranged into:
 1916: @example
 1917: BEGIN
 1918:   @{ x @}
 1919:   ... 0=
 1920: WHILE
 1921:   x
 1922: REPEAT
 1923: @end example
 1924: 
 1925: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
 1926: @subsubsection How long do locals live?
 1927: @cindex locals lifetime
 1928: @cindex lifetime of locals
 1929: 
 1930: The right answer for the lifetime question would be: A local lives at
 1931: least as long as it can be accessed. For a value-flavoured local this
 1932: means: until the end of its visibility. However, a variable-flavoured
 1933: local could be accessed through its address far beyond its visibility
 1934: scope. Ultimately, this would mean that such locals would have to be
 1935: garbage collected. Since this entails un-Forth-like implementation
 1936: complexities, I adopted the same cowardly solution as some other
 1937: languages (e.g., C): The local lives only as long as it is visible;
 1938: afterwards its address is invalid (and programs that access it
 1939: afterwards are erroneous).
 1940: 
 1941: @node Programming Style, Implementation, How long do locals live?, Gforth locals
 1942: @subsubsection Programming Style
 1943: @cindex locals programming style
 1944: @cindex programming style, locals
 1945: 
 1946: The freedom to define locals anywhere has the potential to change
 1947: programming styles dramatically. In particular, the need to use the
 1948: return stack for intermediate storage vanishes. Moreover, all stack
 1949: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
 1950: determined arguments) can be eliminated: If the stack items are in the
 1951: wrong order, just write a locals definition for all of them; then
 1952: write the items in the order you want.
 1953: 
 1954: This seems a little far-fetched and eliminating stack manipulations is
 1955: unlikely to become a conscious programming objective. Still, the number
 1956: of stack manipulations will be reduced dramatically if local variables
 1957: are used liberally (e.g., compare @code{max} in @ref{Gforth locals} with
 1958: a traditional implementation of @code{max}).
 1959: 
 1960: This shows one potential benefit of locals: making Forth programs more
 1961: readable. Of course, this benefit will only be realized if the
 1962: programmers continue to honour the principle of factoring instead of
 1963: using the added latitude to make the words longer.
 1964: 
 1965: @cindex single-assignment style for locals
 1966: Using @code{TO} can and should be avoided.  Without @code{TO},
 1967: every value-flavoured local has only a single assignment and many
 1968: advantages of functional languages apply to Forth. I.e., programs are
 1969: easier to analyse, to optimize and to read: It is clear from the
 1970: definition what the local stands for, it does not turn into something
 1971: different later.
 1972: 
 1973: E.g., a definition using @code{TO} might look like this:
 1974: @example
 1975: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 1976:  u1 u2 min 0
 1977:  ?do
 1978:    addr1 c@@ addr2 c@@ -
 1979:    ?dup-if
 1980:      unloop exit
 1981:    then
 1982:    addr1 char+ TO addr1
 1983:    addr2 char+ TO addr2
 1984:  loop
 1985:  u1 u2 - ;
 1986: @end example
 1987: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
 1988: every loop iteration. @code{strcmp} is a typical example of the
 1989: readability problems of using @code{TO}. When you start reading
 1990: @code{strcmp}, you think that @code{addr1} refers to the start of the
 1991: string. Only near the end of the loop you realize that it is something
 1992: else.
 1993: 
 1994: This can be avoided by defining two locals at the start of the loop that
 1995: are initialized with the right value for the current iteration.
 1996: @example
 1997: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 1998:  addr1 addr2
 1999:  u1 u2 min 0 
 2000:  ?do @{ s1 s2 @}
 2001:    s1 c@@ s2 c@@ -
 2002:    ?dup-if
 2003:      unloop exit
 2004:    then
 2005:    s1 char+ s2 char+
 2006:  loop
 2007:  2drop
 2008:  u1 u2 - ;
 2009: @end example
 2010: Here it is clear from the start that @code{s1} has a different value
 2011: in every loop iteration.
 2012: 
 2013: @node Implementation,  , Programming Style, Gforth locals
 2014: @subsubsection Implementation
 2015: @cindex locals implementation
 2016: @cindex implementation of locals
 2017: 
 2018: @cindex locals stack
 2019: Gforth uses an extra locals stack. The most compelling reason for
 2020: this is that the return stack is not float-aligned; using an extra stack
 2021: also eliminates the problems and restrictions of using the return stack
 2022: as locals stack. Like the other stacks, the locals stack grows toward
 2023: lower addresses. A few primitives allow an efficient implementation:
 2024: 
 2025: doc-@local#
 2026: doc-f@local#
 2027: doc-laddr#
 2028: doc-lp+!#
 2029: doc-lp!
 2030: doc->l
 2031: doc-f>l
 2032: 
 2033: In addition to these primitives, some specializations of these
 2034: primitives for commonly occurring inline arguments are provided for
 2035: efficiency reasons, e.g., @code{@@local0} as specialization of
 2036: @code{@@local#} for the inline argument 0. The following compiling words
 2037: compile the right specialized version, or the general version, as
 2038: appropriate:
 2039: 
 2040: doc-compile-@local
 2041: doc-compile-f@local
 2042: doc-compile-lp+!
 2043: 
 2044: Combinations of conditional branches and @code{lp+!#} like
 2045: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
 2046: is taken) are provided for efficiency and correctness in loops.
 2047: 
 2048: A special area in the dictionary space is reserved for keeping the
 2049: local variable names. @code{@{} switches the dictionary pointer to this
 2050: area and @code{@}} switches it back and generates the locals
 2051: initializing code. @code{W:} etc.@ are normal defining words. This
 2052: special area is cleared at the start of every colon definition.
 2053: 
 2054: @cindex wordlist for defining locals
 2055: A special feature of Gforth's dictionary is used to implement the
 2056: definition of locals without type specifiers: every wordlist (aka
 2057: vocabulary) has its own methods for searching
 2058: etc. (@pxref{Wordlists}). For the present purpose we defined a wordlist
 2059: with a special search method: When it is searched for a word, it
 2060: actually creates that word using @code{W:}. @code{@{} changes the search
 2061: order to first search the wordlist containing @code{@}}, @code{W:} etc.,
 2062: and then the wordlist for defining locals without type specifiers.
 2063: 
 2064: The lifetime rules support a stack discipline within a colon
 2065: definition: The lifetime of a local is either nested with other locals
 2066: lifetimes or it does not overlap them.
 2067: 
 2068: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
 2069: pointer manipulation is generated. Between control structure words
 2070: locals definitions can push locals onto the locals stack. @code{AGAIN}
 2071: is the simplest of the other three control flow words. It has to
 2072: restore the locals stack depth of the corresponding @code{BEGIN}
 2073: before branching. The code looks like this:
 2074: @format
 2075: @code{lp+!#} current-locals-size @minus{} dest-locals-size
 2076: @code{branch} <begin>
 2077: @end format
 2078: 
 2079: @code{UNTIL} is a little more complicated: If it branches back, it
 2080: must adjust the stack just like @code{AGAIN}. But if it falls through,
 2081: the locals stack must not be changed. The compiler generates the
 2082: following code:
 2083: @format
 2084: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
 2085: @end format
 2086: The locals stack pointer is only adjusted if the branch is taken.
 2087: 
 2088: @code{THEN} can produce somewhat inefficient code:
 2089: @format
 2090: @code{lp+!#} current-locals-size @minus{} orig-locals-size
 2091: <orig target>:
 2092: @code{lp+!#} orig-locals-size @minus{} new-locals-size
 2093: @end format
 2094: The second @code{lp+!#} adjusts the locals stack pointer from the
 2095: level at the @var{orig} point to the level after the @code{THEN}. The
 2096: first @code{lp+!#} adjusts the locals stack pointer from the current
 2097: level to the level at the orig point, so the complete effect is an
 2098: adjustment from the current level to the right level after the
 2099: @code{THEN}.
 2100: 
 2101: @cindex locals information on the control-flow stack
 2102: @cindex control-flow stack items, locals information
 2103: In a conventional Forth implementation a dest control-flow stack entry
 2104: is just the target address and an orig entry is just the address to be
 2105: patched. Our locals implementation adds a wordlist to every orig or dest
 2106: item. It is the list of locals visible (or assumed visible) at the point
 2107: described by the entry. Our implementation also adds a tag to identify
 2108: the kind of entry, in particular to differentiate between live and dead
 2109: (reachable and unreachable) orig entries.
 2110: 
 2111: A few unusual operations have to be performed on locals wordlists:
 2112: 
 2113: doc-common-list
 2114: doc-sub-list?
 2115: doc-list-size
 2116: 
 2117: Several features of our locals wordlist implementation make these
 2118: operations easy to implement: The locals wordlists are organised as
 2119: linked lists; the tails of these lists are shared, if the lists
 2120: contain some of the same locals; and the address of a name is greater
 2121: than the address of the names behind it in the list.
 2122: 
 2123: Another important implementation detail is the variable
 2124: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
 2125: determine if they can be reached directly or only through the branch
 2126: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
 2127: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
 2128: definition, by @code{BEGIN} and usually by @code{THEN}.
 2129: 
 2130: Counted loops are similar to other loops in most respects, but
 2131: @code{LEAVE} requires special attention: It performs basically the same
 2132: service as @code{AHEAD}, but it does not create a control-flow stack
 2133: entry. Therefore the information has to be stored elsewhere;
 2134: traditionally, the information was stored in the target fields of the
 2135: branches created by the @code{LEAVE}s, by organizing these fields into a
 2136: linked list. Unfortunately, this clever trick does not provide enough
 2137: space for storing our extended control flow information. Therefore, we
 2138: introduce another stack, the leave stack. It contains the control-flow
 2139: stack entries for all unresolved @code{LEAVE}s.
 2140: 
 2141: Local names are kept until the end of the colon definition, even if
 2142: they are no longer visible in any control-flow path. In a few cases
 2143: this may lead to increased space needs for the locals name area, but
 2144: usually less than reclaiming this space would cost in code size.
 2145: 
 2146: 
 2147: @node ANS Forth locals,  , Gforth locals, Locals
 2148: @subsection ANS Forth locals
 2149: @cindex locals, ANS Forth style
 2150: 
 2151: The ANS Forth locals wordset does not define a syntax for locals, but
 2152: words that make it possible to define various syntaxes. One of the
 2153: possible syntaxes is a subset of the syntax we used in the Gforth locals
 2154: wordset, i.e.:
 2155: 
 2156: @example
 2157: @{ local1 local2 ... -- comment @}
 2158: @end example
 2159: or
 2160: @example
 2161: @{ local1 local2 ... @}
 2162: @end example
 2163: 
 2164: The order of the locals corresponds to the order in a stack comment. The
 2165: restrictions are:
 2166: 
 2167: @itemize @bullet
 2168: @item
 2169: Locals can only be cell-sized values (no type specifiers are allowed).
 2170: @item
 2171: Locals can be defined only outside control structures.
 2172: @item
 2173: Locals can interfere with explicit usage of the return stack. For the
 2174: exact (and long) rules, see the standard. If you don't use return stack
 2175: accessing words in a definition using locals, you will be all right. The
 2176: purpose of this rule is to make locals implementation on the return
 2177: stack easier.
 2178: @item
 2179: The whole definition must be in one line.
 2180: @end itemize
 2181: 
 2182: Locals defined in this way behave like @code{VALUE}s (@xref{Simple
 2183: Defining Words}). I.e., they are initialized from the stack. Using their
 2184: name produces their value. Their value can be changed using @code{TO}.
 2185: 
 2186: Since this syntax is supported by Gforth directly, you need not do
 2187: anything to use it. If you want to port a program using this syntax to
 2188: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
 2189: syntax on the other system.
 2190: 
 2191: Note that a syntax shown in the standard, section A.13 looks
 2192: similar, but is quite different in having the order of locals
 2193: reversed. Beware!
 2194: 
 2195: The ANS Forth locals wordset itself consists of the following word
 2196: 
 2197: doc-(local)
 2198: 
 2199: The ANS Forth locals extension wordset defines a syntax, but it is so
 2200: awful that we strongly recommend not to use it. We have implemented this
 2201: syntax to make porting to Gforth easy, but do not document it here. The
 2202: problem with this syntax is that the locals are defined in an order
 2203: reversed with respect to the standard stack comment notation, making
 2204: programs harder to read, and easier to misread and miswrite. The only
 2205: merit of this syntax is that it is easy to implement using the ANS Forth
 2206: locals wordset.
 2207: 
 2208: @node Defining Words, Structures, Locals, Words
 2209: @section Defining Words
 2210: @cindex defining words
 2211: 
 2212: @menu
 2213: * Simple Defining Words::       
 2214: * Colon Definitions::           
 2215: * User-defined Defining Words::  
 2216: * Supplying names::             
 2217: * Interpretation and Compilation Semantics::  
 2218: @end menu
 2219: 
 2220: @node Simple Defining Words, Colon Definitions, Defining Words, Defining Words
 2221: @subsection Simple Defining Words
 2222: @cindex simple defining words
 2223: @cindex defining words, simple
 2224: 
 2225: doc-constant
 2226: doc-2constant
 2227: doc-fconstant
 2228: doc-variable
 2229: doc-2variable
 2230: doc-fvariable
 2231: doc-create
 2232: doc-user
 2233: doc-value
 2234: doc-to
 2235: doc-defer
 2236: doc-is
 2237: 
 2238: @node Colon Definitions, User-defined Defining Words, Simple Defining Words, Defining Words
 2239: @subsection Colon Definitions
 2240: @cindex colon definitions
 2241: 
 2242: @example
 2243: : name ( ... -- ... )
 2244:     word1 word2 word3 ;
 2245: @end example
 2246: 
 2247: creates a word called @code{name}, that, upon execution, executes
 2248: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
 2249: 
 2250: The explanation above is somewhat superficial. @xref{Interpretation and
 2251: Compilation Semantics} for an in-depth discussion of some of the issues
 2252: involved.
 2253: 
 2254: doc-:
 2255: doc-;
 2256: 
 2257: @node User-defined Defining Words, Supplying names, Colon Definitions, Defining Words
 2258: @subsection User-defined Defining Words
 2259: @cindex user-defined defining words
 2260: @cindex defining words, user-defined
 2261: 
 2262: You can create new defining words simply by wrapping defining-time code
 2263: around existing defining words and putting the sequence in a colon
 2264: definition.
 2265: 
 2266: @cindex @code{CREATE} ... @code{DOES>}
 2267: If you want the words defined with your defining words to behave
 2268: differently from words defined with standard defining words, you can
 2269: write your defining word like this:
 2270: 
 2271: @example
 2272: : def-word ( "name" -- )
 2273:     Create @var{code1}
 2274: DOES> ( ... -- ... )
 2275:     @var{code2} ;
 2276: 
 2277: def-word name
 2278: @end example
 2279: 
 2280: Technically, this fragment defines a defining word @code{def-word}, and
 2281: a word @code{name}; when you execute @code{name}, the address of the
 2282: body of @code{name} is put on the data stack and @var{code2} is executed
 2283: (the address of the body of @code{name} is the address @code{HERE}
 2284: returns immediately after the @code{CREATE}).
 2285: 
 2286: In other words, if you make the following definitions:
 2287: 
 2288: @example
 2289: : def-word1 ( "name" -- )
 2290:     Create @var{code1} ;
 2291: 
 2292: : action1 ( ... -- ... )
 2293:     @var{code2} ;
 2294: 
 2295: def-word name1
 2296: @end example
 2297: 
 2298: Using @code{name1 action1} is equivalent to using @code{name}.
 2299: 
 2300: E.g., you can implement @code{Constant} in this way:
 2301: 
 2302: @example
 2303: : constant ( w "name" -- )
 2304:     create ,
 2305: DOES> ( -- w )
 2306:     @@ ;
 2307: @end example
 2308: 
 2309: When you create a constant with @code{5 constant five}, first a new word
 2310: @code{five} is created, then the value 5 is laid down in the body of
 2311: @code{five} with @code{,}. When @code{five} is invoked, the address of
 2312: the body is put on the stack, and @code{@@} retrieves the value 5.
 2313: 
 2314: @cindex stack effect of @code{DOES>}-parts
 2315: @cindex @code{DOES>}-parts, stack effect
 2316: In the example above the stack comment after the @code{DOES>} specifies
 2317: the stack effect of the defined words, not the stack effect of the
 2318: following code (the following code expects the address of the body on
 2319: the top of stack, which is not reflected in the stack comment). This is
 2320: the convention that I use and recommend (it clashes a bit with using
 2321: locals declarations for stack effect specification, though).
 2322: 
 2323: @subsubsection Applications of @code{CREATE..DOES>}
 2324: @cindex @code{CREATE} ... @code{DOES>}, applications
 2325: 
 2326: You may wonder how to use this feature. Here are some usage patterns:
 2327: 
 2328: @cindex factoring similar colon definitions
 2329: When you see a sequence of code occurring several times, and you can
 2330: identify a meaning, you will factor it out as a colon definition. When
 2331: you see similar colon definitions, you can factor them using
 2332: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
 2333: that look very similar:
 2334: @example
 2335: : ori, ( reg-target reg-source n -- )
 2336:     0 asm-reg-reg-imm ;
 2337: : andi, ( reg-target reg-source n -- )
 2338:     1 asm-reg-reg-imm ;
 2339: @end example
 2340: 
 2341: This could be factored with:
 2342: @example
 2343: : reg-reg-imm ( op-code -- )
 2344:     create ,
 2345: DOES> ( reg-target reg-source n -- )
 2346:     @@ asm-reg-reg-imm ;
 2347: 
 2348: 0 reg-reg-imm ori,
 2349: 1 reg-reg-imm andi,
 2350: @end example
 2351: 
 2352: @cindex currying
 2353: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
 2354: supply a part of the parameters for a word (known as @dfn{currying} in
 2355: the functional language community). E.g., @code{+} needs two
 2356: parameters. Creating versions of @code{+} with one parameter fixed can
 2357: be done like this:
 2358: @example
 2359: : curry+ ( n1 -- )
 2360:     create ,
 2361: DOES> ( n2 -- n1+n2 )
 2362:     @@ + ;
 2363: 
 2364:  3 curry+ 3+
 2365: -2 curry+ 2-
 2366: @end example
 2367: 
 2368: @subsubsection The gory details of @code{CREATE..DOES>}
 2369: @cindex @code{CREATE} ... @code{DOES>}, details
 2370: 
 2371: doc-does>
 2372: 
 2373: @cindex @code{DOES>} in a separate definition
 2374: This means that you need not use @code{CREATE} and @code{DOES>} in the
 2375: same definition; E.g., you can put the @code{DOES>}-part in a separate
 2376: definition. This allows us to, e.g., select among different DOES>-parts:
 2377: @example
 2378: : does1 
 2379: DOES> ( ... -- ... )
 2380:     ... ;
 2381: 
 2382: : does2
 2383: DOES> ( ... -- ... )
 2384:     ... ;
 2385: 
 2386: : def-word ( ... -- ... )
 2387:     create ...
 2388:     IF
 2389:        does1
 2390:     ELSE
 2391:        does2
 2392:     ENDIF ;
 2393: @end example
 2394: 
 2395: @cindex @code{DOES>} in interpretation state
 2396: In a standard program you can apply a @code{DOES>}-part only if the last
 2397: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
 2398: will override the behaviour of the last word defined in any case. In a
 2399: standard program, you can use @code{DOES>} only in a colon
 2400: definition. In Gforth, you can also use it in interpretation state, in a
 2401: kind of one-shot mode:
 2402: @example
 2403: CREATE name ( ... -- ... )
 2404:   @var{initialization}
 2405: DOES>
 2406:   @var{code} ;
 2407: @end example
 2408: This is equivalent to the standard
 2409: @example
 2410: :noname
 2411: DOES>
 2412:     @var{code} ;
 2413: CREATE name EXECUTE ( ... -- ... )
 2414:     @var{initialization}
 2415: @end example
 2416: 
 2417: You can get the address of the body of a word with
 2418: 
 2419: doc->body
 2420: 
 2421: @node Supplying names, Interpretation and Compilation Semantics, User-defined Defining Words, Defining Words
 2422: @subsection Supplying names for the defined words
 2423: @cindex names for defined words
 2424: @cindex defining words, name parameter
 2425: 
 2426: @cindex defining words, name given in a string
 2427: By default, defining words take the names for the defined words from the
 2428: input stream. Sometimes you want to supply the name from a string. You
 2429: can do this with
 2430: 
 2431: doc-nextname
 2432: 
 2433: E.g.,
 2434: 
 2435: @example
 2436: s" foo" nextname create
 2437: @end example
 2438: is equivalent to
 2439: @example
 2440: create foo
 2441: @end example
 2442: 
 2443: @cindex defining words without name
 2444: Sometimes you want to define a word without a name. You can do this with
 2445: 
 2446: doc-noname
 2447: 
 2448: @cindex execution token of last defined word
 2449: To make any use of the newly defined word, you need its execution
 2450: token. You can get it with
 2451: 
 2452: doc-lastxt
 2453: 
 2454: E.g., you can initialize a deferred word with an anonymous colon
 2455: definition:
 2456: @example
 2457: Defer deferred
 2458: noname : ( ... -- ... )
 2459:   ... ;
 2460: lastxt IS deferred
 2461: @end example
 2462: 
 2463: @code{lastxt} also works when the last word was not defined as
 2464: @code{noname}. 
 2465: 
 2466: The standard has also recognized the need for anonymous words and
 2467: provides
 2468: 
 2469: doc-:noname
 2470: 
 2471: This leaves the execution token for the word on the stack after the
 2472: closing @code{;}. You can rewrite the last example with @code{:noname}:
 2473: @example
 2474: Defer deferred
 2475: :noname ( ... -- ... )
 2476:   ... ;
 2477: IS deferred
 2478: @end example
 2479: 
 2480: @node Interpretation and Compilation Semantics,  , Supplying names, Defining Words
 2481: @subsection Interpretation and Compilation Semantics
 2482: @cindex semantics, interpretation and compilation
 2483: 
 2484: @cindex interpretation semantics
 2485: The @dfn{interpretation semantics} of a word are what the text
 2486: interpreter does when it encounters the word in interpret state. It also
 2487: appears in some other contexts, e.g., the execution token returned by
 2488: @code{' @var{word}} identifies the interpretation semantics of
 2489: @var{word} (in other words, @code{' @var{word} execute} is equivalent to
 2490: interpret-state text interpretation of @code{@var{word}}).
 2491: 
 2492: @cindex compilation semantics
 2493: The @dfn{compilation semantics} of a word are what the text interpreter
 2494: does when it encounters the word in compile state. It also appears in
 2495: other contexts, e.g, @code{POSTPONE @var{word}} compiles@footnote{In
 2496: standard terminology, ``appends to the current definition''.} the
 2497: compilation semantics of @var{word}.
 2498: 
 2499: @cindex execution semantics
 2500: The standard also talks about @dfn{execution semantics}. They are used
 2501: only for defining the interpretation and compilation semantics of many
 2502: words. By default, the interpretation semantics of a word are to
 2503: @code{execute} its execution semantics, and the compilation semantics of
 2504: a word are to @code{compile,} its execution semantics.@footnote{In
 2505: standard terminology: The default interpretation semantics are its
 2506: execution semantics; the default compilation semantics are to append its
 2507: execution semantics to the execution semantics of the current
 2508: definition.}
 2509: 
 2510: @cindex immediate words
 2511: You can change the compilation semantics into @code{execute}ing the
 2512: execution semantics with
 2513: 
 2514: doc-immediate
 2515: 
 2516: @cindex compile-only words
 2517: You can remove the interpretation semantics of a word with
 2518: 
 2519: doc-compile-only
 2520: doc-restrict
 2521: 
 2522: Note that ticking (@code{'}) compile-only words gives an error
 2523: (``Interpreting a compile-only word'').
 2524: 
 2525: Gforth also allows you to define words with arbitrary combinations of
 2526: interpretation and compilation semantics.
 2527: 
 2528: doc-interpret/compile:
 2529: 
 2530: This feature was introduced for implementing @code{TO} and @code{S"}. I
 2531: recommend that you do not define such words, as cute as they may be:
 2532: they make it hard to get at both parts of the word in some contexts.
 2533: E.g., assume you want to get an execution token for the compilation
 2534: part. Instead, define two words, one that embodies the interpretation
 2535: part, and one that embodies the compilation part.
 2536: 
 2537: There is, however, a potentially useful application of this feature:
 2538: Providing differing implementations for the default semantics. While
 2539: this introduces redundancy and is therefore usually a bad idea, a
 2540: performance improvement may be worth the trouble. E.g., consider the
 2541: word @code{foobar}:
 2542: 
 2543: @example
 2544: : foobar
 2545:     foo bar ;
 2546: @end example
 2547: 
 2548: Let us assume that @code{foobar} is called so frequently that the
 2549: calling overhead would take a significant amount of the run-time. We can
 2550: optimize it with @code{interpret/compile:}:
 2551: 
 2552: @example
 2553: :noname
 2554:    foo bar ;
 2555: :noname
 2556:    POSTPONE foo POSTPONE bar ;
 2557: interpret/compile: foobar
 2558: @end example
 2559: 
 2560: This definition has the same interpretation semantics and essentially
 2561: the same compilation semantics as the simple definition of
 2562: @code{foobar}, but the implementation of the compilation semantics is
 2563: more efficient with respect to run-time.
 2564: 
 2565: @cindex state-smart words are a bad idea
 2566: Some people try to use state-smart words to emulate the feature provided
 2567: by @code{interpret/compile:} (words are state-smart if they check
 2568: @code{STATE} during execution). E.g., they would try to code
 2569: @code{foobar} like this:
 2570: 
 2571: @example
 2572: : foobar
 2573:   STATE @@
 2574:   IF ( compilation state )
 2575:     POSTPONE foo POSTPONE bar
 2576:   ELSE
 2577:     foo bar
 2578:   ENDIF ; immediate
 2579: @end example
 2580: 
 2581: While this works if @code{foobar} is processed only by the text
 2582: interpreter, it does not work in other contexts (like @code{'} or
 2583: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
 2584: for a state-smart word, not for the interpretation semantics of the
 2585: original @code{foobar}; when you execute this execution token (directly
 2586: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
 2587: state, the result will not be what you expected (i.e., it will not
 2588: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
 2589: write them!
 2590: 
 2591: @cindex defining words with arbitrary semantics combinations
 2592: It is also possible to write defining words that define words with
 2593: arbitrary combinations of interpretation and compilation semantics (or,
 2594: preferably, arbitrary combinations of implementations of the default
 2595: semantics). In general, this looks like:
 2596: 
 2597: @example
 2598: : def-word
 2599:     create-interpret/compile
 2600:     @var{code1}
 2601: interpretation>
 2602:     @var{code2}
 2603: <interpretation
 2604: compilation>
 2605:     @var{code3}
 2606: <compilation ;
 2607: @end example
 2608: 
 2609: For a @var{word} defined with @code{def-word}, the interpretation
 2610: semantics are to push the address of the body of @var{word} and perform
 2611: @var{code2}, and the compilation semantics are to push the address of
 2612: the body of @var{word} and perform @var{code3}. E.g., @code{constant}
 2613: can also be defined like this:
 2614: 
 2615: @example
 2616: : constant ( n "name" -- )
 2617:     create-interpret/compile
 2618:     ,
 2619: interpretation> ( -- n )
 2620:     @@
 2621: <interpretation
 2622: compilation> ( compilation. -- ; run-time. -- n )
 2623:     @@ postpone literal
 2624: <compilation ;
 2625: @end example
 2626: 
 2627: doc-create-interpret/compile
 2628: doc-interpretation>
 2629: doc-<interpretation
 2630: doc-compilation>
 2631: doc-<compilation
 2632: 
 2633: Note that words defined with @code{interpret/compile:} and
 2634: @code{create-interpret/compile} have an extended header structure that
 2635: differs from other words; however, unless you try to access them with
 2636: plain address arithmetic, you should not notice this. Words for
 2637: accessing the header structure usually know how to deal with this; e.g.,
 2638: @code{' word >body} also gives you the body of a word created with
 2639: @code{create-interpret/compile}.
 2640: 
 2641: @c ----------------------------------------------------------
 2642: @node Structures, Objects, Defining Words, Words
 2643: @section  Structures
 2644: @cindex structures
 2645: @cindex records
 2646: 
 2647: This section presents the structure package that comes with Gforth. A
 2648: version of the package implemented in plain ANS Forth is available in
 2649: @file{compat/struct.fs}. This package was inspired by a posting on
 2650: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
 2651: possibly John Hayes). A version of this section has been published in
 2652: ???. Marcel Hendrix provided helpful comments.
 2653: 
 2654: @menu
 2655: * Why explicit structure support?::  
 2656: * Structure Usage::             
 2657: * Structure Naming Convention::  
 2658: * Structure Implementation::    
 2659: * Structure Glossary::          
 2660: @end menu
 2661: 
 2662: @node Why explicit structure support?, Structure Usage, Structures, Structures
 2663: @subsection Why explicit structure support?
 2664: 
 2665: @cindex address arithmetic for structures
 2666: @cindex structures using address arithmetic
 2667: If we want to use a structure containing several fields, we could simply
 2668: reserve memory for it, and access the fields using address arithmetic
 2669: (@pxref{Address arithmetic}). As an example, consider a structure with
 2670: the following fields
 2671: 
 2672: @table @code
 2673: @item a
 2674: is a float
 2675: @item b
 2676: is a cell
 2677: @item c
 2678: is a float
 2679: @end table
 2680: 
 2681: Given the (float-aligned) base address of the structure we get the
 2682: address of the field
 2683: 
 2684: @table @code
 2685: @item a
 2686: without doing anything further.
 2687: @item b
 2688: with @code{float+}
 2689: @item c
 2690: with @code{float+ cell+ faligned}
 2691: @end table
 2692: 
 2693: It is easy to see that this can become quite tiring. 
 2694: 
 2695: Moreover, it is not very readable, because seeing a
 2696: @code{cell+} tells us neither which kind of structure is
 2697: accessed nor what field is accessed; we have to somehow infer the kind
 2698: of structure, and then look up in the documentation, which field of
 2699: that structure corresponds to that offset.
 2700: 
 2701: Finally, this kind of address arithmetic also causes maintenance
 2702: troubles: If you add or delete a field somewhere in the middle of the
 2703: structure, you have to find and change all computations for the fields
 2704: afterwards.
 2705: 
 2706: So, instead of using @code{cell+} and friends directly, how
 2707: about storing the offsets in constants:
 2708: 
 2709: @example
 2710: 0 constant a-offset
 2711: 0 float+ constant b-offset
 2712: 0 float+ cell+ faligned c-offset
 2713: @end example
 2714: 
 2715: Now we can get the address of field @code{x} with @code{x-offset
 2716: +}. This is much better in all respects. Of course, you still
 2717: have to change all later offset definitions if you add a field. You can
 2718: fix this by declaring the offsets in the following way:
 2719: 
 2720: @example
 2721: 0 constant a-offset
 2722: a-offset float+ constant b-offset
 2723: b-offset cell+ faligned constant c-offset
 2724: @end example
 2725: 
 2726: Since we always use the offsets with @code{+}, using a defining
 2727: word @code{cfield} that includes the @code{+} in the
 2728: action of the defined word offers itself:
 2729: 
 2730: @example
 2731: : cfield ( n "name" -- )
 2732:     create ,
 2733: does> ( name execution: addr1 -- addr2 )
 2734:     @@ + ;
 2735: 
 2736: 0 cfield a
 2737: 0 a float+ cfield b
 2738: 0 b cell+ faligned cfield c
 2739: @end example
 2740: 
 2741: Instead of @code{x-offset +}, we now simply write @code{x}.
 2742: 
 2743: The structure field words now can be used quite nicely. However,
 2744: their definition is still a bit cumbersome: We have to repeat the
 2745: name, the information about size and alignment is distributed before
 2746: and after the field definitions etc.  The structure package presented
 2747: here addresses these problems.
 2748: 
 2749: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
 2750: @subsection Structure Usage
 2751: @cindex structure usage
 2752: 
 2753: @cindex @code{field} usage
 2754: @cindex @code{struct} usage
 2755: @cindex @code{end-struct} usage
 2756: You can define a structure for a (data-less) linked list with
 2757: @example
 2758: struct
 2759:     cell% field list-next
 2760: end-struct list%
 2761: @end example
 2762: 
 2763: With the address of the list node on the stack, you can compute the
 2764: address of the field that contains the address of the next node with
 2765: @code{list-next}. E.g., you can determine the length of a list
 2766: with:
 2767: 
 2768: @example
 2769: : list-length ( list -- n )
 2770: \ "list" is a pointer to the first element of a linked list
 2771: \ "n" is the length of the list
 2772:     0 begin ( list1 n1 )
 2773:         over
 2774:     while ( list1 n1 )
 2775:         1+ swap list-next @@ swap
 2776:     repeat
 2777:     nip ;
 2778: @end example
 2779: 
 2780: You can reserve memory for a list node in the dictionary with
 2781: @code{list% %allot}, which leaves the address of the list node on the
 2782: stack. For the equivalent allocation on the heap you can use @code{list%
 2783: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
 2784: use @code{list% %allocate}). You can also get the the size of a list
 2785: node with @code{list% %size} and it's alignment with @code{list%
 2786: %alignment}.
 2787: 
 2788: Note that in ANS Forth the body of a @code{create}d word is
 2789: @code{aligned} but not necessarily @code{faligned};
 2790: therefore, if you do a
 2791: @example
 2792: create @emph{name} foo% %allot
 2793: @end example
 2794: 
 2795: then the memory alloted for @code{foo%} is
 2796: guaranteed to start at the body of @code{@emph{name}} only if
 2797: @code{foo%} contains only character, cell and double fields.
 2798: 
 2799: @cindex strcutures containing structures
 2800: You can also include a structure @code{foo%} as field of
 2801: another structure, with:
 2802: @example
 2803: struct
 2804: ...
 2805:     foo% field ...
 2806: ...
 2807: end-struct ...
 2808: @end example
 2809: 
 2810: @cindex structure extension
 2811: @cindex extended records
 2812: Instead of starting with an empty structure, you can also extend an
 2813: existing structure. E.g., a plain linked list without data, as defined
 2814: above, is hardly useful; You can extend it to a linked list of integers,
 2815: like this:@footnote{This feature is also known as @emph{extended
 2816: records}. It is the main innovation in the Oberon language; in other
 2817: words, adding this feature to Modula-2 led Wirth to create a new
 2818: language, write a new compiler etc.  Adding this feature to Forth just
 2819: requires a few lines of code.}
 2820: 
 2821: @example
 2822: list%
 2823:     cell% field intlist-int
 2824: end-struct intlist%
 2825: @end example
 2826: 
 2827: @code{intlist%} is a structure with two fields:
 2828: @code{list-next} and @code{intlist-int}.
 2829: 
 2830: @cindex structures containing arrays
 2831: You can specify an array type containing @emph{n} elements of
 2832: type @code{foo%} like this:
 2833: 
 2834: @example
 2835: foo% @emph{n} *
 2836: @end example
 2837: 
 2838: You can use this array type in any place where you can use a normal
 2839: type, e.g., when defining a @code{field}, or with
 2840: @code{%allot}.
 2841: 
 2842: @cindex first field optimization
 2843: The first field is at the base address of a structure and the word
 2844: for this field (e.g., @code{list-next}) actually does not change
 2845: the address on the stack. You may be tempted to leave it away in the
 2846: interest of run-time and space efficiency. This is not necessary,
 2847: because the structure package optimizes this case and compiling such
 2848: words does not generate any code. So, in the interest of readability
 2849: and maintainability you should include the word for the field when
 2850: accessing the field.
 2851: 
 2852: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
 2853: @subsection Structure Naming Convention
 2854: @cindex structure naming conventions
 2855: 
 2856: The field names that come to (my) mind are often quite generic, and,
 2857: if used, would cause frequent name clashes. E.g., many structures
 2858: probably contain a @code{counter} field. The structure names
 2859: that come to (my) mind are often also the logical choice for the names
 2860: of words that create such a structure.
 2861: 
 2862: Therefore, I have adopted the following naming conventions: 
 2863: 
 2864: @itemize @bullet
 2865: @cindex field naming convention
 2866: @item
 2867: The names of fields are of the form
 2868: @code{@emph{struct}-@emph{field}}, where
 2869: @code{@emph{struct}} is the basic name of the structure, and
 2870: @code{@emph{field}} is the basic name of the field. You can
 2871: think about field words as converting converts the (address of the)
 2872: structure into the (address of the) field.
 2873: 
 2874: @cindex structure naming convention
 2875: @item
 2876: The names of structures are of the form
 2877: @code{@emph{struct}%}, where
 2878: @code{@emph{struct}} is the basic name of the structure.
 2879: @end itemize
 2880: 
 2881: This naming convention does not work that well for fields of extended
 2882: structures; e.g., the integer list structure has a field
 2883: @code{intlist-int}, but has @code{list-next}, not
 2884: @code{intlist-next}.
 2885: 
 2886: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
 2887: @subsection Structure Implementation
 2888: @cindex structure implementation
 2889: @cindex implementation of structures
 2890: 
 2891: The central idea in the implementation is to pass the data about the
 2892: structure being built on the stack, not in some global
 2893: variable. Everything else falls into place naturally once this design
 2894: decision is made.
 2895: 
 2896: The type description on the stack is of the form @emph{align
 2897: size}. Keeping the size on the top-of-stack makes dealing with arrays
 2898: very simple.
 2899: 
 2900: @code{field} is a defining word that uses @code{create}
 2901: and @code{does>}. The body of the field contains the offset
 2902: of the field, and the normal @code{does>} action is
 2903: 
 2904: @example
 2905: @ +
 2906: @end example
 2907: 
 2908: i.e., add the offset to the address, giving the stack effect
 2909: @code{addr1 -- addr2} for a field.
 2910: 
 2911: @cindex first field optimization, implementation
 2912: This simple structure is slightly complicated by the optimization
 2913: for fields with offset 0, which requires a different
 2914: @code{does>}-part (because we cannot rely on there being
 2915: something on the stack if such a field is invoked during
 2916: compilation). Therefore, we put the different @code{does>}-parts
 2917: in separate words, and decide which one to invoke based on the
 2918: offset. For a zero offset, the field is basically a noop; it is
 2919: immediate, and therefore no code is generated when it is compiled.
 2920: 
 2921: @node Structure Glossary,  , Structure Implementation, Structures
 2922: @subsection Structure Glossary
 2923: @cindex structure glossary
 2924: 
 2925: doc-%align
 2926: doc-%alignment
 2927: doc-%alloc
 2928: doc-%allocate
 2929: doc-%allot
 2930: doc-cell%
 2931: doc-char%
 2932: doc-dfloat%
 2933: doc-double%
 2934: doc-end-struct
 2935: doc-field
 2936: doc-float%
 2937: doc-nalign
 2938: doc-sfloat%
 2939: doc-%size
 2940: doc-struct
 2941: 
 2942: @c -------------------------------------------------------------
 2943: @node Objects, Object Oriented Forth, Structures, Words
 2944: @section Objects
 2945: @cindex objects
 2946: @cindex object-oriented programming
 2947: 
 2948: @cindex @file{objects.fs}
 2949: @cindex @file{oof.fs}
 2950: Gforth comes with two packets for object-oriented programming,
 2951: @file{objects.fs} and @file{oof.fs}; none of them is preloaded, so you
 2952: have to @code{include} them before use. This section describes the
 2953: @file{objects.fs} packet. You can find a description (in German) of
 2954: @file{oof.fs} in @cite{Object oriented bigFORTH} by Bernd Paysan,
 2955: published in @cite{Vierte Dimension} 10(2), 1994. Both packets are
 2956: written in ANS Forth and can be used with any other standard Forth.
 2957: @c McKewan's and Zsoter's packages
 2958: @c this section is a variant of ...
 2959: 
 2960: This section assumes (in some places) that you have read @ref{Structures}.
 2961: 
 2962: @menu
 2963: * Properties of the Objects model::  
 2964: * Why object-oriented programming?::  
 2965: * Object-Oriented Terminology::  
 2966: * Basic Objects Usage::         
 2967: * The class Object::            
 2968: * Creating objects::            
 2969: * Object-Oriented Programming Style::  
 2970: * Class Binding::               
 2971: * Method conveniences::         
 2972: * Classes and Scoping::         
 2973: * Object Interfaces::           
 2974: * Objects Implementation::      
 2975: * Comparison with other object models::  
 2976: * Objects Glossary::            
 2977: @end menu
 2978: 
 2979: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
 2980: and Bernd Paysan helped me with the related works section.
 2981: 
 2982: @node Properties of the Objects model, Why object-oriented programming?, Objects, Objects
 2983: @subsection Properties of the @file{objects.fs} model
 2984: @cindex @file{objects.fs} properties
 2985: 
 2986: @itemize @bullet
 2987: @item
 2988: It is straightforward to pass objects on the stack. Passing
 2989: selectors on the stack is a little less convenient, but possible.
 2990: 
 2991: @item
 2992: Objects are just data structures in memory, and are referenced by
 2993: their address. You can create words for objects with normal defining
 2994: words like @code{constant}. Likewise, there is no difference
 2995: between instance variables that contain objects and those
 2996: that contain other data.
 2997: 
 2998: @item
 2999: Late binding is efficient and easy to use.
 3000: 
 3001: @item
 3002: It avoids parsing, and thus avoids problems with state-smartness
 3003: and reduced extensibility; for convenience there are a few parsing
 3004: words, but they have non-parsing counterparts. There are also a few
 3005: defining words that parse. This is hard to avoid, because all standard
 3006: defining words parse (except @code{:noname}); however, such
 3007: words are not as bad as many other parsing words, because they are not
 3008: state-smart.
 3009: 
 3010: @item
 3011: It does not try to incorporate everything. It does a few things
 3012: and does them well (IMO). In particular, I did not intend to support
 3013: information hiding with this model (although it has features that may
 3014: help); you can use a separate package for achieving this.
 3015: 
 3016: @item
 3017: It is layered; you don't have to learn and use all features to use this
 3018: model. Only a few features are necessary (@xref{Basic Objects Usage},
 3019: @xref{The class Object}, @xref{Creating objects}.), the others
 3020: are optional and independent of each other.
 3021: 
 3022: @item
 3023: An implementation in ANS Forth is available.
 3024: 
 3025: @end itemize
 3026: 
 3027: I have used the technique, on which this model is based, for
 3028: implementing the parser generator Gray; we have also used this technique
 3029: in Gforth for implementing the various flavours of wordlists (hashed or
 3030: not, case-sensitive or not, special-purpose wordlists for locals etc.).
 3031: 
 3032: @node Why object-oriented programming?, Object-Oriented Terminology, Properties of the Objects model, Objects
 3033: @subsection Why object-oriented programming?
 3034: @cindex object-oriented programming motivation
 3035: @cindex motivation for object-oriented programming
 3036: 
 3037: Often we have to deal with several data structures (@emph{objects}),
 3038: that have to be treated similarly in some respects, but differ in
 3039: others. Graphical objects are the textbook example: circles,
 3040: triangles, dinosaurs, icons, and others, and we may want to add more
 3041: during program development. We want to apply some operations to any
 3042: graphical object, e.g., @code{draw} for displaying it on the
 3043: screen. However, @code{draw} has to do something different for
 3044: every kind of object.
 3045: 
 3046: We could implement @code{draw} as a big @code{CASE}
 3047: control structure that executes the appropriate code depending on the
 3048: kind of object to be drawn. This would be not be very elegant, and,
 3049: moreover, we would have to change @code{draw} every time we add
 3050: a new kind of graphical object (say, a spaceship).
 3051: 
 3052: What we would rather do is: When defining spaceships, we would tell
 3053: the system: "Here's how you @code{draw} a spaceship; you figure
 3054: out the rest."
 3055: 
 3056: This is the problem that all systems solve that (rightfully) call
 3057: themselves object-oriented, and the object-oriented package I present
 3058: here also solves this problem (and not much else).
 3059: 
 3060: @node Object-Oriented Terminology, Basic Objects Usage, Why object-oriented programming?, Objects
 3061: @subsection Object-Oriented Terminology
 3062: @cindex object-oriented terminology
 3063: @cindex terminology for object-oriented programming
 3064: 
 3065: This section is mainly for reference, so you don't have to understand
 3066: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
 3067: short:
 3068: 
 3069: @table @emph
 3070: @cindex class
 3071: @item class
 3072: a data structure definition with some extras.
 3073: 
 3074: @cindex object
 3075: @item object
 3076: an instance of the data structure described by the class definition.
 3077: 
 3078: @cindex instance variables
 3079: @item instance variables
 3080: fields of the data structure.
 3081: 
 3082: @cindex selector
 3083: @cindex method selector
 3084: @cindex virtual function
 3085: @item selector
 3086: (or @emph{method selector}) a word (e.g.,
 3087: @code{draw}) for performing an operation on a variety of data
 3088: structures (classes). A selector describes @emph{what} operation to
 3089: perform. In C++ terminology: a (pure) virtual function.
 3090: 
 3091: @cindex method
 3092: @item method
 3093: the concrete definition that performs the operation
 3094: described by the selector for a specific class. A method specifies
 3095: @emph{how} the operation is performed for a specific class.
 3096: 
 3097: @cindex selector invocation
 3098: @cindex message send
 3099: @cindex invoking a selector
 3100: @item selector invocation
 3101: a call of a selector. One argument of the call (the TOS (top-of-stack))
 3102: is used for determining which method is used. In Smalltalk terminology:
 3103: a message (consisting of the selector and the other arguments) is sent
 3104: to the object.
 3105: 
 3106: @cindex receiving object
 3107: @item receiving object
 3108: the object used for determining the method executed by a selector
 3109: invocation. In our model it is the object that is on the TOS when the
 3110: selector is invoked. (@emph{Receiving} comes from Smalltalks
 3111: @emph{message} terminology.)
 3112: 
 3113: @cindex child class
 3114: @cindex parent class
 3115: @cindex inheritance
 3116: @item child class
 3117: a class that has (@emph{inherits}) all properties (instance variables,
 3118: selectors, methods) from a @emph{parent class}. In Smalltalk
 3119: terminology: The subclass inherits from the superclass. In C++
 3120: terminology: The derived class inherits from the base class.
 3121: 
 3122: @end table
 3123: 
 3124: @c If you wonder about the message sending terminology, it comes from
 3125: @c a time when each object had it's own task and objects communicated via
 3126: @c message passing; eventually the Smalltalk developers realized that
 3127: @c they can do most things through simple (indirect) calls. They kept the
 3128: @c terminology.
 3129: 
 3130: @node Basic Objects Usage, The class Object, Object-Oriented Terminology, Objects
 3131: @subsection Basic Objects Usage
 3132: @cindex basic objects usage
 3133: @cindex objects, basic usage
 3134: 
 3135: You can define a class for graphical objects like this:
 3136: 
 3137: @cindex @code{class} usage
 3138: @cindex @code{end-class} usage
 3139: @cindex @code{selector} usage
 3140: @example
 3141: object class \ "object" is the parent class
 3142:   selector draw ( x y graphical -- )
 3143: end-class graphical
 3144: @end example
 3145: 
 3146: This code defines a class @code{graphical} with an
 3147: operation @code{draw}.  We can perform the operation
 3148: @code{draw} on any @code{graphical} object, e.g.:
 3149: 
 3150: @example
 3151: 100 100 t-rex draw
 3152: @end example
 3153: 
 3154: where @code{t-rex} is a word (say, a constant) that produces a
 3155: graphical object.
 3156: 
 3157: @cindex abstract class
 3158: How do we create a graphical object? With the present definitions,
 3159: we cannot create a useful graphical object. The class
 3160: @code{graphical} describes graphical objects in general, but not
 3161: any concrete graphical object type (C++ users would call it an
 3162: @emph{abstract class}); e.g., there is no method for the selector
 3163: @code{draw} in the class @code{graphical}.
 3164: 
 3165: For concrete graphical objects, we define child classes of the
 3166: class @code{graphical}, e.g.:
 3167: 
 3168: @cindex @code{overrides} usage
 3169: @cindex @code{field} usage in class definition
 3170: @example
 3171: graphical class \ "graphical" is the parent class
 3172:   cell% field circle-radius
 3173: 
 3174: :noname ( x y circle -- )
 3175:   circle-radius @@ draw-circle ;
 3176: overrides draw
 3177: 
 3178: :noname ( n-radius circle -- )
 3179:   circle-radius ! ;
 3180: overrides construct
 3181: 
 3182: end-class circle
 3183: @end example
 3184: 
 3185: Here we define a class @code{circle} as a child of @code{graphical},
 3186: with a field @code{circle-radius} (which behaves just like a field in
 3187: @pxref{Structures}); it defines new methods for the selectors
 3188: @code{draw} and @code{construct} (@code{construct} is defined in
 3189: @code{object}, the parent class of @code{graphical}).
 3190: 
 3191: Now we can create a circle on the heap (i.e.,
 3192: @code{allocate}d memory) with
 3193: 
 3194: @cindex @code{heap-new} usage
 3195: @example
 3196: 50 circle heap-new constant my-circle
 3197: @end example
 3198: 
 3199: @code{heap-new} invokes @code{construct}, thus
 3200: initializing the field @code{circle-radius} with 50. We can draw
 3201: this new circle at (100,100) with
 3202: 
 3203: @example
 3204: 100 100 my-circle draw
 3205: @end example
 3206: 
 3207: @cindex selector invocation, restrictions
 3208: @cindex class definition, restrictions
 3209: Note: You can invoke a selector only if the object on the TOS
 3210: (the receiving object) belongs to the class where the selector was
 3211: defined or one of its descendents; e.g., you can invoke
 3212: @code{draw} only for objects belonging to @code{graphical}
 3213: or its descendents (e.g., @code{circle}).  Immediately before
 3214: @code{end-class}, the search order has to be the same as
 3215: immediately after @code{class}.
 3216: 
 3217: @node The class Object, Creating objects, Basic Objects Usage, Objects
 3218: @subsection The class @code{object}
 3219: @cindex @code{object} class
 3220: 
 3221: When you define a class, you have to specify a parent class.  So how do
 3222: you start defining classes? There is one class available from the start:
 3223: @code{object}. You can use it as ancestor for all classes. It is the
 3224: only class that has no parent. It has two selectors: @code{construct}
 3225: and @code{print}.
 3226: 
 3227: @node Creating objects, Object-Oriented Programming Style, The class Object, Objects
 3228: @subsection Creating objects
 3229: @cindex creating objects
 3230: @cindex object creation
 3231: @cindex object allocation options
 3232: 
 3233: @cindex @code{heap-new} discussion
 3234: @cindex @code{dict-new} discussion
 3235: @cindex @code{construct} discussion
 3236: You can create and initialize an object of a class on the heap with
 3237: @code{heap-new} ( ... class -- object ) and in the dictionary
 3238: (allocation with @code{allot}) with @code{dict-new} (
 3239: ... class -- object ). Both words invoke @code{construct}, which
 3240: consumes the stack items indicated by "..." above.
 3241: 
 3242: @cindex @code{init-object} discussion
 3243: @cindex @code{class-inst-size} discussion
 3244: If you want to allocate memory for an object yourself, you can get its
 3245: alignment and size with @code{class-inst-size 2@@} ( class --
 3246: align size ). Once you have memory for an object, you can initialize
 3247: it with @code{init-object} ( ... class object -- );
 3248: @code{construct} does only a part of the necessary work.
 3249: 
 3250: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
 3251: @subsection Object-Oriented Programming Style
 3252: @cindex object-oriented programming style
 3253: 
 3254: This section is not exhaustive.
 3255: 
 3256: @cindex stack effects of selectors
 3257: @cindex selectors and stack effects
 3258: In general, it is a good idea to ensure that all methods for the
 3259: same selector have the same stack effect: when you invoke a selector,
 3260: you often have no idea which method will be invoked, so, unless all
 3261: methods have the same stack effect, you will not know the stack effect
 3262: of the selector invocation.
 3263: 
 3264: One exception to this rule is methods for the selector
 3265: @code{construct}. We know which method is invoked, because we
 3266: specify the class to be constructed at the same place. Actually, I
 3267: defined @code{construct} as a selector only to give the users a
 3268: convenient way to specify initialization. The way it is used, a
 3269: mechanism different from selector invocation would be more natural
 3270: (but probably would take more code and more space to explain).
 3271: 
 3272: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
 3273: @subsection Class Binding
 3274: @cindex class binding
 3275: @cindex early binding
 3276: 
 3277: @cindex late binding
 3278: Normal selector invocations determine the method at run-time depending
 3279: on the class of the receiving object (late binding).
 3280: 
 3281: Sometimes we want to invoke a different method. E.g., assume that
 3282: you want to use the simple method for @code{print}ing
 3283: @code{object}s instead of the possibly long-winded
 3284: @code{print} method of the receiver class. You can achieve this
 3285: by replacing the invocation of @code{print} with
 3286: 
 3287: @cindex @code{[bind]} usage
 3288: @example
 3289: [bind] object print
 3290: @end example
 3291: 
 3292: in compiled code or
 3293: 
 3294: @cindex @code{bind} usage
 3295: @example
 3296: bind object print
 3297: @end example
 3298: 
 3299: @cindex class binding, alternative to
 3300: in interpreted code. Alternatively, you can define the method with a
 3301: name (e.g., @code{print-object}), and then invoke it through the
 3302: name. Class binding is just a (often more convenient) way to achieve
 3303: the same effect; it avoids name clutter and allows you to invoke
 3304: methods directly without naming them first.
 3305: 
 3306: @cindex superclass binding
 3307: @cindex parent class binding
 3308: A frequent use of class binding is this: When we define a method
 3309: for a selector, we often want the method to do what the selector does
 3310: in the parent class, and a little more. There is a special word for
 3311: this purpose: @code{[parent]}; @code{[parent]
 3312: @emph{selector}} is equivalent to @code{[bind] @emph{parent
 3313: selector}}, where @code{@emph{parent}} is the parent
 3314: class of the current class. E.g., a method definition might look like:
 3315: 
 3316: @cindex @code{[parent]} usage
 3317: @example
 3318: :noname
 3319:   dup [parent] foo \ do parent's foo on the receiving object
 3320:   ... \ do some more
 3321: ; overrides foo
 3322: @end example
 3323: 
 3324: @cindex class binding as optimization
 3325: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
 3326: March 1997), Andrew McKewan presents class binding as an optimization
 3327: technique. I recommend not using it for this purpose unless you are in
 3328: an emergency. Late binding is pretty fast with this model anyway, so the
 3329: benefit of using class binding is small; the cost of using class binding
 3330: where it is not appropriate is reduced maintainability.
 3331: 
 3332: While we are at programming style questions: You should bind
 3333: selectors only to ancestor classes of the receiving object. E.g., say,
 3334: you know that the receiving object is of class @code{foo} or its
 3335: descendents; then you should bind only to @code{foo} and its
 3336: ancestors.
 3337: 
 3338: @node Method conveniences, Classes and Scoping, Class Binding, Objects
 3339: @subsection Method conveniences
 3340: @cindex method conveniences
 3341: 
 3342: In a method you usually access the receiving object pretty often.  If
 3343: you define the method as a plain colon definition (e.g., with
 3344: @code{:noname}), you may have to do a lot of stack
 3345: gymnastics. To avoid this, you can define the method with @code{m:
 3346: ... ;m}. E.g., you could define the method for
 3347: @code{draw}ing a @code{circle} with
 3348: 
 3349: @cindex @code{this} usage
 3350: @cindex @code{m:} usage
 3351: @cindex @code{;m} usage
 3352: @example
 3353: m: ( x y circle -- )
 3354:   ( x y ) this circle-radius @@ draw-circle ;m
 3355: @end example
 3356: 
 3357: @cindex @code{exit} in @code{m: ... ;m}
 3358: @cindex @code{exitm} discussion
 3359: @cindex @code{catch} in @code{m: ... ;m}
 3360: When this method is executed, the receiver object is removed from the
 3361: stack; you can access it with @code{this} (admittedly, in this
 3362: example the use of @code{m: ... ;m} offers no advantage). Note
 3363: that I specify the stack effect for the whole method (i.e. including
 3364: the receiver object), not just for the code between @code{m:}
 3365: and @code{;m}. You cannot use @code{exit} in
 3366: @code{m:...;m}; instead, use
 3367: @code{exitm}.@footnote{Moreover, for any word that calls
 3368: @code{catch} and was defined before loading
 3369: @code{objects.fs}, you have to redefine it like I redefined
 3370: @code{catch}: @code{: catch this >r catch r> to-this ;}}
 3371: 
 3372: @cindex @code{inst-var} usage
 3373: You will frequently use sequences of the form @code{this
 3374: @emph{field}} (in the example above: @code{this
 3375: circle-radius}). If you use the field only in this way, you can
 3376: define it with @code{inst-var} and eliminate the
 3377: @code{this} before the field name. E.g., the @code{circle}
 3378: class above could also be defined with:
 3379: 
 3380: @example
 3381: graphical class
 3382:   cell% inst-var radius
 3383: 
 3384: m: ( x y circle -- )
 3385:   radius @@ draw-circle ;m
 3386: overrides draw
 3387: 
 3388: m: ( n-radius circle -- )
 3389:   radius ! ;m
 3390: overrides construct
 3391: 
 3392: end-class circle
 3393: @end example
 3394: 
 3395: @code{radius} can only be used in @code{circle} and its
 3396: descendent classes and inside @code{m:...;m}.
 3397: 
 3398: @cindex @code{inst-value} usage
 3399: You can also define fields with @code{inst-value}, which is
 3400: to @code{inst-var} what @code{value} is to
 3401: @code{variable}.  You can change the value of such a field with
 3402: @code{[to-inst]}.  E.g., we could also define the class
 3403: @code{circle} like this:
 3404: 
 3405: @example
 3406: graphical class
 3407:   inst-value radius
 3408: 
 3409: m: ( x y circle -- )
 3410:   radius draw-circle ;m
 3411: overrides draw
 3412: 
 3413: m: ( n-radius circle -- )
 3414:   [to-inst] radius ;m
 3415: overrides construct
 3416: 
 3417: end-class circle
 3418: @end example
 3419: 
 3420: 
 3421: @node Classes and Scoping, Object Interfaces, Method conveniences, Objects
 3422: @subsection Classes and Scoping
 3423: @cindex classes and scoping
 3424: @cindex scoping and classes
 3425: 
 3426: Inheritance is frequent, unlike structure extension. This exacerbates
 3427: the problem with the field name convention (@pxref{Structure Naming
 3428: Convention}): One always has to remember in which class the field was
 3429: originally defined; changing a part of the class structure would require
 3430: changes for renaming in otherwise unaffected code.
 3431: 
 3432: @cindex @code{inst-var} visibility
 3433: @cindex @code{inst-value} visibility
 3434: To solve this problem, I added a scoping mechanism (which was not in my
 3435: original charter): A field defined with @code{inst-var} (or
 3436: @code{inst-value}) is visible only in the class where it is defined and in
 3437: the descendent classes of this class.  Using such fields only makes
 3438: sense in @code{m:}-defined methods in these classes anyway.
 3439: 
 3440: This scoping mechanism allows us to use the unadorned field name,
 3441: because name clashes with unrelated words become much less likely.
 3442: 
 3443: @cindex @code{protected} discussion
 3444: @cindex @code{private} discussion
 3445: Once we have this mechanism, we can also use it for controlling the
 3446: visibility of other words: All words defined after
 3447: @code{protected} are visible only in the current class and its
 3448: descendents. @code{public} restores the compilation
 3449: (i.e. @code{current}) wordlist that was in effect before. If you
 3450: have several @code{protected}s without an intervening
 3451: @code{public} or @code{set-current}, @code{public}
 3452: will restore the compilation wordlist in effect before the first of
 3453: these @code{protected}s.
 3454: 
 3455: @node Object Interfaces, Objects Implementation, Classes and Scoping, Objects
 3456: @subsection Object Interfaces
 3457: @cindex object interfaces
 3458: @cindex interfaces for objects
 3459: 
 3460: In this model you can only call selectors defined in the class of the
 3461: receiving objects or in one of its ancestors. If you call a selector
 3462: with a receiving object that is not in one of these classes, the
 3463: result is undefined; if you are lucky, the program crashes
 3464: immediately.
 3465: 
 3466: @cindex selectors common to hardly-related classes
 3467: Now consider the case when you want to have a selector (or several)
 3468: available in two classes: You would have to add the selector to a
 3469: common ancestor class, in the worst case to @code{object}. You
 3470: may not want to do this, e.g., because someone else is responsible for
 3471: this ancestor class.
 3472: 
 3473: The solution for this problem is interfaces. An interface is a
 3474: collection of selectors. If a class implements an interface, the
 3475: selectors become available to the class and its descendents. A class
 3476: can implement an unlimited number of interfaces. For the problem
 3477: discussed above, we would define an interface for the selector(s), and
 3478: both classes would implement the interface.
 3479: 
 3480: As an example, consider an interface @code{storage} for
 3481: writing objects to disk and getting them back, and a class
 3482: @code{foo} foo that implements it. The code for this would look
 3483: like this:
 3484: 
 3485: @cindex @code{interface} usage
 3486: @cindex @code{end-interface} usage
 3487: @cindex @code{implementation} usage
 3488: @example
 3489: interface
 3490:   selector write ( file object -- )
 3491:   selector read1 ( file object -- )
 3492: end-interface storage
 3493: 
 3494: bar class
 3495:   storage implementation
 3496: 
 3497: ... overrides write
 3498: ... overrides read
 3499: ...
 3500: end-class foo
 3501: @end example
 3502: 
 3503: (I would add a word @code{read} ( file -- object ) that uses
 3504: @code{read1} internally, but that's beyond the point illustrated
 3505: here.)
 3506: 
 3507: Note that you cannot use @code{protected} in an interface; and
 3508: of course you cannot define fields.
 3509: 
 3510: In the Neon model, all selectors are available for all classes;
 3511: therefore it does not need interfaces. The price you pay in this model
 3512: is slower late binding, and therefore, added complexity to avoid late
 3513: binding.
 3514: 
 3515: @node Objects Implementation, Comparison with other object models, Object Interfaces, Objects
 3516: @subsection @file{objects.fs} Implementation
 3517: @cindex @file{objects.fs} implementation
 3518: 
 3519: @cindex @code{object-map} discussion
 3520: An object is a piece of memory, like one of the data structures
 3521: described with @code{struct...end-struct}. It has a field
 3522: @code{object-map} that points to the method map for the object's
 3523: class.
 3524: 
 3525: @cindex method map
 3526: @cindex virtual function table
 3527: The @emph{method map}@footnote{This is Self terminology; in C++
 3528: terminology: virtual function table.} is an array that contains the
 3529: execution tokens (XTs) of the methods for the object's class. Each
 3530: selector contains an offset into the method maps.
 3531: 
 3532: @cindex @code{selector} implementation, class
 3533: @code{selector} is a defining word that uses
 3534: @code{create} and @code{does>}. The body of the
 3535: selector contains the offset; the @code{does>} action for a
 3536: class selector is, basically:
 3537: 
 3538: @example
 3539: ( object addr ) @@ over object-map @@ + @@ execute
 3540: @end example
 3541: 
 3542: Since @code{object-map} is the first field of the object, it
 3543: does not generate any code. As you can see, calling a selector has a
 3544: small, constant cost.
 3545: 
 3546: @cindex @code{current-interface} discussion
 3547: @cindex class implementation and representation
 3548: A class is basically a @code{struct} combined with a method
 3549: map. During the class definition the alignment and size of the class
 3550: are passed on the stack, just as with @code{struct}s, so
 3551: @code{field} can also be used for defining class
 3552: fields. However, passing more items on the stack would be
 3553: inconvenient, so @code{class} builds a data structure in memory,
 3554: which is accessed through the variable
 3555: @code{current-interface}. After its definition is complete, the
 3556: class is represented on the stack by a pointer (e.g., as parameter for
 3557: a child class definition).
 3558: 
 3559: At the start, a new class has the alignment and size of its parent,
 3560: and a copy of the parent's method map. Defining new fields extends the
 3561: size and alignment; likewise, defining new selectors extends the
 3562: method map. @code{overrides} just stores a new XT in the method
 3563: map at the offset given by the selector.
 3564: 
 3565: @cindex class binding, implementation
 3566: Class binding just gets the XT at the offset given by the selector
 3567: from the class's method map and @code{compile,}s (in the case of
 3568: @code{[bind]}) it.
 3569: 
 3570: @cindex @code{this} implementation
 3571: @cindex @code{catch} and @code{this}
 3572: @cindex @code{this} and @code{catch}
 3573: I implemented @code{this} as a @code{value}. At the
 3574: start of an @code{m:...;m} method the old @code{this} is
 3575: stored to the return stack and restored at the end; and the object on
 3576: the TOS is stored @code{TO this}. This technique has one
 3577: disadvantage: If the user does not leave the method via
 3578: @code{;m}, but via @code{throw} or @code{exit},
 3579: @code{this} is not restored (and @code{exit} may
 3580: crash). To deal with the @code{throw} problem, I have redefined
 3581: @code{catch} to save and restore @code{this}; the same
 3582: should be done with any word that can catch an exception. As for
 3583: @code{exit}, I simply forbid it (as a replacement, there is
 3584: @code{exitm}).
 3585: 
 3586: @cindex @code{inst-var} implementation
 3587: @code{inst-var} is just the same as @code{field}, with
 3588: a different @code{does>} action:
 3589: @example
 3590: @@ this +
 3591: @end example
 3592: Similar for @code{inst-value}.
 3593: 
 3594: @cindex class scoping implementation
 3595: Each class also has a wordlist that contains the words defined with
 3596: @code{inst-var} and @code{inst-value}, and its protected
 3597: words. It also has a pointer to its parent. @code{class} pushes
 3598: the wordlists of the class an all its ancestors on the search order,
 3599: and @code{end-class} drops them.
 3600: 
 3601: @cindex interface implementation
 3602: An interface is like a class without fields, parent and protected
 3603: words; i.e., it just has a method map. If a class implements an
 3604: interface, its method map contains a pointer to the method map of the
 3605: interface. The positive offsets in the map are reserved for class
 3606: methods, therefore interface map pointers have negative
 3607: offsets. Interfaces have offsets that are unique throughout the
 3608: system, unlike class selectors, whose offsets are only unique for the
 3609: classes where the selector is available (invokable).
 3610: 
 3611: This structure means that interface selectors have to perform one
 3612: indirection more than class selectors to find their method. Their body
 3613: contains the interface map pointer offset in the class method map, and
 3614: the method offset in the interface method map. The
 3615: @code{does>} action for an interface selector is, basically:
 3616: 
 3617: @example
 3618: ( object selector-body )
 3619: 2dup selector-interface @@ ( object selector-body object interface-offset )
 3620: swap object-map @@ + @@ ( object selector-body map )
 3621: swap selector-offset @@ + @@ execute
 3622: @end example
 3623: 
 3624: where @code{object-map} and @code{selector-offset} are
 3625: first fields and generate no code.
 3626: 
 3627: As a concrete example, consider the following code:
 3628: 
 3629: @example
 3630: interface
 3631:   selector if1sel1
 3632:   selector if1sel2
 3633: end-interface if1
 3634: 
 3635: object class
 3636:   if1 implementation
 3637:   selector cl1sel1
 3638:   cell% inst-var cl1iv1
 3639: 
 3640: ' m1 overrides construct
 3641: ' m2 overrides if1sel1
 3642: ' m3 overrides if1sel2
 3643: ' m4 overrides cl1sel2
 3644: end-class cl1
 3645: 
 3646: create obj1 object dict-new drop
 3647: create obj2 cl1    dict-new drop
 3648: @end example
 3649: 
 3650: The data structure created by this code (including the data structure
 3651: for @code{object}) is shown in the <a
 3652: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
 3653: 
 3654: @node Comparison with other object models, Objects Glossary, Objects Implementation, Objects
 3655: @subsection Comparison with other object models
 3656: @cindex comparison of object models
 3657: @cindex object models, comparison
 3658: 
 3659: Many object-oriented Forth extensions have been proposed (@cite{A survey
 3660: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
 3661: J. Rodriguez and W. F. S. Poehlman lists 17). Here I'll discuss the
 3662: relation of @file{objects.fs} to two well-known and two closely-related
 3663: (by the use of method maps) models.
 3664: 
 3665: @cindex Neon model
 3666: The most popular model currently seems to be the Neon model (see
 3667: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
 3668: 1997) by Andrew McKewan). The Neon model uses a @code{@emph{selector
 3669: object}} syntax, which makes it unnatural to pass objects on the
 3670: stack. It also requires that the selector parses the input stream (at
 3671: compile time); this leads to reduced extensibility and to bugs that are
 3672: hard to find. Finally, it allows using every selector to every object;
 3673: this eliminates the need for classes, but makes it harder to create
 3674: efficient implementations. A longer version of this critique can be
 3675: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
 3676: Dimensions, May 1997) by Anton Ertl.
 3677: 
 3678: @cindex Pountain's object-oriented model
 3679: Another well-known publication is @cite{Object-Oriented Forth} (Academic
 3680: Press, London, 1987) by Dick Pountain. However, it is not really about
 3681: object-oriented programming, because it hardly deals with late
 3682: binding. Instead, it focuses on features like information hiding and
 3683: overloading that are characteristic of modular languages like Ada (83).
 3684: 
 3685: @cindex Zsoter's object-oriented model
 3686: In @cite{Does late binding have to be slow?} (Forth Dimensions ??? 1996)
 3687: Andras Zsoter describes a model that makes heavy use of an active object
 3688: (like @code{this} in @file{objects.fs}): The active object is not only
 3689: used for accessing all fields, but also specifies the receiving object
 3690: of every selector invocation; you have to change the active object
 3691: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
 3692: changes more or less implicitly at @code{m: ... ;m}. Such a change at
 3693: the method entry point is unnecessary with the Zsoter's model, because
 3694: the receiving object is the active object already; OTOH, the explicit
 3695: change is absolutely necessary in that model, because otherwise no one
 3696: could ever change the active object. An ANS Forth implementation of this
 3697: model is available at @url{http://www.forth.org/fig/oopf.html}.
 3698: 
 3699: @cindex @file{oof.fs} object model
 3700: The @file{oof.fs} model combines information hiding and overloading
 3701: resolution (by keeping names in various wordlists) with object-oriented
 3702: programming. It sets the active object implicitly on method entry, but
 3703: also allows explicit changing (with @code{>o...o>} or with
 3704: @code{with...endwith}). It uses parsing and state-smart objects and
 3705: classes for resolving overloading and for early binding: the object or
 3706: class parses the selector and determines the method from this. If the
 3707: selector is not parsed by an object or class, it performs a call to the
 3708: selector for the active object (late binding), like Zsoter's model.
 3709: Fields are always accessed through the active object. The big
 3710: disadvantage of this model is the parsing and the state-smartness, which
 3711: reduces extensibility and increases the opportunities for subtle bugs;
 3712: essentially, you are only safe if you never tick or @code{postpone} an
 3713: object or class.
 3714: 
 3715: @node Objects Glossary,  , Comparison with other object models, Objects
 3716: @subsection @file{objects.fs} Glossary
 3717: @cindex @file{objects.fs} Glossary
 3718: 
 3719: doc-bind
 3720: doc-<bind>
 3721: doc-bind'
 3722: doc-[bind]
 3723: doc-class
 3724: doc-class->map
 3725: doc-class-inst-size
 3726: doc-class-override!
 3727: doc-construct
 3728: doc-current'
 3729: doc-[current]
 3730: doc-current-interface
 3731: doc-dict-new
 3732: doc-drop-order
 3733: doc-end-class
 3734: doc-end-class-noname
 3735: doc-end-interface
 3736: doc-end-interface-noname
 3737: doc-exitm
 3738: doc-heap-new
 3739: doc-implementation
 3740: doc-init-object
 3741: doc-inst-value
 3742: doc-inst-var
 3743: doc-interface
 3744: doc-;m
 3745: doc-m:
 3746: doc-method
 3747: doc-object
 3748: doc-overrides
 3749: doc-[parent]
 3750: doc-print
 3751: doc-protected
 3752: doc-public
 3753: doc-push-order
 3754: doc-selector
 3755: doc-this
 3756: doc-<to-inst>
 3757: doc-[to-inst]
 3758: doc-to-this
 3759: doc-xt-new
 3760: 
 3761: @c -------------------------------------------------------------
 3762: @node Object Oriented Forth, Tokens for Words, Objects, Words
 3763: @section Object oriented Forth
 3764: @cindex oof
 3765: @cindex object-oriented programming
 3766: 
 3767: @cindex @file{objects.fs}
 3768: @cindex @file{oof.fs}
 3769: Gforth comes with two packets for object-oriented programming,
 3770: @file{objects.fs} and @file{oof.fs}; none of them is preloaded, so you
 3771: have to @code{include} them before use. This section describes the
 3772: @file{oof.fs} packet. Both packets are written in ANS Forth and can be
 3773: used with any other standard Forth (@pxref{Objects}). This section uses
 3774: the same rationale why using object-oriented programming, and the same
 3775: terminology.
 3776: 
 3777: The packet described in this section is used in bigFORTH since 1991, and
 3778: used for two large applications: a chromatographic system used to
 3779: create new medicaments, and a graphic user interface library (MINOS).
 3780: 
 3781: @menu
 3782: * Properties of the OOF model::
 3783: * Basic OOF Usage::
 3784: * The base class object::
 3785: * Class Declaration::
 3786: * Class Implementation::
 3787: @end menu
 3788: 
 3789: @node Properties of the OOF model, Basic OOF Usage, Object Oriented Forth, Object Oriented Forth
 3790: @subsection Properties of the OOF model
 3791: @cindex @file{oof.fs} properties
 3792: 
 3793: @itemize @bullet
 3794: @item
 3795: This model combines object oriented programming with information
 3796: hiding. It helps you writing large application, where scoping is
 3797: necessary, because it provides class-oriented scoping.
 3798: 
 3799: @item
 3800: Named objects, object pointers, and object arrays can be created,
 3801: selector invocation uses the "object selector" syntax. Selector invocation
 3802: to objects and/or selectors on the stack is a bit less convenient, but
 3803: possible.
 3804: 
 3805: @item
 3806: Selector invocation and instance variable usage of the active object is
 3807: straight forward, since both make use of the active object.
 3808: 
 3809: @item
 3810: Late binding is efficient and easy to use.
 3811: 
 3812: @item
 3813: State-smart objects parse selectors. However, extensibility is provided
 3814: using a (parsing) selector @code{postpone} and a selector @code{'}.
 3815: 
 3816: @item
 3817: An implementation in ANS Forth is available.
 3818: 
 3819: @end itemize
 3820: 
 3821: 
 3822: @node Basic OOF Usage, The base class object, Properties of the OOF model, Object Oriented Forth
 3823: @subsection Basic OOF Usage
 3824: @cindex @file{oof.fs} usage
 3825: 
 3826: Here, I use the same example as for @code{objects} (@pxref{Basic Objects Usage}).
 3827: 
 3828: You can define a class for graphical objects like this:
 3829: 
 3830: @cindex @code{class} usage
 3831: @cindex @code{class;} usage
 3832: @cindex @code{method} usage
 3833: @example
 3834: object class graphical \ "object" is the parent class
 3835:   method draw ( x y graphical -- )
 3836: class;
 3837: @end example
 3838: 
 3839: This code defines a class @code{graphical} with an
 3840: operation @code{draw}.  We can perform the operation
 3841: @code{draw} on any @code{graphical} object, e.g.:
 3842: 
 3843: @example
 3844: 100 100 t-rex draw
 3845: @end example
 3846: 
 3847: where @code{t-rex} is an object or object pointer, created with e.g.
 3848: @code{graphical : trex}.
 3849: 
 3850: @cindex abstract class
 3851: How do we create a graphical object? With the present definitions,
 3852: we cannot create a useful graphical object. The class
 3853: @code{graphical} describes graphical objects in general, but not
 3854: any concrete graphical object type (C++ users would call it an
 3855: @emph{abstract class}); e.g., there is no method for the selector
 3856: @code{draw} in the class @code{graphical}.
 3857: 
 3858: For concrete graphical objects, we define child classes of the
 3859: class @code{graphical}, e.g.:
 3860: 
 3861: @example
 3862: graphical class circle \ "graphical" is the parent class
 3863:   cell var circle-radius
 3864: how:
 3865:   : draw ( x y -- )
 3866:     circle-radius @@ draw-circle ;
 3867: 
 3868:   : init ( n-radius -- (
 3869:     circle-radius ! ;
 3870: class;
 3871: @end example
 3872: 
 3873: Here we define a class @code{circle} as a child of @code{graphical},
 3874: with a field @code{circle-radius}; it defines new methods for the
 3875: selectors @code{draw} and @code{init} (@code{init} is defined in
 3876: @code{object}, the parent class of @code{graphical}).
 3877: 
 3878: Now we can create a circle in the dictionary with
 3879: 
 3880: @example
 3881: 50 circle : my-circle
 3882: @end example
 3883: 
 3884: @code{:} invokes @code{init}, thus initializing the field
 3885: @code{circle-radius} with 50. We can draw this new circle at (100,100)
 3886: with
 3887: 
 3888: @example
 3889: 100 100 my-circle draw
 3890: @end example
 3891: 
 3892: @cindex selector invocation, restrictions
 3893: @cindex class definition, restrictions
 3894: Note: You can invoke a selector only if the receiving object belongs to
 3895: the class where the selector was defined or one of its descendents;
 3896: e.g., you can invoke @code{draw} only for objects belonging to
 3897: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
 3898: mechanism will check if you try to invoke a selector that is not
 3899: defined in this class hierarchy, so you'll get an error at compilation
 3900: time.
 3901: 
 3902: 
 3903: @node The base class object, Class Declaration, Basic OOF Usage, Object Oriented Forth
 3904: @subsection The base class @file{object}
 3905: @cindex @file{oof.fs} base class
 3906: 
 3907: When you define a class, you have to specify a parent class.  So how do
 3908: you start defining classes? There is one class available from the start:
 3909: @code{object}. You have to use it as ancestor for all classes. It is the
 3910: only class that has no parent. Classes are also objects, except that
 3911: they don't have instance variables; class manipulation such as
 3912: inheritance or changing definitions of a class is handled through
 3913: selectors of the class @code{object}.
 3914: 
 3915: @code{object} provides a number of selectors:
 3916: 
 3917: @itemize @bullet
 3918: @item
 3919: @code{class} for subclassing, @code{definitions} to add definitions
 3920: later on, and @code{class?} to get type informations (is the class a
 3921: subclass of the class passed on the stack?).
 3922: doc---object-class
 3923: doc---object-definitions
 3924: doc---object-class?
 3925: 
 3926: @item
 3927: @code{init} and @code{dispose} as constructor and destroctor of the
 3928: object. @code{init} is invocated after the object's memory is allocated,
 3929: while @code{dispose} also handles deallocation. Thus if you redefine
 3930: @code{dispose}, you have to call the parent's dispose with @code{super
 3931: dispose}, too.
 3932: doc---object-init
 3933: doc---object-dispose
 3934: 
 3935: @item
 3936: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
 3937: @code{[]} to create named and unnamed objects and object arrays or
 3938: object pointers.
 3939: doc---object-new
 3940: doc---object-new[]
 3941: doc---object-:
 3942: doc---object-ptr
 3943: doc---object-asptr
 3944: doc---object-[]
 3945: 
 3946: @item
 3947: @code{::} and @code{super} for expicit scoping. You should use expicit
 3948: scoping only for super classes or classes with the same set of instance
 3949: variables. Explicit scoped selectors use early binding.
 3950: doc---object-::
 3951: doc---object-super
 3952: 
 3953: @item
 3954: @code{self} to get the address of the object
 3955: doc---object-self
 3956: 
 3957: @item
 3958: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
 3959: pointers and instance defers.
 3960: doc---object-bind
 3961: doc---object-bound
 3962: doc---object-link
 3963: doc---object-is
 3964: 
 3965: @item
 3966: @code{'} to obtain selector tokens, @code{send} to invocate selectors
 3967: form the stack, and @code{postpone} to generate selector invocation code.
 3968: doc---object-'
 3969: doc---object-postpone
 3970: 
 3971: @item
 3972: @code{with} and @code{endwith} to select the active object from the
 3973: stack, and enabling it's scope. Using @code{with} and @code{endwith}
 3974: also allows to create code using selector @code{postpone} without being
 3975: trapped bye the state-smart objects.
 3976: doc---object-with
 3977: doc---object-endwith
 3978: 
 3979: @end itemize
 3980: 
 3981: @node Class Declaration, Class Implementation, The base class object, Object Oriented Forth
 3982: @subsection Class Declaration
 3983: @cindex class declaration
 3984: 
 3985: @itemize @bullet
 3986: @item
 3987: Instance variables
 3988: doc---oof-var
 3989: 
 3990: @item
 3991: Object pointers
 3992: doc---oof-ptr
 3993: doc---oof-asptr
 3994: 
 3995: @item
 3996: Instance defers
 3997: doc---oof-defer
 3998: 
 3999: @item
 4000: Method selectors
 4001: doc---oof-early
 4002: doc---oof-method
 4003: 
 4004: @item
 4005: Class wide variables
 4006: doc---oof-static
 4007: 
 4008: @item
 4009: End declaration
 4010: doc---oof-how:
 4011: doc---oof-class;
 4012: 
 4013: @end itemize
 4014: 
 4015: @node Class Implementation, , Class Declaration, Object Oriented Forth
 4016: @subsection Class Implementation
 4017: @cindex class implementation
 4018: 
 4019: @c -------------------------------------------------------------
 4020: @node Tokens for Words, Wordlists, Object Oriented Forth, Words
 4021: @section Tokens for Words
 4022: @cindex tokens for words
 4023: 
 4024: This chapter describes the creation and use of tokens that represent
 4025: words on the stack (and in data space).
 4026: 
 4027: Named words have interpretation and compilation semantics. Unnamed words
 4028: just have execution semantics.
 4029: 
 4030: @cindex execution token
 4031: An @dfn{execution token} represents the execution semantics of an
 4032: unnamed word. An execution token occupies one cell. As explained in
 4033: section @ref{Supplying names}, the execution token of the last words
 4034: defined can be produced with
 4035: 
 4036: short-lastxt
 4037: 
 4038: You can perform the semantics represented by an execution token with
 4039: doc-execute
 4040: You can compile the word with
 4041: doc-compile,
 4042: 
 4043: @cindex code field address
 4044: @cindex CFA
 4045: In Gforth, the abstract data type @emph{execution token} is implemented
 4046: as CFA (code field address).
 4047: 
 4048: The interpretation semantics of a named word are also represented by an
 4049: execution token. You can get it with
 4050: 
 4051: doc-[']
 4052: doc-'
 4053: 
 4054: For literals, you use @code{'} in interpreted code and @code{[']} in
 4055: compiled code. Gforth's @code{'} and @code{[']} behave somewhat unusual
 4056: by complaining about compile-only words. To get an execution token for a
 4057: compiling word @var{X}, use @code{COMP' @var{X} drop} or @code{[COMP']
 4058: @var{X} drop}.
 4059: 
 4060: @cindex compilation token
 4061: The compilation semantics are represented by a @dfn{compilation token}
 4062: consisting of two cells: @var{w xt}. The top cell @var{xt} is an
 4063: execution token. The compilation semantics represented by the
 4064: compilation token can be performed with @code{execute}, which consumes
 4065: the whole compilation token, with an additional stack effect determined
 4066: by the represented compilation semantics.
 4067: 
 4068: doc-[comp']
 4069: doc-comp'
 4070: 
 4071: You can compile the compilation semantics with @code{postpone,}. I.e.,
 4072: @code{COMP' @var{word} POSTPONE,} is equivalent to @code{POSTPONE
 4073: @var{word}}.
 4074: 
 4075: doc-postpone,
 4076: 
 4077: At present, the @var{w} part of a compilation token is an execution
 4078: token, and the @var{xt} part represents either @code{execute} or
 4079: @code{compile,}. However, don't rely on that knowledge, unless necessary;
 4080: we may introduce unusual compilation tokens in the future (e.g.,
 4081: compilation tokens representing the compilation semantics of literals).
 4082: 
 4083: @cindex name token
 4084: @cindex name field address
 4085: @cindex NFA
 4086: Named words are also represented by the @dfn{name token}. The abstract
 4087: data type @emph{name token} is implemented as NFA (name field address).
 4088: 
 4089: doc-find-name
 4090: doc-name>int
 4091: doc-name?int
 4092: doc-name>comp
 4093: doc-name>string
 4094: 
 4095: @node Wordlists, Files, Tokens for Words, Words
 4096: @section Wordlists
 4097: 
 4098: @node Files, Blocks, Wordlists, Words
 4099: @section Files
 4100: 
 4101: @node Blocks, Other I/O, Files, Words
 4102: @section Blocks
 4103: 
 4104: @node Other I/O, Programming Tools, Blocks, Words
 4105: @section Other I/O
 4106: 
 4107: @node Programming Tools, Assembler and Code Words, Other I/O, Words
 4108: @section Programming Tools
 4109: @cindex programming tools
 4110: 
 4111: @menu
 4112: * Debugging::                   Simple and quick.
 4113: * Assertions::                  Making your programs self-checking.
 4114: * Singlestep Debugger::		Executing your program word by word.
 4115: @end menu
 4116: 
 4117: @node Debugging, Assertions, Programming Tools, Programming Tools
 4118: @subsection Debugging
 4119: @cindex debugging
 4120: 
 4121: The simple debugging aids provided in @file{debugs.fs}
 4122: are meant to support a different style of debugging than the
 4123: tracing/stepping debuggers used in languages with long turn-around
 4124: times.
 4125: 
 4126: A much better (faster) way in fast-compiling languages is to add
 4127: printing code at well-selected places, let the program run, look at
 4128: the output, see where things went wrong, add more printing code, etc.,
 4129: until the bug is found.
 4130: 
 4131: The word @code{~~} is easy to insert. It just prints debugging
 4132: information (by default the source location and the stack contents). It
 4133: is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
 4134: query-replace them with nothing). The deferred words
 4135: @code{printdebugdata} and @code{printdebugline} control the output of
 4136: @code{~~}. The default source location output format works well with
 4137: Emacs' compilation mode, so you can step through the program at the
 4138: source level using @kbd{C-x `} (the advantage over a stepping debugger
 4139: is that you can step in any direction and you know where the crash has
 4140: happened or where the strange data has occurred).
 4141: 
 4142: Note that the default actions clobber the contents of the pictured
 4143: numeric output string, so you should not use @code{~~}, e.g., between
 4144: @code{<#} and @code{#>}.
 4145: 
 4146: doc-~~
 4147: doc-printdebugdata
 4148: doc-printdebugline
 4149: 
 4150: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
 4151: @subsection Assertions
 4152: @cindex assertions
 4153: 
 4154: It is a good idea to make your programs self-checking, in particular, if
 4155: you use an assumption (e.g., that a certain field of a data structure is
 4156: never zero) that may become wrong during maintenance. Gforth supports
 4157: assertions for this purpose. They are used like this:
 4158: 
 4159: @example
 4160: assert( @var{flag} )
 4161: @end example
 4162: 
 4163: The code between @code{assert(} and @code{)} should compute a flag, that
 4164: should be true if everything is alright and false otherwise. It should
 4165: not change anything else on the stack. The overall stack effect of the
 4166: assertion is @code{( -- )}. E.g.
 4167: 
 4168: @example
 4169: assert( 1 1 + 2 = ) \ what we learn in school
 4170: assert( dup 0<> ) \ assert that the top of stack is not zero
 4171: assert( false ) \ this code should not be reached
 4172: @end example
 4173: 
 4174: The need for assertions is different at different times. During
 4175: debugging, we want more checking, in production we sometimes care more
 4176: for speed. Therefore, assertions can be turned off, i.e., the assertion
 4177: becomes a comment. Depending on the importance of an assertion and the
 4178: time it takes to check it, you may want to turn off some assertions and
 4179: keep others turned on. Gforth provides several levels of assertions for
 4180: this purpose:
 4181: 
 4182: doc-assert0(
 4183: doc-assert1(
 4184: doc-assert2(
 4185: doc-assert3(
 4186: doc-assert(
 4187: doc-)
 4188: 
 4189: @code{Assert(} is the same as @code{assert1(}. The variable
 4190: @code{assert-level} specifies the highest assertions that are turned
 4191: on. I.e., at the default @code{assert-level} of one, @code{assert0(} and
 4192: @code{assert1(} assertions perform checking, while @code{assert2(} and
 4193: @code{assert3(} assertions are treated as comments.
 4194: 
 4195: Note that the @code{assert-level} is evaluated at compile-time, not at
 4196: run-time. I.e., you cannot turn assertions on or off at run-time, you
 4197: have to set the @code{assert-level} appropriately before compiling a
 4198: piece of code. You can compile several pieces of code at several
 4199: @code{assert-level}s (e.g., a trusted library at level 1 and newly
 4200: written code at level 3).
 4201: 
 4202: doc-assert-level
 4203: 
 4204: If an assertion fails, a message compatible with Emacs' compilation mode
 4205: is produced and the execution is aborted (currently with @code{ABORT"}.
 4206: If there is interest, we will introduce a special throw code. But if you
 4207: intend to @code{catch} a specific condition, using @code{throw} is
 4208: probably more appropriate than an assertion).
 4209: 
 4210: @node Singlestep Debugger, , Assertions, Programming Tools
 4211: @subsection Singlestep Debugger
 4212: @cindex singlestep Debugger
 4213: @cindex debugging Singlestep
 4214: @cindex @code{dbg}
 4215: @cindex @code{BREAK:}
 4216: @cindex @code{BREAK"}
 4217: 
 4218: When a new word is created there's often the need to check whether it behaves
 4219: correctly or not. You can do this by typing @code{dbg badword}. This might
 4220: look like:
 4221: @example
 4222: : badword 0 DO i . LOOP ;  ok
 4223: 2 dbg badword 
 4224: : badword  
 4225: Scanning code...
 4226: 
 4227: Nesting debugger ready!
 4228: 
 4229: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
 4230: 400D4740  8049F68 DO             -> [ 0 ] 
 4231: 400D4744  804A0C8 i              -> [ 1 ] 00000 
 4232: 400D4748 400C5E60 .              -> 0 [ 0 ] 
 4233: 400D474C  8049D0C LOOP           -> [ 0 ] 
 4234: 400D4744  804A0C8 i              -> [ 1 ] 00001 
 4235: 400D4748 400C5E60 .              -> 1 [ 0 ] 
 4236: 400D474C  8049D0C LOOP           -> [ 0 ] 
 4237: 400D4758  804B384 ;              ->  ok
 4238: @end example
 4239: 
 4240: Each line displayed is one step. You always have to hit return to
 4241: execute the next word that is displayed. If you don't want to execute
 4242: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
 4243: an overview what keys are available:
 4244: 
 4245: @table @i
 4246: 
 4247: @item <return>
 4248: Next; Execute the next word.
 4249: 
 4250: @item n
 4251: Nest; Single step through next word.
 4252: 
 4253: @item u
 4254: Unnest; Stop debugging and execute rest of word. If we got to this word
 4255: with nest, continue debugging with the calling word.
 4256: 
 4257: @item d
 4258: Done; Stop debugging and execute rest.
 4259: 
 4260: @item s
 4261: Stopp; Abort immediately.
 4262: 
 4263: @end table
 4264: 
 4265: Debugging large application with this mechanism is very difficult, because
 4266: you have to nest very deep into the program before the interesting part
 4267: begins. This takes a lot of time. 
 4268: 
 4269: To do it more directly put a @code{BREAK:} command into your source code.
 4270: When program execution reaches @code{BREAK:} the single step debugger is
 4271: invoked and you have all the features described above.
 4272: 
 4273: If you have more than one part to debug it is useful to know where the
 4274: program has stopped at the moment. You can do this by the 
 4275: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
 4276: string is typed out when the ``breakpoint'' is reached.
 4277: 
 4278: @node Assembler and Code Words, Threading Words, Programming Tools, Words
 4279: @section Assembler and Code Words
 4280: @cindex assembler
 4281: @cindex code words
 4282: 
 4283: Gforth provides some words for defining primitives (words written in
 4284: machine code), and for defining the the machine-code equivalent of
 4285: @code{DOES>}-based defining words. However, the machine-independent
 4286: nature of Gforth poses a few problems: First of all, Gforth runs on
 4287: several architectures, so it can provide no standard assembler. What's
 4288: worse is that the register allocation not only depends on the processor,
 4289: but also on the @code{gcc} version and options used.
 4290: 
 4291: The words that Gforth offers encapsulate some system dependences (e.g., the
 4292: header structure), so a system-independent assembler may be used in
 4293: Gforth. If you do not have an assembler, you can compile machine code
 4294: directly with @code{,} and @code{c,}.
 4295: 
 4296: doc-assembler
 4297: doc-code
 4298: doc-end-code
 4299: doc-;code
 4300: doc-flush-icache
 4301: 
 4302: If @code{flush-icache} does not work correctly, @code{code} words
 4303: etc. will not work (reliably), either.
 4304: 
 4305: These words are rarely used. Therefore they reside in @code{code.fs},
 4306: which is usually not loaded (except @code{flush-icache}, which is always
 4307: present). You can load them with @code{require code.fs}.
 4308: 
 4309: @cindex registers of the inner interpreter
 4310: In the assembly code you will want to refer to the inner interpreter's
 4311: registers (e.g., the data stack pointer) and you may want to use other
 4312: registers for temporary storage. Unfortunately, the register allocation
 4313: is installation-dependent.
 4314: 
 4315: The easiest solution is to use explicit register declarations
 4316: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
 4317: GNU C Manual}) for all of the inner interpreter's registers: You have to
 4318: compile Gforth with @code{-DFORCE_REG} (configure option
 4319: @code{--enable-force-reg}) and the appropriate declarations must be
 4320: present in the @code{machine.h} file (see @code{mips.h} for an example;
 4321: you can find a full list of all declarable register symbols with
 4322: @code{grep register engine.c}). If you give explicit registers to all
 4323: variables that are declared at the beginning of @code{engine()}, you
 4324: should be able to use the other caller-saved registers for temporary
 4325: storage. Alternatively, you can use the @code{gcc} option
 4326: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
 4327: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
 4328: (however, this restriction on register allocation may slow Gforth
 4329: significantly).
 4330: 
 4331: If this solution is not viable (e.g., because @code{gcc} does not allow
 4332: you to explicitly declare all the registers you need), you have to find
 4333: out by looking at the code where the inner interpreter's registers
 4334: reside and which registers can be used for temporary storage. You can
 4335: get an assembly listing of the engine's code with @code{make engine.s}.
 4336: 
 4337: In any case, it is good practice to abstract your assembly code from the
 4338: actual register allocation. E.g., if the data stack pointer resides in
 4339: register @code{$17}, create an alias for this register called @code{sp},
 4340: and use that in your assembly code.
 4341: 
 4342: @cindex code words, portable
 4343: Another option for implementing normal and defining words efficiently
 4344: is: adding the wanted functionality to the source of Gforth. For normal
 4345: words you just have to edit @file{primitives} (@pxref{Automatic
 4346: Generation}), defining words (equivalent to @code{;CODE} words, for fast
 4347: defined words) may require changes in @file{engine.c}, @file{kernal.fs},
 4348: @file{prims2x.fs}, and possibly @file{cross.fs}.
 4349: 
 4350: 
 4351: @node Threading Words, Including Files, Assembler and Code Words, Words
 4352: @section Threading Words
 4353: @cindex threading words
 4354: 
 4355: @cindex code address
 4356: These words provide access to code addresses and other threading stuff
 4357: in Gforth (and, possibly, other interpretive Forths). It more or less
 4358: abstracts away the differences between direct and indirect threading
 4359: (and, for direct threading, the machine dependences). However, at
 4360: present this wordset is still incomplete. It is also pretty low-level;
 4361: some day it will hopefully be made unnecessary by an internals wordset
 4362: that abstracts implementation details away completely.
 4363: 
 4364: doc->code-address
 4365: doc->does-code
 4366: doc-code-address!
 4367: doc-does-code!
 4368: doc-does-handler!
 4369: doc-/does-handler
 4370: 
 4371: The code addresses produced by various defining words are produced by
 4372: the following words:
 4373: 
 4374: doc-docol:
 4375: doc-docon:
 4376: doc-dovar:
 4377: doc-douser:
 4378: doc-dodefer:
 4379: doc-dofield:
 4380: 
 4381: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
 4382: with @code{>DOES-CODE}. If the word was defined in that way, the value
 4383: returned is different from 0 and identifies the @code{DOES>} used by the
 4384: defining word.
 4385: 
 4386: @node Including Files, Include and Require, Threading Words, Words
 4387: @section Including Files
 4388: @cindex including files
 4389: 
 4390: @menu
 4391: * Include and Require::
 4392: * Path Handling::
 4393: @end menu
 4394: 
 4395: @node Include and Require, Path Handling, Including Files, Including Files
 4396: @subsection Include and Requrie
 4397: 
 4398: There a two words to include the source files more intelligently.
 4399: 
 4400: doc-include
 4401: doc-require
 4402: 
 4403: @node Path Handling, , Include and Require, Including Files
 4404: @subsection Path Handling
 4405: @cindex path handling
 4406: 
 4407: In larger program projects it is often neccassary to build up a structured
 4408: directory tree. Standard Forth programs are somewhere more central because
 4409: they must be accessed from some more other programs. To achieve this it is
 4410: possible to manipulate the search path in which Gforth tries to find the
 4411: source file.
 4412: 
 4413: doc-fpath+
 4414: doc-fpath=
 4415: doc-.fpath
 4416: 
 4417: Using fpath and require would look like:
 4418: 
 4419: @example
 4420: 
 4421: fpath= /usr/lib/forth/|./
 4422: 
 4423: require timer.fs
 4424: 
 4425: ...
 4426: 
 4427: @end example
 4428: 
 4429: @cindex ~+
 4430: There is another nice feature which is similar to C's @code{include <...>}
 4431: and @code{include "..."}. For example: You have a program seperated into
 4432: several files in a subdirectory and you want to include some other files
 4433: in this subdirectory from within the program. You have to tell Gforth that
 4434: you are now looking relative to the directory the current file comes from.
 4435: You can tell this Gforth by using the prefix @code{~+/} in front of the
 4436: filename. It is also possible to add it to the search path.
 4437: 
 4438: If you have the need to look for a file in the Forth search path, you could
 4439: use this Gforth feature in your application.
 4440: 
 4441: doc-open-fpath-file
 4442: 
 4443: It is even possible to use your own search paths. Create a search path like
 4444: this:
 4445: 
 4446: @example
 4447: 
 4448: Make a buffer for the path:
 4449: create mypath   100 chars ,     \ maximum length (is checked)
 4450:                 0 ,             \ real len
 4451:                 100 chars allot \ space for path
 4452: 
 4453: @end example
 4454: 
 4455: You have the same functions for the forth search path in an generic version
 4456: for different pathes.
 4457: 
 4458: doc-path+
 4459: doc-path=
 4460: doc-.path
 4461: doc-open-path-file
 4462: 
 4463: @c ******************************************************************
 4464: @node Tools, ANS conformance, Words, Top
 4465: @chapter Tools
 4466: 
 4467: @menu
 4468: * ANS Report::                  Report the words used, sorted by wordset.
 4469: @end menu
 4470: 
 4471: See also @ref{Emacs and Gforth}.
 4472: 
 4473: @node ANS Report,  , Tools, Tools
 4474: @section @file{ans-report.fs}: Report the words used, sorted by wordset
 4475: @cindex @file{ans-report.fs}
 4476: @cindex report the words used in your program
 4477: @cindex words used in your program
 4478: 
 4479: If you want to label a Forth program as ANS Forth Program, you must
 4480: document which wordsets the program uses; for extension wordsets, it is
 4481: helpful to list the words the program requires from these wordsets
 4482: (because Forth systems are allowed to provide only some words of them).
 4483: 
 4484: The @file{ans-report.fs} tool makes it easy for you to determine which
 4485: words from which wordset and which non-ANS words your application
 4486: uses. You simply have to include @file{ans-report.fs} before loading the
 4487: program you want to check. After loading your program, you can get the
 4488: report with @code{print-ans-report}. A typical use is to run this as
 4489: batch job like this:
 4490: @example
 4491: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
 4492: @end example
 4493: 
 4494: The output looks like this (for @file{compat/control.fs}):
 4495: @example
 4496: The program uses the following words
 4497: from CORE :
 4498: : POSTPONE THEN ; immediate ?dup IF 0= 
 4499: from BLOCK-EXT :
 4500: \ 
 4501: from FILE :
 4502: ( 
 4503: @end example
 4504: 
 4505: @subsection Caveats
 4506: 
 4507: Note that @file{ans-report.fs} just checks which words are used, not whether
 4508: they are used in an ANS Forth conforming way!
 4509: 
 4510: Some words are defined in several wordsets in the
 4511: standard. @file{ans-report.fs} reports them for only one of the
 4512: wordsets, and not necessarily the one you expect. It depends on usage
 4513: which wordset is the right one to specify. E.g., if you only use the
 4514: compilation semantics of @code{S"}, it is a Core word; if you also use
 4515: its interpretation semantics, it is a File word.
 4516: 
 4517: @c ******************************************************************
 4518: @node ANS conformance, Model, Tools, Top
 4519: @chapter ANS conformance
 4520: @cindex ANS conformance of Gforth
 4521: 
 4522: To the best of our knowledge, Gforth is an
 4523: 
 4524: ANS Forth System
 4525: @itemize @bullet
 4526: @item providing the Core Extensions word set
 4527: @item providing the Block word set
 4528: @item providing the Block Extensions word set
 4529: @item providing the Double-Number word set
 4530: @item providing the Double-Number Extensions word set
 4531: @item providing the Exception word set
 4532: @item providing the Exception Extensions word set
 4533: @item providing the Facility word set
 4534: @item providing @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
 4535: @item providing the File Access word set
 4536: @item providing the File Access Extensions word set
 4537: @item providing the Floating-Point word set
 4538: @item providing the Floating-Point Extensions word set
 4539: @item providing the Locals word set
 4540: @item providing the Locals Extensions word set
 4541: @item providing the Memory-Allocation word set
 4542: @item providing the Memory-Allocation Extensions word set (that one's easy)
 4543: @item providing the Programming-Tools word set
 4544: @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
 4545: @item providing the Search-Order word set
 4546: @item providing the Search-Order Extensions word set
 4547: @item providing the String word set
 4548: @item providing the String Extensions word set (another easy one)
 4549: @end itemize
 4550: 
 4551: @cindex system documentation
 4552: In addition, ANS Forth systems are required to document certain
 4553: implementation choices. This chapter tries to meet these
 4554: requirements. In many cases it gives a way to ask the system for the
 4555: information instead of providing the information directly, in
 4556: particular, if the information depends on the processor, the operating
 4557: system or the installation options chosen, or if they are likely to
 4558: change during the maintenance of Gforth.
 4559: 
 4560: @comment The framework for the rest has been taken from pfe.
 4561: 
 4562: @menu
 4563: * The Core Words::              
 4564: * The optional Block word set::  
 4565: * The optional Double Number word set::  
 4566: * The optional Exception word set::  
 4567: * The optional Facility word set::  
 4568: * The optional File-Access word set::  
 4569: * The optional Floating-Point word set::  
 4570: * The optional Locals word set::  
 4571: * The optional Memory-Allocation word set::  
 4572: * The optional Programming-Tools word set::  
 4573: * The optional Search-Order word set::  
 4574: @end menu
 4575: 
 4576: 
 4577: @c =====================================================================
 4578: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
 4579: @comment  node-name,  next,  previous,  up
 4580: @section The Core Words
 4581: @c =====================================================================
 4582: @cindex core words, system documentation
 4583: @cindex system documentation, core words
 4584: 
 4585: @menu
 4586: * core-idef::                   Implementation Defined Options                   
 4587: * core-ambcond::                Ambiguous Conditions                
 4588: * core-other::                  Other System Documentation                  
 4589: @end menu
 4590: 
 4591: @c ---------------------------------------------------------------------
 4592: @node core-idef, core-ambcond, The Core Words, The Core Words
 4593: @subsection Implementation Defined Options
 4594: @c ---------------------------------------------------------------------
 4595: @cindex core words, implementation-defined options
 4596: @cindex implementation-defined options, core words
 4597: 
 4598: 
 4599: @table @i
 4600: @item (Cell) aligned addresses:
 4601: @cindex cell-aligned addresses
 4602: @cindex aligned addresses
 4603: processor-dependent. Gforth's alignment words perform natural alignment
 4604: (e.g., an address aligned for a datum of size 8 is divisible by
 4605: 8). Unaligned accesses usually result in a @code{-23 THROW}.
 4606: 
 4607: @item @code{EMIT} and non-graphic characters:
 4608: @cindex @code{EMIT} and non-graphic characters
 4609: @cindex non-graphic characters and @code{EMIT}
 4610: The character is output using the C library function (actually, macro)
 4611: @code{putc}.
 4612: 
 4613: @item character editing of @code{ACCEPT} and @code{EXPECT}:
 4614: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
 4615: @cindex editing in @code{ACCEPT} and @code{EXPECT}
 4616: @cindex @code{ACCEPT}, editing
 4617: @cindex @code{EXPECT}, editing
 4618: This is modeled on the GNU readline library (@pxref{Readline
 4619: Interaction, , Command Line Editing, readline, The GNU Readline
 4620: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
 4621: producing a full word completion every time you type it (instead of
 4622: producing the common prefix of all completions).
 4623: 
 4624: @item character set:
 4625: @cindex character set
 4626: The character set of your computer and display device. Gforth is
 4627: 8-bit-clean (but some other component in your system may make trouble).
 4628: 
 4629: @item Character-aligned address requirements:
 4630: @cindex character-aligned address requirements
 4631: installation-dependent. Currently a character is represented by a C
 4632: @code{unsigned char}; in the future we might switch to @code{wchar_t}
 4633: (Comments on that requested).
 4634: 
 4635: @item character-set extensions and matching of names:
 4636: @cindex character-set extensions and matching of names
 4637: @cindex case sensitivity for name lookup
 4638: @cindex name lookup, case sensitivity
 4639: @cindex locale and case sensitivity
 4640: Any character except the ASCII NUL charcter can be used in a
 4641: name. Matching is case-insensitive (except in @code{TABLE}s). The
 4642: matching is performed using the C function @code{strncasecmp}, whose
 4643: function is probably influenced by the locale. E.g., the @code{C} locale
 4644: does not know about accents and umlauts, so they are matched
 4645: case-sensitively in that locale. For portability reasons it is best to
 4646: write programs such that they work in the @code{C} locale. Then one can
 4647: use libraries written by a Polish programmer (who might use words
 4648: containing ISO Latin-2 encoded characters) and by a French programmer
 4649: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
 4650: funny results for some of the words (which ones, depends on the font you
 4651: are using)). Also, the locale you prefer may not be available in other
 4652: operating systems. Hopefully, Unicode will solve these problems one day.
 4653: 
 4654: @item conditions under which control characters match a space delimiter:
 4655: @cindex space delimiters
 4656: @cindex control characters as delimiters
 4657: If @code{WORD} is called with the space character as a delimiter, all
 4658: white-space characters (as identified by the C macro @code{isspace()})
 4659: are delimiters. @code{PARSE}, on the other hand, treats space like other
 4660: delimiters. @code{PARSE-WORD} treats space like @code{WORD}, but behaves
 4661: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
 4662: interpreter (aka text interpreter) by default, treats all white-space
 4663: characters as delimiters.
 4664: 
 4665: @item format of the control flow stack:
 4666: @cindex control flow stack, format
 4667: The data stack is used as control flow stack. The size of a control flow
 4668: stack item in cells is given by the constant @code{cs-item-size}. At the
 4669: time of this writing, an item consists of a (pointer to a) locals list
 4670: (third), an address in the code (second), and a tag for identifying the
 4671: item (TOS). The following tags are used: @code{defstart},
 4672: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
 4673: @code{scopestart}.
 4674: 
 4675: @item conversion of digits > 35
 4676: @cindex digits > 35
 4677: The characters @code{[\]^_'} are the digits with the decimal value
 4678: 36@minus{}41. There is no way to input many of the larger digits.
 4679: 
 4680: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
 4681: @cindex @code{EXPECT}, display after end of input
 4682: @cindex @code{ACCEPT}, display after end of input
 4683: The cursor is moved to the end of the entered string. If the input is
 4684: terminated using the @kbd{Return} key, a space is typed.
 4685: 
 4686: @item exception abort sequence of @code{ABORT"}:
 4687: @cindex exception abort sequence of @code{ABORT"}
 4688: @cindex @code{ABORT"}, exception abort sequence
 4689: The error string is stored into the variable @code{"error} and a
 4690: @code{-2 throw} is performed.
 4691: 
 4692: @item input line terminator:
 4693: @cindex input line terminator
 4694: @cindex line terminator on input
 4695: @cindex newline charcter on input
 4696: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
 4697: lines. One of these characters is typically produced when you type the
 4698: @kbd{Enter} or @kbd{Return} key.
 4699: 
 4700: @item maximum size of a counted string:
 4701: @cindex maximum size of a counted string
 4702: @cindex counted string, maximum size
 4703: @code{s" /counted-string" environment? drop .}. Currently 255 characters
 4704: on all ports, but this may change.
 4705: 
 4706: @item maximum size of a parsed string:
 4707: @cindex maximum size of a parsed string
 4708: @cindex parsed string, maximum size
 4709: Given by the constant @code{/line}. Currently 255 characters.
 4710: 
 4711: @item maximum size of a definition name, in characters:
 4712: @cindex maximum size of a definition name, in characters
 4713: @cindex name, maximum length
 4714: 31
 4715: 
 4716: @item maximum string length for @code{ENVIRONMENT?}, in characters:
 4717: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
 4718: @cindex @code{ENVIRONMENT?} string length, maximum
 4719: 31
 4720: 
 4721: @item method of selecting the user input device:
 4722: @cindex user input device, method of selecting
 4723: The user input device is the standard input. There is currently no way to
 4724: change it from within Gforth. However, the input can typically be
 4725: redirected in the command line that starts Gforth.
 4726: 
 4727: @item method of selecting the user output device:
 4728: @cindex user output device, method of selecting
 4729: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
 4730: @code{outfile-id} (@code{stdout} by default). Gforth uses buffered
 4731: output, so output on a terminal does not become visible before the next
 4732: newline or buffer overflow. Output on non-terminals is invisible until
 4733: the buffer overflows.
 4734: 
 4735: @item methods of dictionary compilation:
 4736: What are we expected to document here?
 4737: 
 4738: @item number of bits in one address unit:
 4739: @cindex number of bits in one address unit
 4740: @cindex address unit, size in bits
 4741: @code{s" address-units-bits" environment? drop .}. 8 in all current
 4742: ports.
 4743: 
 4744: @item number representation and arithmetic:
 4745: @cindex number representation and arithmetic
 4746: Processor-dependent. Binary two's complement on all current ports.
 4747: 
 4748: @item ranges for integer types:
 4749: @cindex ranges for integer types
 4750: @cindex integer types, ranges
 4751: Installation-dependent. Make environmental queries for @code{MAX-N},
 4752: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
 4753: unsigned (and positive) types is 0. The lower bound for signed types on
 4754: two's complement and one's complement machines machines can be computed
 4755: by adding 1 to the upper bound.
 4756: 
 4757: @item read-only data space regions:
 4758: @cindex read-only data space regions
 4759: @cindex data-space, read-only regions
 4760: The whole Forth data space is writable.
 4761: 
 4762: @item size of buffer at @code{WORD}:
 4763: @cindex size of buffer at @code{WORD}
 4764: @cindex @code{WORD} buffer size
 4765: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
 4766: shared with the pictured numeric output string. If overwriting
 4767: @code{PAD} is acceptable, it is as large as the remaining dictionary
 4768: space, although only as much can be sensibly used as fits in a counted
 4769: string.
 4770: 
 4771: @item size of one cell in address units:
 4772: @cindex cell size
 4773: @code{1 cells .}.
 4774: 
 4775: @item size of one character in address units:
 4776: @cindex char size
 4777: @code{1 chars .}. 1 on all current ports.
 4778: 
 4779: @item size of the keyboard terminal buffer:
 4780: @cindex size of the keyboard terminal buffer
 4781: @cindex terminal buffer, size
 4782: Varies. You can determine the size at a specific time using @code{lp@@
 4783: tib - .}. It is shared with the locals stack and TIBs of files that
 4784: include the current file. You can change the amount of space for TIBs
 4785: and locals stack at Gforth startup with the command line option
 4786: @code{-l}.
 4787: 
 4788: @item size of the pictured numeric output buffer:
 4789: @cindex size of the pictured numeric output buffer
 4790: @cindex pictured numeric output buffer, size
 4791: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
 4792: shared with @code{WORD}.
 4793: 
 4794: @item size of the scratch area returned by @code{PAD}:
 4795: @cindex size of the scratch area returned by @code{PAD}
 4796: @cindex @code{PAD} size
 4797: The remainder of dictionary space. @code{unused pad here - - .}.
 4798: 
 4799: @item system case-sensitivity characteristics:
 4800: @cindex case-sensitivity characteristics
 4801: Dictionary searches are case insensitive (except in
 4802: @code{TABLE}s). However, as explained above under @i{character-set
 4803: extensions}, the matching for non-ASCII characters is determined by the
 4804: locale you are using. In the default @code{C} locale all non-ASCII
 4805: characters are matched case-sensitively.
 4806: 
 4807: @item system prompt:
 4808: @cindex system prompt
 4809: @cindex prompt
 4810: @code{ ok} in interpret state, @code{ compiled} in compile state.
 4811: 
 4812: @item division rounding:
 4813: @cindex division rounding
 4814: installation dependent. @code{s" floored" environment? drop .}. We leave
 4815: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
 4816: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
 4817: 
 4818: @item values of @code{STATE} when true:
 4819: @cindex @code{STATE} values
 4820: -1.
 4821: 
 4822: @item values returned after arithmetic overflow:
 4823: On two's complement machines, arithmetic is performed modulo
 4824: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
 4825: arithmetic (with appropriate mapping for signed types). Division by zero
 4826: typically results in a @code{-55 throw} (Floating-point unidentified
 4827: fault), although a @code{-10 throw} (divide by zero) would be more
 4828: appropriate.
 4829: 
 4830: @item whether the current definition can be found after @t{DOES>}:
 4831: @cindex @t{DOES>}, visibility of current definition
 4832: No.
 4833: 
 4834: @end table
 4835: 
 4836: @c ---------------------------------------------------------------------
 4837: @node core-ambcond, core-other, core-idef, The Core Words
 4838: @subsection Ambiguous conditions
 4839: @c ---------------------------------------------------------------------
 4840: @cindex core words, ambiguous conditions
 4841: @cindex ambiguous conditions, core words
 4842: 
 4843: @table @i
 4844: 
 4845: @item a name is neither a word nor a number:
 4846: @cindex name not found
 4847: @cindex Undefined word
 4848: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
 4849: preserves the data and FP stack, so you don't lose more work than
 4850: necessary.
 4851: 
 4852: @item a definition name exceeds the maximum length allowed:
 4853: @cindex Word name too long
 4854: @code{-19 throw} (Word name too long)
 4855: 
 4856: @item addressing a region not inside the various data spaces of the forth system:
 4857: @cindex Invalid memory address
 4858: The stacks, code space and name space are accessible. Machine code space is
 4859: typically readable. Accessing other addresses gives results dependent on
 4860: the operating system. On decent systems: @code{-9 throw} (Invalid memory
 4861: address).
 4862: 
 4863: @item argument type incompatible with parameter:
 4864: @cindex Argument type mismatch
 4865: This is usually not caught. Some words perform checks, e.g., the control
 4866: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
 4867: mismatch).
 4868: 
 4869: @item attempting to obtain the execution token of a word with undefined execution semantics:
 4870: @cindex Interpreting a compile-only word, for @code{'} etc.
 4871: @cindex execution token of words with undefined execution semantics
 4872: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
 4873: get an execution token for @code{compile-only-error} (which performs a
 4874: @code{-14 throw} when executed).
 4875: 
 4876: @item dividing by zero:
 4877: @cindex dividing by zero
 4878: @cindex floating point unidentified fault, integer division
 4879: @cindex divide by zero
 4880: typically results in a @code{-55 throw} (floating point unidentified
 4881: fault), although a @code{-10 throw} (divide by zero) would be more
 4882: appropriate.
 4883: 
 4884: @item insufficient data stack or return stack space:
 4885: @cindex insufficient data stack or return stack space
 4886: @cindex stack overflow
 4887: @cindex Address alignment exception, stack overflow
 4888: @cindex Invalid memory address, stack overflow
 4889: Depending on the operating system, the installation, and the invocation
 4890: of Gforth, this is either checked by the memory management hardware, or
 4891: it is not checked. If it is checked, you typically get a @code{-9 throw}
 4892: (Invalid memory address) as soon as the overflow happens. If it is not
 4893: check, overflows typically result in mysterious illegal memory accesses,
 4894: producing @code{-9 throw} (Invalid memory address) or @code{-23 throw}
 4895: (Address alignment exception); they might also destroy the internal data
 4896: structure of @code{ALLOCATE} and friends, resulting in various errors in
 4897: these words.
 4898: 
 4899: @item insufficient space for loop control parameters:
 4900: @cindex insufficient space for loop control parameters
 4901: like other return stack overflows.
 4902: 
 4903: @item insufficient space in the dictionary:
 4904: @cindex insufficient space in the dictionary
 4905: @cindex dictionary overflow
 4906: Depending on the operating system, the installation, and the invocation
 4907: of Gforth, this is either checked by the memory management hardware, or
 4908: it is not checked. Similar results as stack overflows. However,
 4909: typically the error appears at a different place when one inserts or
 4910: removes code. Also, the @code{THROW} does not relieve the situation (it
 4911: does for stack overflows).
 4912: 
 4913: @item interpreting a word with undefined interpretation semantics:
 4914: @cindex interpreting a word with undefined interpretation semantics
 4915: @cindex Interpreting a compile-only word
 4916: For some words, we have defined interpretation semantics. For the
 4917: others: @code{-14 throw} (Interpreting a compile-only word).
 4918: 
 4919: @item modifying the contents of the input buffer or a string literal:
 4920: @cindex modifying the contents of the input buffer or a string literal
 4921: These are located in writable memory and can be modified.
 4922: 
 4923: @item overflow of the pictured numeric output string:
 4924: @cindex overflow of the pictured numeric output string
 4925: @cindex pictured numeric output string, overflow
 4926: Not checked. Runs into the dictionary and destroys it (at least,
 4927: partially).
 4928: 
 4929: @item parsed string overflow:
 4930: @cindex parsed string overflow
 4931: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
 4932: 
 4933: @item producing a result out of range:
 4934: @cindex result out of range
 4935: On two's complement machines, arithmetic is performed modulo
 4936: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
 4937: arithmetic (with appropriate mapping for signed types). Division by zero
 4938: typically results in a @code{-55 throw} (floatingpoint unidentified
 4939: fault), although a @code{-10 throw} (divide by zero) would be more
 4940: appropriate. @code{convert} and @code{>number} currently overflow
 4941: silently.
 4942: 
 4943: @item reading from an empty data or return stack:
 4944: @cindex stack empty
 4945: @cindex stack underflow
 4946: The data stack is checked by the outer (aka text) interpreter after
 4947: every word executed. If it has underflowed, a @code{-4 throw} (Stack
 4948: underflow) is performed. Apart from that, stacks may be checked or not,
 4949: depending on operating system, installation, and invocation. The
 4950: consequences of stack underflows are similar to the consequences of
 4951: stack overflows. Note that even if the system uses checking (through the
 4952: MMU), your program may have to underflow by a significant number of
 4953: stack items to trigger the reaction (the reason for this is that the
 4954: MMU, and therefore the checking, works with a page-size granularity).
 4955: 
 4956: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
 4957: @cindex unexpected end of the input buffer
 4958: @cindex zero-length string as a name
 4959: @cindex Attempt to use zero-length string as a name
 4960: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
 4961: use zero-length string as a name). Words like @code{'} probably will not
 4962: find what they search. Note that it is possible to create zero-length
 4963: names with @code{nextname} (should it not?).
 4964: 
 4965: @item @code{>IN} greater than input buffer:
 4966: @cindex @code{>IN} greater than input buffer
 4967: The next invocation of a parsing word returns a string with length 0.
 4968: 
 4969: @item @code{RECURSE} appears after @code{DOES>}:
 4970: @cindex @code{RECURSE} appears after @code{DOES>}
 4971: Compiles a recursive call to the defining word, not to the defined word.
 4972: 
 4973: @item argument input source different than current input source for @code{RESTORE-INPUT}:
 4974: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
 4975: @cindex Argument type mismatch, @code{RESTORE-INPUT}
 4976: @cindex @code{RESTORE-INPUT}, Argument type mismatch
 4977: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
 4978: the end of the file was reached), its source-id may be
 4979: reused. Therefore, restoring an input source specification referencing a
 4980: closed file may lead to unpredictable results instead of a @code{-12
 4981: THROW}.
 4982: 
 4983: In the future, Gforth may be able to restore input source specifications
 4984: from other than the current input source.
 4985: 
 4986: @item data space containing definitions gets de-allocated:
 4987: @cindex data space containing definitions gets de-allocated
 4988: Deallocation with @code{allot} is not checked. This typically results in
 4989: memory access faults or execution of illegal instructions.
 4990: 
 4991: @item data space read/write with incorrect alignment:
 4992: @cindex data space read/write with incorrect alignment
 4993: @cindex alignment faults
 4994: @cindex Address alignment exception
 4995: Processor-dependent. Typically results in a @code{-23 throw} (Address
 4996: alignment exception). Under Linux on a 486 or later processor with
 4997: alignment turned on, incorrect alignment results in a @code{-9 throw}
 4998: (Invalid memory address). There are reportedly some processors with
 4999: alignment restrictions that do not report them.
 5000: 
 5001: @item data space pointer not properly aligned, @code{,}, @code{C,}:
 5002: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
 5003: Like other alignment errors.
 5004: 
 5005: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
 5006: Like other stack underflows.
 5007: 
 5008: @item loop control parameters not available:
 5009: @cindex loop control parameters not available
 5010: Not checked. The counted loop words simply assume that the top of return
 5011: stack items are loop control parameters and behave accordingly.
 5012: 
 5013: @item most recent definition does not have a name (@code{IMMEDIATE}):
 5014: @cindex most recent definition does not have a name (@code{IMMEDIATE})
 5015: @cindex last word was headerless
 5016: @code{abort" last word was headerless"}.
 5017: 
 5018: @item name not defined by @code{VALUE} used by @code{TO}:
 5019: @cindex name not defined by @code{VALUE} used by @code{TO}
 5020: @cindex @code{TO} on non-@code{VALUE}s
 5021: @cindex Invalid name argument, @code{TO}
 5022: @code{-32 throw} (Invalid name argument) (unless name is a local or was
 5023: defined by @code{CONSTANT}; in the latter case it just changes the constant).
 5024: 
 5025: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
 5026: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
 5027: @cindex Undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
 5028: @code{-13 throw} (Undefined word)
 5029: 
 5030: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
 5031: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
 5032: Gforth behaves as if they were of the same type. I.e., you can predict
 5033: the behaviour by interpreting all parameters as, e.g., signed.
 5034: 
 5035: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
 5036: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
 5037: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
 5038: compilation semantics of @code{TO}.
 5039: 
 5040: @item String longer than a counted string returned by @code{WORD}:
 5041: @cindex String longer than a counted string returned by @code{WORD}
 5042: @cindex @code{WORD}, string overflow
 5043: Not checked. The string will be ok, but the count will, of course,
 5044: contain only the least significant bits of the length.
 5045: 
 5046: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
 5047: @cindex @code{LSHIFT}, large shift counts
 5048: @cindex @code{RSHIFT}, large shift counts
 5049: Processor-dependent. Typical behaviours are returning 0 and using only
 5050: the low bits of the shift count.
 5051: 
 5052: @item word not defined via @code{CREATE}:
 5053: @cindex @code{>BODY} of non-@code{CREATE}d words
 5054: @code{>BODY} produces the PFA of the word no matter how it was defined.
 5055: 
 5056: @cindex @code{DOES>} of non-@code{CREATE}d words
 5057: @code{DOES>} changes the execution semantics of the last defined word no
 5058: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
 5059: @code{CREATE , DOES>}.
 5060: 
 5061: @item words improperly used outside @code{<#} and @code{#>}:
 5062: Not checked. As usual, you can expect memory faults.
 5063: 
 5064: @end table
 5065: 
 5066: 
 5067: @c ---------------------------------------------------------------------
 5068: @node core-other,  , core-ambcond, The Core Words
 5069: @subsection Other system documentation
 5070: @c ---------------------------------------------------------------------
 5071: @cindex other system documentation, core words
 5072: @cindex core words, other system documentation
 5073: 
 5074: @table @i
 5075: @item nonstandard words using @code{PAD}:
 5076: @cindex @code{PAD} use by nonstandard words
 5077: None.
 5078: 
 5079: @item operator's terminal facilities available:
 5080: @cindex operator's terminal facilities available
 5081: After processing the command line, Gforth goes into interactive mode,
 5082: and you can give commands to Gforth interactively. The actual facilities
 5083: available depend on how you invoke Gforth.
 5084: 
 5085: @item program data space available:
 5086: @cindex program data space available
 5087: @cindex data space available
 5088: @code{UNUSED .} gives the remaining dictionary space. The total
 5089: dictionary space can be specified with the @code{-m} switch
 5090: (@pxref{Invoking Gforth}) when Gforth starts up.
 5091: 
 5092: @item return stack space available:
 5093: @cindex return stack space available
 5094: You can compute the total return stack space in cells with
 5095: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
 5096: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
 5097: 
 5098: @item stack space available:
 5099: @cindex stack space available
 5100: You can compute the total data stack space in cells with
 5101: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
 5102: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
 5103: 
 5104: @item system dictionary space required, in address units:
 5105: @cindex system dictionary space required, in address units
 5106: Type @code{here forthstart - .} after startup. At the time of this
 5107: writing, this gives 80080 (bytes) on a 32-bit system.
 5108: @end table
 5109: 
 5110: 
 5111: @c =====================================================================
 5112: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
 5113: @section The optional Block word set
 5114: @c =====================================================================
 5115: @cindex system documentation, block words
 5116: @cindex block words, system documentation
 5117: 
 5118: @menu
 5119: * block-idef::                  Implementation Defined Options
 5120: * block-ambcond::               Ambiguous Conditions               
 5121: * block-other::                 Other System Documentation                 
 5122: @end menu
 5123: 
 5124: 
 5125: @c ---------------------------------------------------------------------
 5126: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
 5127: @subsection Implementation Defined Options
 5128: @c ---------------------------------------------------------------------
 5129: @cindex implementation-defined options, block words
 5130: @cindex block words, implementation-defined options
 5131: 
 5132: @table @i
 5133: @item the format for display by @code{LIST}:
 5134: @cindex @code{LIST} display format
 5135: First the screen number is displayed, then 16 lines of 64 characters,
 5136: each line preceded by the line number.
 5137: 
 5138: @item the length of a line affected by @code{\}:
 5139: @cindex length of a line affected by @code{\}
 5140: @cindex @code{\}, line length in blocks
 5141: 64 characters.
 5142: @end table
 5143: 
 5144: 
 5145: @c ---------------------------------------------------------------------
 5146: @node block-ambcond, block-other, block-idef, The optional Block word set
 5147: @subsection Ambiguous conditions
 5148: @c ---------------------------------------------------------------------
 5149: @cindex block words, ambiguous conditions
 5150: @cindex ambiguous conditions, block words
 5151: 
 5152: @table @i
 5153: @item correct block read was not possible:
 5154: @cindex block read not possible
 5155: Typically results in a @code{throw} of some OS-derived value (between
 5156: -512 and -2048). If the blocks file was just not long enough, blanks are
 5157: supplied for the missing portion.
 5158: 
 5159: @item I/O exception in block transfer:
 5160: @cindex I/O exception in block transfer
 5161: @cindex block transfer, I/O exception
 5162: Typically results in a @code{throw} of some OS-derived value (between
 5163: -512 and -2048).
 5164: 
 5165: @item invalid block number:
 5166: @cindex invalid block number
 5167: @cindex block number invalid
 5168: @code{-35 throw} (Invalid block number)
 5169: 
 5170: @item a program directly alters the contents of @code{BLK}:
 5171: @cindex @code{BLK}, altering @code{BLK}
 5172: The input stream is switched to that other block, at the same
 5173: position. If the storing to @code{BLK} happens when interpreting
 5174: non-block input, the system will get quite confused when the block ends.
 5175: 
 5176: @item no current block buffer for @code{UPDATE}:
 5177: @cindex @code{UPDATE}, no current block buffer
 5178: @code{UPDATE} has no effect.
 5179: 
 5180: @end table
 5181: 
 5182: @c ---------------------------------------------------------------------
 5183: @node block-other,  , block-ambcond, The optional Block word set
 5184: @subsection Other system documentation
 5185: @c ---------------------------------------------------------------------
 5186: @cindex other system documentation, block words
 5187: @cindex block words, other system documentation
 5188: 
 5189: @table @i
 5190: @item any restrictions a multiprogramming system places on the use of buffer addresses:
 5191: No restrictions (yet).
 5192: 
 5193: @item the number of blocks available for source and data:
 5194: depends on your disk space.
 5195: 
 5196: @end table
 5197: 
 5198: 
 5199: @c =====================================================================
 5200: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
 5201: @section The optional Double Number word set
 5202: @c =====================================================================
 5203: @cindex system documentation, double words
 5204: @cindex double words, system documentation
 5205: 
 5206: @menu
 5207: * double-ambcond::              Ambiguous Conditions              
 5208: @end menu
 5209: 
 5210: 
 5211: @c ---------------------------------------------------------------------
 5212: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
 5213: @subsection Ambiguous conditions
 5214: @c ---------------------------------------------------------------------
 5215: @cindex double words, ambiguous conditions
 5216: @cindex ambiguous conditions, double words
 5217: 
 5218: @table @i
 5219: @item @var{d} outside of range of @var{n} in @code{D>S}:
 5220: @cindex @code{D>S}, @var{d} out of range of @var{n} 
 5221: The least significant cell of @var{d} is produced.
 5222: 
 5223: @end table
 5224: 
 5225: 
 5226: @c =====================================================================
 5227: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
 5228: @section The optional Exception word set
 5229: @c =====================================================================
 5230: @cindex system documentation, exception words
 5231: @cindex exception words, system documentation
 5232: 
 5233: @menu
 5234: * exception-idef::              Implementation Defined Options              
 5235: @end menu
 5236: 
 5237: 
 5238: @c ---------------------------------------------------------------------
 5239: @node exception-idef,  , The optional Exception word set, The optional Exception word set
 5240: @subsection Implementation Defined Options
 5241: @c ---------------------------------------------------------------------
 5242: @cindex implementation-defined options, exception words
 5243: @cindex exception words, implementation-defined options
 5244: 
 5245: @table @i
 5246: @item @code{THROW}-codes used in the system:
 5247: @cindex @code{THROW}-codes used in the system
 5248: The codes -256@minus{}-511 are used for reporting signals. The mapping
 5249: from OS signal numbers to throw codes is -256@minus{}@var{signal}. The
 5250: codes -512@minus{}-2047 are used for OS errors (for file and memory
 5251: allocation operations). The mapping from OS error numbers to throw codes
 5252: is -512@minus{}@code{errno}. One side effect of this mapping is that
 5253: undefined OS errors produce a message with a strange number; e.g.,
 5254: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
 5255: @end table
 5256: 
 5257: @c =====================================================================
 5258: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
 5259: @section The optional Facility word set
 5260: @c =====================================================================
 5261: @cindex system documentation, facility words
 5262: @cindex facility words, system documentation
 5263: 
 5264: @menu
 5265: * facility-idef::               Implementation Defined Options               
 5266: * facility-ambcond::            Ambiguous Conditions            
 5267: @end menu
 5268: 
 5269: 
 5270: @c ---------------------------------------------------------------------
 5271: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
 5272: @subsection Implementation Defined Options
 5273: @c ---------------------------------------------------------------------
 5274: @cindex implementation-defined options, facility words
 5275: @cindex facility words, implementation-defined options
 5276: 
 5277: @table @i
 5278: @item encoding of keyboard events (@code{EKEY}):
 5279: @cindex keyboard events, encoding in @code{EKEY}
 5280: @cindex @code{EKEY}, encoding of keyboard events
 5281: Not yet implemented.
 5282: 
 5283: @item duration of a system clock tick:
 5284: @cindex duration of a system clock tick
 5285: @cindex clock tick duration
 5286: System dependent. With respect to @code{MS}, the time is specified in
 5287: microseconds. How well the OS and the hardware implement this, is
 5288: another question.
 5289: 
 5290: @item repeatability to be expected from the execution of @code{MS}:
 5291: @cindex repeatability to be expected from the execution of @code{MS}
 5292: @cindex @code{MS}, repeatability to be expected
 5293: System dependent. On Unix, a lot depends on load. If the system is
 5294: lightly loaded, and the delay is short enough that Gforth does not get
 5295: swapped out, the performance should be acceptable. Under MS-DOS and
 5296: other single-tasking systems, it should be good.
 5297: 
 5298: @end table
 5299: 
 5300: 
 5301: @c ---------------------------------------------------------------------
 5302: @node facility-ambcond,  , facility-idef, The optional Facility word set
 5303: @subsection Ambiguous conditions
 5304: @c ---------------------------------------------------------------------
 5305: @cindex facility words, ambiguous conditions
 5306: @cindex ambiguous conditions, facility words
 5307: 
 5308: @table @i
 5309: @item @code{AT-XY} can't be performed on user output device:
 5310: @cindex @code{AT-XY} can't be performed on user output device
 5311: Largely terminal dependent. No range checks are done on the arguments.
 5312: No errors are reported. You may see some garbage appearing, you may see
 5313: simply nothing happen.
 5314: 
 5315: @end table
 5316: 
 5317: 
 5318: @c =====================================================================
 5319: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
 5320: @section The optional File-Access word set
 5321: @c =====================================================================
 5322: @cindex system documentation, file words
 5323: @cindex file words, system documentation
 5324: 
 5325: @menu
 5326: * file-idef::                   Implementation Defined Options
 5327: * file-ambcond::                Ambiguous Conditions                
 5328: @end menu
 5329: 
 5330: @c ---------------------------------------------------------------------
 5331: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
 5332: @subsection Implementation Defined Options
 5333: @c ---------------------------------------------------------------------
 5334: @cindex implementation-defined options, file words
 5335: @cindex file words, implementation-defined options
 5336: 
 5337: @table @i
 5338: @item file access methods used:
 5339: @cindex file access methods used
 5340: @code{R/O}, @code{R/W} and @code{BIN} work as you would
 5341: expect. @code{W/O} translates into the C file opening mode @code{w} (or
 5342: @code{wb}): The file is cleared, if it exists, and created, if it does
 5343: not (with both @code{open-file} and @code{create-file}).  Under Unix
 5344: @code{create-file} creates a file with 666 permissions modified by your
 5345: umask.
 5346: 
 5347: @item file exceptions:
 5348: @cindex file exceptions
 5349: The file words do not raise exceptions (except, perhaps, memory access
 5350: faults when you pass illegal addresses or file-ids).
 5351: 
 5352: @item file line terminator:
 5353: @cindex file line terminator
 5354: System-dependent. Gforth uses C's newline character as line
 5355: terminator. What the actual character code(s) of this are is
 5356: system-dependent.
 5357: 
 5358: @item file name format:
 5359: @cindex file name format
 5360: System dependent. Gforth just uses the file name format of your OS.
 5361: 
 5362: @item information returned by @code{FILE-STATUS}:
 5363: @cindex @code{FILE-STATUS}, returned information
 5364: @code{FILE-STATUS} returns the most powerful file access mode allowed
 5365: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
 5366: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
 5367: along with the returned mode.
 5368: 
 5369: @item input file state after an exception when including source:
 5370: @cindex exception when including source
 5371: All files that are left via the exception are closed.
 5372: 
 5373: @item @var{ior} values and meaning:
 5374: @cindex @var{ior} values and meaning
 5375: The @var{ior}s returned by the file and memory allocation words are
 5376: intended as throw codes. They typically are in the range
 5377: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
 5378: @var{ior}s is -512@minus{}@var{errno}.
 5379: 
 5380: @item maximum depth of file input nesting:
 5381: @cindex maximum depth of file input nesting
 5382: @cindex file input nesting, maximum depth
 5383: limited by the amount of return stack, locals/TIB stack, and the number
 5384: of open files available. This should not give you troubles.
 5385: 
 5386: @item maximum size of input line:
 5387: @cindex maximum size of input line
 5388: @cindex input line size, maximum
 5389: @code{/line}. Currently 255.
 5390: 
 5391: @item methods of mapping block ranges to files:
 5392: @cindex mapping block ranges to files
 5393: @cindex files containing blocks
 5394: @cindex blocks in files
 5395: By default, blocks are accessed in the file @file{blocks.fb} in the
 5396: current working directory. The file can be switched with @code{USE}.
 5397: 
 5398: @item number of string buffers provided by @code{S"}:
 5399: @cindex @code{S"}, number of string buffers
 5400: 1
 5401: 
 5402: @item size of string buffer used by @code{S"}:
 5403: @cindex @code{S"}, size of string buffer
 5404: @code{/line}. currently 255.
 5405: 
 5406: @end table
 5407: 
 5408: @c ---------------------------------------------------------------------
 5409: @node file-ambcond,  , file-idef, The optional File-Access word set
 5410: @subsection Ambiguous conditions
 5411: @c ---------------------------------------------------------------------
 5412: @cindex file words, ambiguous conditions
 5413: @cindex ambiguous conditions, file words
 5414: 
 5415: @table @i
 5416: @item attempting to position a file outside its boundaries:
 5417: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
 5418: @code{REPOSITION-FILE} is performed as usual: Afterwards,
 5419: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
 5420: 
 5421: @item attempting to read from file positions not yet written:
 5422: @cindex reading from file positions not yet written
 5423: End-of-file, i.e., zero characters are read and no error is reported.
 5424: 
 5425: @item @var{file-id} is invalid (@code{INCLUDE-FILE}):
 5426: @cindex @code{INCLUDE-FILE}, @var{file-id} is invalid 
 5427: An appropriate exception may be thrown, but a memory fault or other
 5428: problem is more probable.
 5429: 
 5430: @item I/O exception reading or closing @var{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
 5431: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @var{file-id}
 5432: @cindex @code{INCLUDED}, I/O exception reading or closing @var{file-id}
 5433: The @var{ior} produced by the operation, that discovered the problem, is
 5434: thrown.
 5435: 
 5436: @item named file cannot be opened (@code{INCLUDED}):
 5437: @cindex @code{INCLUDED}, named file cannot be opened
 5438: The @var{ior} produced by @code{open-file} is thrown.
 5439: 
 5440: @item requesting an unmapped block number:
 5441: @cindex unmapped block numbers
 5442: There are no unmapped legal block numbers. On some operating systems,
 5443: writing a block with a large number may overflow the file system and
 5444: have an error message as consequence.
 5445: 
 5446: @item using @code{source-id} when @code{blk} is non-zero:
 5447: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
 5448: @code{source-id} performs its function. Typically it will give the id of
 5449: the source which loaded the block. (Better ideas?)
 5450: 
 5451: @end table
 5452: 
 5453: 
 5454: @c =====================================================================
 5455: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
 5456: @section The optional Floating-Point word set
 5457: @c =====================================================================
 5458: @cindex system documentation, floating-point words
 5459: @cindex floating-point words, system documentation
 5460: 
 5461: @menu
 5462: * floating-idef::               Implementation Defined Options
 5463: * floating-ambcond::            Ambiguous Conditions            
 5464: @end menu
 5465: 
 5466: 
 5467: @c ---------------------------------------------------------------------
 5468: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
 5469: @subsection Implementation Defined Options
 5470: @c ---------------------------------------------------------------------
 5471: @cindex implementation-defined options, floating-point words
 5472: @cindex floating-point words, implementation-defined options
 5473: 
 5474: @table @i
 5475: @item format and range of floating point numbers:
 5476: @cindex format and range of floating point numbers
 5477: @cindex floating point numbers, format and range
 5478: System-dependent; the @code{double} type of C.
 5479: 
 5480: @item results of @code{REPRESENT} when @var{float} is out of range:
 5481: @cindex  @code{REPRESENT}, results when @var{float} is out of range
 5482: System dependent; @code{REPRESENT} is implemented using the C library
 5483: function @code{ecvt()} and inherits its behaviour in this respect.
 5484: 
 5485: @item rounding or truncation of floating-point numbers:
 5486: @cindex rounding of floating-point numbers
 5487: @cindex truncation of floating-point numbers
 5488: @cindex floating-point numbers, rounding or truncation
 5489: System dependent; the rounding behaviour is inherited from the hosting C
 5490: compiler. IEEE-FP-based (i.e., most) systems by default round to
 5491: nearest, and break ties by rounding to even (i.e., such that the last
 5492: bit of the mantissa is 0).
 5493: 
 5494: @item size of floating-point stack:
 5495: @cindex floating-point stack size
 5496: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
 5497: the floating-point stack (in floats). You can specify this on startup
 5498: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
 5499: 
 5500: @item width of floating-point stack:
 5501: @cindex floating-point stack width 
 5502: @code{1 floats}.
 5503: 
 5504: @end table
 5505: 
 5506: 
 5507: @c ---------------------------------------------------------------------
 5508: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
 5509: @subsection Ambiguous conditions
 5510: @c ---------------------------------------------------------------------
 5511: @cindex floating-point words, ambiguous conditions
 5512: @cindex ambiguous conditions, floating-point words
 5513: 
 5514: @table @i
 5515: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
 5516: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
 5517: System-dependent. Typically results in a @code{-23 THROW} like other
 5518: alignment violations.
 5519: 
 5520: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
 5521: @cindex @code{f@@} used with an address that is not float aligned
 5522: @cindex @code{f!} used with an address that is not float aligned
 5523: System-dependent. Typically results in a @code{-23 THROW} like other
 5524: alignment violations.
 5525: 
 5526: @item floating-point result out of range:
 5527: @cindex floating-point result out of range
 5528: System-dependent. Can result in a @code{-55 THROW} (Floating-point
 5529: unidentified fault), or can produce a special value representing, e.g.,
 5530: Infinity.
 5531: 
 5532: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
 5533: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
 5534: System-dependent. Typically results in an alignment fault like other
 5535: alignment violations.
 5536: 
 5537: @item @code{BASE} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
 5538: @cindex @code{BASE} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
 5539: The floating-point number is converted into decimal nonetheless.
 5540: 
 5541: @item Both arguments are equal to zero (@code{FATAN2}):
 5542: @cindex @code{FATAN2}, both arguments are equal to zero
 5543: System-dependent. @code{FATAN2} is implemented using the C library
 5544: function @code{atan2()}.
 5545: 
 5546: @item Using @code{FTAN} on an argument @var{r1} where cos(@var{r1}) is zero:
 5547: @cindex @code{FTAN} on an argument @var{r1} where cos(@var{r1}) is zero
 5548: System-dependent. Anyway, typically the cos of @var{r1} will not be zero
 5549: because of small errors and the tan will be a very large (or very small)
 5550: but finite number.
 5551: 
 5552: @item @var{d} cannot be presented precisely as a float in @code{D>F}:
 5553: @cindex @code{D>F}, @var{d} cannot be presented precisely as a float
 5554: The result is rounded to the nearest float.
 5555: 
 5556: @item dividing by zero:
 5557: @cindex dividing by zero, floating-point
 5558: @cindex floating-point dividing by zero
 5559: @cindex floating-point unidentified fault, FP divide-by-zero
 5560: @code{-55 throw} (Floating-point unidentified fault)
 5561: 
 5562: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
 5563: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
 5564: System dependent. On IEEE-FP based systems the number is converted into
 5565: an infinity.
 5566: 
 5567: @item @var{float}<1 (@code{FACOSH}):
 5568: @cindex @code{FACOSH}, @var{float}<1
 5569: @cindex floating-point unidentified fault, @code{FACOSH}
 5570: @code{-55 throw} (Floating-point unidentified fault)
 5571: 
 5572: @item @var{float}=<-1 (@code{FLNP1}):
 5573: @cindex @code{FLNP1}, @var{float}=<-1
 5574: @cindex floating-point unidentified fault, @code{FLNP1}
 5575: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
 5576: negative infinity is typically produced for @var{float}=-1.
 5577: 
 5578: @item @var{float}=<0 (@code{FLN}, @code{FLOG}):
 5579: @cindex @code{FLN}, @var{float}=<0
 5580: @cindex @code{FLOG}, @var{float}=<0
 5581: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
 5582: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
 5583: negative infinity is typically produced for @var{float}=0.
 5584: 
 5585: @item @var{float}<0 (@code{FASINH}, @code{FSQRT}):
 5586: @cindex @code{FASINH}, @var{float}<0
 5587: @cindex @code{FSQRT}, @var{float}<0
 5588: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
 5589: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
 5590: produces values for these inputs on my Linux box (Bug in the C library?)
 5591: 
 5592: @item |@var{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
 5593: @cindex @code{FACOS}, |@var{float}|>1
 5594: @cindex @code{FASIN}, |@var{float}|>1
 5595: @cindex @code{FATANH}, |@var{float}|>1
 5596: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
 5597: @code{-55 throw} (Floating-point unidentified fault).
 5598: 
 5599: @item integer part of float cannot be represented by @var{d} in @code{F>D}:
 5600: @cindex @code{F>D}, integer part of float cannot be represented by @var{d}
 5601: @cindex floating-point unidentified fault, @code{F>D}
 5602: @code{-55 throw} (Floating-point unidentified fault).
 5603: 
 5604: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
 5605: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
 5606: This does not happen.
 5607: @end table
 5608: 
 5609: @c =====================================================================
 5610: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
 5611: @section The optional Locals word set
 5612: @c =====================================================================
 5613: @cindex system documentation, locals words
 5614: @cindex locals words, system documentation
 5615: 
 5616: @menu
 5617: * locals-idef::                 Implementation Defined Options                 
 5618: * locals-ambcond::              Ambiguous Conditions              
 5619: @end menu
 5620: 
 5621: 
 5622: @c ---------------------------------------------------------------------
 5623: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
 5624: @subsection Implementation Defined Options
 5625: @c ---------------------------------------------------------------------
 5626: @cindex implementation-defined options, locals words
 5627: @cindex locals words, implementation-defined options
 5628: 
 5629: @table @i
 5630: @item maximum number of locals in a definition:
 5631: @cindex maximum number of locals in a definition
 5632: @cindex locals, maximum number in a definition
 5633: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
 5634: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
 5635: characters. The number of locals in a definition is bounded by the size
 5636: of locals-buffer, which contains the names of the locals.
 5637: 
 5638: @end table
 5639: 
 5640: 
 5641: @c ---------------------------------------------------------------------
 5642: @node locals-ambcond,  , locals-idef, The optional Locals word set
 5643: @subsection Ambiguous conditions
 5644: @c ---------------------------------------------------------------------
 5645: @cindex locals words, ambiguous conditions
 5646: @cindex ambiguous conditions, locals words
 5647: 
 5648: @table @i
 5649: @item executing a named local in interpretation state:
 5650: @cindex local in interpretation state
 5651: @cindex Interpreting a compile-only word, for a local
 5652: Locals have no interpretation semantics. If you try to perform the
 5653: interpretation semantics, you will get a @code{-14 throw} somewhere
 5654: (Interpreting a compile-only word). If you perform the compilation
 5655: semantics, the locals access will be compiled (irrespective of state).
 5656: 
 5657: @item @var{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
 5658: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
 5659: @cindex @code{TO} on non-@code{VALUE}s and non-locals
 5660: @cindex Invalid name argument, @code{TO}
 5661: @code{-32 throw} (Invalid name argument)
 5662: 
 5663: @end table
 5664: 
 5665: 
 5666: @c =====================================================================
 5667: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
 5668: @section The optional Memory-Allocation word set
 5669: @c =====================================================================
 5670: @cindex system documentation, memory-allocation words
 5671: @cindex memory-allocation words, system documentation
 5672: 
 5673: @menu
 5674: * memory-idef::                 Implementation Defined Options                 
 5675: @end menu
 5676: 
 5677: 
 5678: @c ---------------------------------------------------------------------
 5679: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
 5680: @subsection Implementation Defined Options
 5681: @c ---------------------------------------------------------------------
 5682: @cindex implementation-defined options, memory-allocation words
 5683: @cindex memory-allocation words, implementation-defined options
 5684: 
 5685: @table @i
 5686: @item values and meaning of @var{ior}:
 5687: @cindex  @var{ior} values and meaning
 5688: The @var{ior}s returned by the file and memory allocation words are
 5689: intended as throw codes. They typically are in the range
 5690: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
 5691: @var{ior}s is -512@minus{}@var{errno}.
 5692: 
 5693: @end table
 5694: 
 5695: @c =====================================================================
 5696: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
 5697: @section The optional Programming-Tools word set
 5698: @c =====================================================================
 5699: @cindex system documentation, programming-tools words
 5700: @cindex programming-tools words, system documentation
 5701: 
 5702: @menu
 5703: * programming-idef::            Implementation Defined Options            
 5704: * programming-ambcond::         Ambiguous Conditions         
 5705: @end menu
 5706: 
 5707: 
 5708: @c ---------------------------------------------------------------------
 5709: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
 5710: @subsection Implementation Defined Options
 5711: @c ---------------------------------------------------------------------
 5712: @cindex implementation-defined options, programming-tools words
 5713: @cindex programming-tools words, implementation-defined options
 5714: 
 5715: @table @i
 5716: @item ending sequence for input following @code{;CODE} and @code{CODE}:
 5717: @cindex @code{;CODE} ending sequence
 5718: @cindex @code{CODE} ending sequence
 5719: @code{END-CODE}
 5720: 
 5721: @item manner of processing input following @code{;CODE} and @code{CODE}:
 5722: @cindex @code{;CODE}, processing input
 5723: @cindex @code{CODE}, processing input
 5724: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
 5725: the input is processed by the text interpreter, (starting) in interpret
 5726: state.
 5727: 
 5728: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
 5729: @cindex @code{ASSEMBLER}, search order capability
 5730: The ANS Forth search order word set.
 5731: 
 5732: @item source and format of display by @code{SEE}:
 5733: @cindex @code{SEE}, source and format of output
 5734: The source for @code{see} is the intermediate code used by the inner
 5735: interpreter.  The current @code{see} tries to output Forth source code
 5736: as well as possible.
 5737: 
 5738: @end table
 5739: 
 5740: @c ---------------------------------------------------------------------
 5741: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
 5742: @subsection Ambiguous conditions
 5743: @c ---------------------------------------------------------------------
 5744: @cindex programming-tools words, ambiguous conditions
 5745: @cindex ambiguous conditions, programming-tools words
 5746: 
 5747: @table @i
 5748: 
 5749: @item deleting the compilation wordlist (@code{FORGET}):
 5750: @cindex @code{FORGET}, deleting the compilation wordlist
 5751: Not implemented (yet).
 5752: 
 5753: @item fewer than @var{u}+1 items on the control flow stack (@code{CS-PICK}, @code{CS-ROLL}):
 5754: @cindex @code{CS-PICK}, fewer than @var{u}+1 items on the control flow stack
 5755: @cindex @code{CS-ROLL}, fewer than @var{u}+1 items on the control flow stack
 5756: @cindex control-flow stack underflow
 5757: This typically results in an @code{abort"} with a descriptive error
 5758: message (may change into a @code{-22 throw} (Control structure mismatch)
 5759: in the future). You may also get a memory access error. If you are
 5760: unlucky, this ambiguous condition is not caught.
 5761: 
 5762: @item @var{name} can't be found (@code{FORGET}):
 5763: @cindex @code{FORGET}, @var{name} can't be found
 5764: Not implemented (yet).
 5765: 
 5766: @item @var{name} not defined via @code{CREATE}:
 5767: @cindex @code{;CODE}, @var{name} not defined via @code{CREATE}
 5768: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
 5769: the execution semantics of the last defined word no matter how it was
 5770: defined.
 5771: 
 5772: @item @code{POSTPONE} applied to @code{[IF]}:
 5773: @cindex @code{POSTPONE} applied to @code{[IF]}
 5774: @cindex @code{[IF]} and @code{POSTPONE}
 5775: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
 5776: equivalent to @code{[IF]}.
 5777: 
 5778: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
 5779: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
 5780: Continue in the same state of conditional compilation in the next outer
 5781: input source. Currently there is no warning to the user about this.
 5782: 
 5783: @item removing a needed definition (@code{FORGET}):
 5784: @cindex @code{FORGET}, removing a needed definition
 5785: Not implemented (yet).
 5786: 
 5787: @end table
 5788: 
 5789: 
 5790: @c =====================================================================
 5791: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
 5792: @section The optional Search-Order word set
 5793: @c =====================================================================
 5794: @cindex system documentation, search-order words
 5795: @cindex search-order words, system documentation
 5796: 
 5797: @menu
 5798: * search-idef::                 Implementation Defined Options                 
 5799: * search-ambcond::              Ambiguous Conditions              
 5800: @end menu
 5801: 
 5802: 
 5803: @c ---------------------------------------------------------------------
 5804: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
 5805: @subsection Implementation Defined Options
 5806: @c ---------------------------------------------------------------------
 5807: @cindex implementation-defined options, search-order words
 5808: @cindex search-order words, implementation-defined options
 5809: 
 5810: @table @i
 5811: @item maximum number of word lists in search order:
 5812: @cindex maximum number of word lists in search order
 5813: @cindex search order, maximum depth
 5814: @code{s" wordlists" environment? drop .}. Currently 16.
 5815: 
 5816: @item minimum search order:
 5817: @cindex minimum search order
 5818: @cindex search order, minimum
 5819: @code{root root}.
 5820: 
 5821: @end table
 5822: 
 5823: @c ---------------------------------------------------------------------
 5824: @node search-ambcond,  , search-idef, The optional Search-Order word set
 5825: @subsection Ambiguous conditions
 5826: @c ---------------------------------------------------------------------
 5827: @cindex search-order words, ambiguous conditions
 5828: @cindex ambiguous conditions, search-order words
 5829: 
 5830: @table @i
 5831: @item changing the compilation wordlist (during compilation):
 5832: @cindex changing the compilation wordlist (during compilation)
 5833: @cindex compilation wordlist, change before definition ends
 5834: The word is entered into the wordlist that was the compilation wordlist
 5835: at the start of the definition. Any changes to the name field (e.g.,
 5836: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
 5837: are applied to the latest defined word (as reported by @code{last} or
 5838: @code{lastxt}), if possible, irrespective of the compilation wordlist.
 5839: 
 5840: @item search order empty (@code{previous}):
 5841: @cindex @code{previous}, search order empty
 5842: @cindex Vocstack empty, @code{previous}
 5843: @code{abort" Vocstack empty"}.
 5844: 
 5845: @item too many word lists in search order (@code{also}):
 5846: @cindex @code{also}, too many word lists in search order
 5847: @cindex Vocstack full, @code{also}
 5848: @code{abort" Vocstack full"}.
 5849: 
 5850: @end table
 5851: 
 5852: @c ***************************************************************
 5853: @node Model, Integrating Gforth, ANS conformance, Top
 5854: @chapter Model
 5855: 
 5856: This chapter has yet to be written. It will contain information, on
 5857: which internal structures you can rely.
 5858: 
 5859: @c ***************************************************************
 5860: @node Integrating Gforth, Emacs and Gforth, Model, Top
 5861: @chapter Integrating Gforth into C programs
 5862: 
 5863: This is not yet implemented.
 5864: 
 5865: Several people like to use Forth as scripting language for applications
 5866: that are otherwise written in C, C++, or some other language.
 5867: 
 5868: The Forth system ATLAST provides facilities for embedding it into
 5869: applications; unfortunately it has several disadvantages: most
 5870: importantly, it is not based on ANS Forth, and it is apparently dead
 5871: (i.e., not developed further and not supported). The facilities
 5872: provided by Gforth in this area are inspired by ATLASTs facilities, so
 5873: making the switch should not be hard.
 5874: 
 5875: We also tried to design the interface such that it can easily be
 5876: implemented by other Forth systems, so that we may one day arrive at a
 5877: standardized interface. Such a standard interface would allow you to
 5878: replace the Forth system without having to rewrite C code.
 5879: 
 5880: You embed the Gforth interpreter by linking with the library
 5881: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
 5882: global symbols in this library that belong to the interface, have the
 5883: prefix @code{forth_}. (Global symbols that are used internally have the
 5884: prefix @code{gforth_}).
 5885: 
 5886: You can include the declarations of Forth types and the functions and
 5887: variables of the interface with @code{#include <forth.h>}.
 5888: 
 5889: Types.
 5890: 
 5891: Variables.
 5892: 
 5893: Data and FP Stack pointer. Area sizes.
 5894: 
 5895: functions.
 5896: 
 5897: forth_init(imagefile)
 5898: forth_evaluate(string) exceptions?
 5899: forth_goto(address) (or forth_execute(xt)?)
 5900: forth_continue() (a corountining mechanism)
 5901: 
 5902: Adding primitives.
 5903: 
 5904: No checking.
 5905: 
 5906: Signals?
 5907: 
 5908: Accessing the Stacks
 5909: 
 5910: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
 5911: @chapter Emacs and Gforth
 5912: @cindex Emacs and Gforth
 5913: 
 5914: @cindex @file{gforth.el}
 5915: @cindex @file{forth.el}
 5916: @cindex Rydqvist, Goran
 5917: @cindex comment editing commands
 5918: @cindex @code{\}, editing with Emacs
 5919: @cindex debug tracer editing commands
 5920: @cindex @code{~~}, removal with Emacs
 5921: @cindex Forth mode in Emacs
 5922: Gforth comes with @file{gforth.el}, an improved version of
 5923: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
 5924: improvements are a better (but still not perfect) handling of
 5925: indentation. I have also added comment paragraph filling (@kbd{M-q}),
 5926: commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) regions and
 5927: removing debugging tracers (@kbd{C-x ~}, @pxref{Debugging}). I left the
 5928: stuff I do not use alone, even though some of it only makes sense for
 5929: TILE. To get a description of these features, enter Forth mode and type
 5930: @kbd{C-h m}.
 5931: 
 5932: @cindex source location of error or debugging output in Emacs
 5933: @cindex error output, finding the source location in Emacs
 5934: @cindex debugging output, finding the source location in Emacs
 5935: In addition, Gforth supports Emacs quite well: The source code locations
 5936: given in error messages, debugging output (from @code{~~}) and failed
 5937: assertion messages are in the right format for Emacs' compilation mode
 5938: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
 5939: Manual}) so the source location corresponding to an error or other
 5940: message is only a few keystrokes away (@kbd{C-x `} for the next error,
 5941: @kbd{C-c C-c} for the error under the cursor).
 5942: 
 5943: @cindex @file{TAGS} file
 5944: @cindex @file{etags.fs}
 5945: @cindex viewing the source of a word in Emacs
 5946: Also, if you @code{include} @file{etags.fs}, a new @file{TAGS} file
 5947: (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) will be produced that
 5948: contains the definitions of all words defined afterwards. You can then
 5949: find the source for a word using @kbd{M-.}. Note that emacs can use
 5950: several tags files at the same time (e.g., one for the Gforth sources
 5951: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
 5952: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
 5953: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
 5954: @file{/usr/local/share/gforth/0.2.0/TAGS}).
 5955: 
 5956: @cindex @file{.emacs}
 5957: To get all these benefits, add the following lines to your @file{.emacs}
 5958: file:
 5959: 
 5960: @example
 5961: (autoload 'forth-mode "gforth.el")
 5962: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
 5963: @end example
 5964: 
 5965: @node Image Files, Engine, Emacs and Gforth, Top
 5966: @chapter Image Files
 5967: @cindex image files
 5968: @cindex @code{.fi} files
 5969: @cindex precompiled Forth code
 5970: @cindex dictionary in persistent form
 5971: @cindex persistent form of dictionary
 5972: 
 5973: An image file is a file containing an image of the Forth dictionary,
 5974: i.e., compiled Forth code and data residing in the dictionary.  By
 5975: convention, we use the extension @code{.fi} for image files.
 5976: 
 5977: @menu
 5978: * Image File Background::          Why have image files?
 5979: * Non-Relocatable Image Files::    don't always work.
 5980: * Data-Relocatable Image Files::   are better.
 5981: * Fully Relocatable Image Files::  better yet.
 5982: * Stack and Dictionary Sizes::     Setting the default sizes for an image.
 5983: * Running Image Files::            @code{gforth -i @var{file}} or @var{file}.
 5984: * Modifying the Startup Sequence:: and turnkey applications.
 5985: @end menu
 5986: 
 5987: @node Image File Background, Non-Relocatable Image Files, Image Files, Image Files
 5988: @section Image File Background
 5989: @cindex image file background
 5990: 
 5991: Our Forth system consists not only of primitives, but also of
 5992: definitions written in Forth. Since the Forth compiler itself belongs to
 5993: those definitions, it is not possible to start the system with the
 5994: primitives and the Forth source alone. Therefore we provide the Forth
 5995: code as an image file in nearly executable form. At the start of the
 5996: system a C routine loads the image file into memory, optionally
 5997: relocates the addresses, then sets up the memory (stacks etc.) according
 5998: to information in the image file, and starts executing Forth code.
 5999: 
 6000: The image file variants represent different compromises between the
 6001: goals of making it easy to generate image files and making them
 6002: portable.
 6003: 
 6004: @cindex relocation at run-time
 6005: Win32Forth 3.4 and Mitch Bradleys @code{cforth} use relocation at
 6006: run-time. This avoids many of the complications discussed below (image
 6007: files are data relocatable without further ado), but costs performance
 6008: (one addition per memory access).
 6009: 
 6010: @cindex relocation at load-time
 6011: By contrast, our loader performs relocation at image load time. The
 6012: loader also has to replace tokens standing for primitive calls with the
 6013: appropriate code-field addresses (or code addresses in the case of
 6014: direct threading).
 6015: 
 6016: There are three kinds of image files, with different degrees of
 6017: relocatability: non-relocatable, data-relocatable, and fully relocatable
 6018: image files.
 6019: 
 6020: @cindex image file loader
 6021: @cindex relocating loader
 6022: @cindex loader for image files
 6023: These image file variants have several restrictions in common; they are
 6024: caused by the design of the image file loader:
 6025: 
 6026: @itemize @bullet
 6027: @item
 6028: There is only one segment; in particular, this means, that an image file
 6029: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
 6030: them). And the contents of the stacks are not represented, either.
 6031: 
 6032: @item
 6033: The only kinds of relocation supported are: adding the same offset to
 6034: all cells that represent data addresses; and replacing special tokens
 6035: with code addresses or with pieces of machine code.
 6036: 
 6037: If any complex computations involving addresses are performed, the
 6038: results cannot be represented in the image file. Several applications that
 6039: use such computations come to mind:
 6040: @itemize @minus
 6041: @item
 6042: Hashing addresses (or data structures which contain addresses) for table
 6043: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
 6044: purpose, you will have no problem, because the hash tables are
 6045: recomputed automatically when the system is started. If you use your own
 6046: hash tables, you will have to do something similar.
 6047: 
 6048: @item
 6049: There's a cute implementation of doubly-linked lists that uses
 6050: @code{XOR}ed addresses. You could represent such lists as singly-linked
 6051: in the image file, and restore the doubly-linked representation on
 6052: startup.@footnote{In my opinion, though, you should think thrice before
 6053: using a doubly-linked list (whatever implementation).}
 6054: 
 6055: @item
 6056: The code addresses of run-time routines like @code{docol:} cannot be
 6057: represented in the image file (because their tokens would be replaced by
 6058: machine code in direct threaded implementations). As a workaround,
 6059: compute these addresses at run-time with @code{>code-address} from the
 6060: executions tokens of appropriate words (see the definitions of
 6061: @code{docol:} and friends in @file{kernel.fs}).
 6062: 
 6063: @item
 6064: On many architectures addresses are represented in machine code in some
 6065: shifted or mangled form. You cannot put @code{CODE} words that contain
 6066: absolute addresses in this form in a relocatable image file. Workarounds
 6067: are representing the address in some relative form (e.g., relative to
 6068: the CFA, which is present in some register), or loading the address from
 6069: a place where it is stored in a non-mangled form.
 6070: @end itemize
 6071: @end itemize
 6072: 
 6073: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
 6074: @section Non-Relocatable Image Files
 6075: @cindex non-relocatable image files
 6076: @cindex image files, non-relocatable
 6077: 
 6078: These files are simple memory dumps of the dictionary. They are specific
 6079: to the executable (i.e., @file{gforth} file) they were created
 6080: with. What's worse, they are specific to the place on which the
 6081: dictionary resided when the image was created. Now, there is no
 6082: guarantee that the dictionary will reside at the same place the next
 6083: time you start Gforth, so there's no guarantee that a non-relocatable
 6084: image will work the next time (Gforth will complain instead of crashing,
 6085: though).
 6086: 
 6087: You can create a non-relocatable image file with
 6088: 
 6089: doc-savesystem
 6090: 
 6091: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
 6092: @section Data-Relocatable Image Files
 6093: @cindex data-relocatable image files
 6094: @cindex image files, data-relocatable
 6095: 
 6096: These files contain relocatable data addresses, but fixed code addresses
 6097: (instead of tokens). They are specific to the executable (i.e.,
 6098: @file{gforth} file) they were created with. For direct threading on some
 6099: architectures (e.g., the i386), data-relocatable images do not work. You
 6100: get a data-relocatable image, if you use @file{gforthmi} with a
 6101: Gforth binary that is not doubly indirect threaded (@pxref{Fully
 6102: Relocatable Image Files}).
 6103: 
 6104: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
 6105: @section Fully Relocatable Image Files
 6106: @cindex fully relocatable image files
 6107: @cindex image files, fully relocatable
 6108: 
 6109: @cindex @file{kern*.fi}, relocatability
 6110: @cindex @file{gforth.fi}, relocatability
 6111: These image files have relocatable data addresses, and tokens for code
 6112: addresses. They can be used with different binaries (e.g., with and
 6113: without debugging) on the same machine, and even across machines with
 6114: the same data formats (byte order, cell size, floating point
 6115: format). However, they are usually specific to the version of Gforth
 6116: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
 6117: are fully relocatable.
 6118: 
 6119: There are two ways to create a fully relocatable image file:
 6120: 
 6121: @menu
 6122: * gforthmi::            The normal way
 6123: * cross.fs::                    The hard way
 6124: @end menu
 6125: 
 6126: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
 6127: @subsection @file{gforthmi}
 6128: @cindex @file{comp-i.fs}
 6129: @cindex @file{gforthmi}
 6130: 
 6131: You will usually use @file{gforthmi}. If you want to create an
 6132: image @var{file} that contains everything you would load by invoking
 6133: Gforth with @code{gforth @var{options}}, you simply say
 6134: @example
 6135: gforthmi @var{file} @var{options}
 6136: @end example
 6137: 
 6138: E.g., if you want to create an image @file{asm.fi} that has the file
 6139: @file{asm.fs} loaded in addition to the usual stuff, you could do it
 6140: like this:
 6141: 
 6142: @example
 6143: gforthmi asm.fi asm.fs
 6144: @end example
 6145: 
 6146: @file{gforthmi} works like this: It produces two non-relocatable
 6147: images for different addresses and then compares them. Its output
 6148: reflects this: first you see the output (if any) of the two Gforth
 6149: invocations that produce the nonrelocatable image files, then you see
 6150: the output of the comparing program: It displays the offset used for
 6151: data addresses and the offset used for code addresses;
 6152: moreover, for each cell that cannot be represented correctly in the
 6153: image files, it displays a line like the following one:
 6154: 
 6155: @example
 6156:      78DC         BFFFFA50         BFFFFA40
 6157: @end example
 6158: 
 6159: This means that at offset $78dc from @code{forthstart}, one input image
 6160: contains $bffffa50, and the other contains $bffffa40. Since these cells
 6161: cannot be represented correctly in the output image, you should examine
 6162: these places in the dictionary and verify that these cells are dead
 6163: (i.e., not read before they are written).
 6164: 
 6165: @cindex @code{savesystem} during @file{gforthmi}
 6166: @cindex @code{bye} during @file{gforthmi}
 6167: @cindex doubly indirect threaded code
 6168: @cindex environment variable @code{GFORTHD}
 6169: @cindex @code{GFORTHD} environment variable
 6170: @cindex @code{gforth-ditc}
 6171: There are a few wrinkles: After processing the passed @var{options}, the
 6172: words @code{savesystem} and @code{bye} must be visible. A special doubly
 6173: indirect threaded version of the @file{gforth} executable is used for
 6174: creating the nonrelocatable images; you can pass the exact filename of
 6175: this executable through the environment variable @code{GFORTHD}
 6176: (default: @file{gforth-ditc}); if you pass a version that is not doubly
 6177: indirect threaded, you will not get a fully relocatable image, but a
 6178: data-relocatable image (because there is no code address offset).
 6179: 
 6180: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
 6181: @subsection @file{cross.fs}
 6182: @cindex @file{cross.fs}
 6183: @cindex cross-compiler
 6184: @cindex metacompiler
 6185: 
 6186: You can also use @code{cross}, a batch compiler that accepts a Forth-like
 6187: programming language. This @code{cross} language has to be documented
 6188: yet.
 6189: 
 6190: @cindex target compiler
 6191: @code{cross} also allows you to create image files for machines with
 6192: different data sizes and data formats than the one used for generating
 6193: the image file. You can also use it to create an application image that
 6194: does not contain a Forth compiler. These features are bought with
 6195: restrictions and inconveniences in programming. E.g., addresses have to
 6196: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
 6197: order to make the code relocatable.
 6198: 
 6199: 
 6200: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
 6201: @section Stack and Dictionary Sizes
 6202: @cindex image file, stack and dictionary sizes
 6203: @cindex dictionary size default
 6204: @cindex stack size default
 6205: 
 6206: If you invoke Gforth with a command line flag for the size
 6207: (@pxref{Invoking Gforth}), the size you specify is stored in the
 6208: dictionary. If you save the dictionary with @code{savesystem} or create
 6209: an image with @file{gforthmi}, this size will become the default
 6210: for the resulting image file. E.g., the following will create a
 6211: fully relocatable version of gforth.fi with a 1MB dictionary:
 6212: 
 6213: @example
 6214: gforthmi gforth.fi -m 1M
 6215: @end example
 6216: 
 6217: In other words, if you want to set the default size for the dictionary
 6218: and the stacks of an image, just invoke @file{gforthmi} with the
 6219: appropriate options when creating the image.
 6220: 
 6221: @cindex stack size, cache-friendly
 6222: Note: For cache-friendly behaviour (i.e., good performance), you should
 6223: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
 6224: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
 6225: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
 6226: 
 6227: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
 6228: @section Running Image Files
 6229: @cindex running image files
 6230: @cindex invoking image files
 6231: @cindex image file invocation
 6232: 
 6233: @cindex -i, invoke image file
 6234: @cindex --image file, invoke image file
 6235: You can invoke Gforth with an image file @var{image} instead of the
 6236: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
 6237: @example
 6238: gforth -i @var{image}
 6239: @end example
 6240: 
 6241: @cindex executable image file
 6242: @cindex image files, executable
 6243: If your operating system supports starting scripts with a line of the
 6244: form @code{#! ...}, you just have to type the image file name to start
 6245: Gforth with this image file (note that the file extension @code{.fi} is
 6246: just a convention). I.e., to run Gforth with the image file @var{image},
 6247: you can just type @var{image} instead of @code{gforth -i @var{image}}.
 6248: 
 6249: doc-#!
 6250: 
 6251: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
 6252: @section Modifying the Startup Sequence
 6253: @cindex startup sequence for image file
 6254: @cindex image file initialization sequence
 6255: @cindex initialization sequence of image file
 6256: 
 6257: You can add your own initialization to the startup sequence through the
 6258: deferred word
 6259: 
 6260: doc-'cold
 6261: 
 6262: @code{'cold} is invoked just before the image-specific command line
 6263: processing (by default, loading files and evaluating (@code{-e}) strings)
 6264: starts.
 6265: 
 6266: A sequence for adding your initialization usually looks like this:
 6267: 
 6268: @example
 6269: :noname
 6270:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
 6271:     ... \ your stuff
 6272: ; IS 'cold
 6273: @end example
 6274: 
 6275: @cindex turnkey image files
 6276: @cindex image files, turnkey applications
 6277: You can make a turnkey image by letting @code{'cold} execute a word
 6278: (your turnkey application) that never returns; instead, it exits Gforth
 6279: via @code{bye} or @code{throw}.
 6280: 
 6281: @cindex command-line arguments, access
 6282: @cindex arguments on the command line, access
 6283: You can access the (image-specific) command-line arguments through the
 6284: variables @code{argc} and @code{argv}. @code{arg} provides conventient
 6285: access to @code{argv}.
 6286: 
 6287: doc-argc
 6288: doc-argv
 6289: doc-arg
 6290: 
 6291: If @code{'cold} exits normally, Gforth processes the command-line
 6292: arguments as files to be loaded and strings to be evaluated.  Therefore,
 6293: @code{'cold} should remove the arguments it has used in this case.
 6294: 
 6295: @c ******************************************************************
 6296: @node Engine, Bugs, Image Files, Top
 6297: @chapter Engine
 6298: @cindex engine
 6299: @cindex virtual machine
 6300: 
 6301: Reading this section is not necessary for programming with Gforth. It
 6302: may be helpful for finding your way in the Gforth sources.
 6303: 
 6304: The ideas in this section have also been published in the papers
 6305: @cite{ANS fig/GNU/??? Forth} (in German) by Bernd Paysan, presented at
 6306: the Forth-Tagung '93 and @cite{A Portable Forth Engine} by M. Anton
 6307: Ertl, presented at EuroForth '93; the latter is available at
 6308: @*@url{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z}.
 6309: 
 6310: @menu
 6311: * Portability::                 
 6312: * Threading::                   
 6313: * Primitives::                  
 6314: * Performance::                 
 6315: @end menu
 6316: 
 6317: @node Portability, Threading, Engine, Engine
 6318: @section Portability
 6319: @cindex engine portability
 6320: 
 6321: One of the main goals of the effort is availability across a wide range
 6322: of personal machines. fig-Forth, and, to a lesser extent, F83, achieved
 6323: this goal by manually coding the engine in assembly language for several
 6324: then-popular processors. This approach is very labor-intensive and the
 6325: results are short-lived due to progress in computer architecture.
 6326: 
 6327: @cindex C, using C for the engine
 6328: Others have avoided this problem by coding in C, e.g., Mitch Bradley
 6329: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
 6330: particularly popular for UNIX-based Forths due to the large variety of
 6331: architectures of UNIX machines. Unfortunately an implementation in C
 6332: does not mix well with the goals of efficiency and with using
 6333: traditional techniques: Indirect or direct threading cannot be expressed
 6334: in C, and switch threading, the fastest technique available in C, is
 6335: significantly slower. Another problem with C is that it is very
 6336: cumbersome to express double integer arithmetic.
 6337: 
 6338: @cindex GNU C for the engine
 6339: @cindex long long
 6340: Fortunately, there is a portable language that does not have these
 6341: limitations: GNU C, the version of C processed by the GNU C compiler
 6342: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
 6343: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
 6344: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
 6345: threading possible, its @code{long long} type (@pxref{Long Long, ,
 6346: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
 6347: double numbers@footnote{Unfortunately, long longs are not implemented
 6348: properly on all machines (e.g., on alpha-osf1, long longs are only 64
 6349: bits, the same size as longs (and pointers), but they should be twice as
 6350: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
 6351: C Manual}). So, we had to implement doubles in C after all. Still, on
 6352: most machines we can use long longs and achieve better performance than
 6353: with the emulation package.}. GNU C is available for free on all
 6354: important (and many unimportant) UNIX machines, VMS, 80386s running
 6355: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
 6356: on all these machines.
 6357: 
 6358: Writing in a portable language has the reputation of producing code that
 6359: is slower than assembly. For our Forth engine we repeatedly looked at
 6360: the code produced by the compiler and eliminated most compiler-induced
 6361: inefficiencies by appropriate changes in the source code.
 6362: 
 6363: @cindex explicit register declarations
 6364: @cindex --enable-force-reg, configuration flag
 6365: @cindex -DFORCE_REG
 6366: However, register allocation cannot be portably influenced by the
 6367: programmer, leading to some inefficiencies on register-starved
 6368: machines. We use explicit register declarations (@pxref{Explicit Reg
 6369: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
 6370: improve the speed on some machines. They are turned on by using the
 6371: configuration flag @code{--enable-force-reg} (@code{gcc} switch
 6372: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
 6373: machine, but also on the compiler version: On some machines some
 6374: compiler versions produce incorrect code when certain explicit register
 6375: declarations are used. So by default @code{-DFORCE_REG} is not used.
 6376: 
 6377: @node Threading, Primitives, Portability, Engine
 6378: @section Threading
 6379: @cindex inner interpreter implementation
 6380: @cindex threaded code implementation
 6381: 
 6382: @cindex labels as values
 6383: GNU C's labels as values extension (available since @code{gcc-2.0},
 6384: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
 6385: makes it possible to take the address of @var{label} by writing
 6386: @code{&&@var{label}}.  This address can then be used in a statement like
 6387: @code{goto *@var{address}}. I.e., @code{goto *&&x} is the same as
 6388: @code{goto x}.
 6389: 
 6390: @cindex NEXT, indirect threaded
 6391: @cindex indirect threaded inner interpreter
 6392: @cindex inner interpreter, indirect threaded
 6393: With this feature an indirect threaded NEXT looks like:
 6394: @example
 6395: cfa = *ip++;
 6396: ca = *cfa;
 6397: goto *ca;
 6398: @end example
 6399: @cindex instruction pointer
 6400: For those unfamiliar with the names: @code{ip} is the Forth instruction
 6401: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
 6402: execution token and points to the code field of the next word to be
 6403: executed; The @code{ca} (code address) fetched from there points to some
 6404: executable code, e.g., a primitive or the colon definition handler
 6405: @code{docol}.
 6406: 
 6407: @cindex NEXT, direct threaded
 6408: @cindex direct threaded inner interpreter
 6409: @cindex inner interpreter, direct threaded
 6410: Direct threading is even simpler:
 6411: @example
 6412: ca = *ip++;
 6413: goto *ca;
 6414: @end example
 6415: 
 6416: Of course we have packaged the whole thing neatly in macros called
 6417: @code{NEXT} and @code{NEXT1} (the part of NEXT after fetching the cfa).
 6418: 
 6419: @menu
 6420: * Scheduling::                  
 6421: * Direct or Indirect Threaded?::  
 6422: * DOES>::                       
 6423: @end menu
 6424: 
 6425: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
 6426: @subsection Scheduling
 6427: @cindex inner interpreter optimization
 6428: 
 6429: There is a little complication: Pipelined and superscalar processors,
 6430: i.e., RISC and some modern CISC machines can process independent
 6431: instructions while waiting for the results of an instruction. The
 6432: compiler usually reorders (schedules) the instructions in a way that
 6433: achieves good usage of these delay slots. However, on our first tries
 6434: the compiler did not do well on scheduling primitives. E.g., for
 6435: @code{+} implemented as
 6436: @example
 6437: n=sp[0]+sp[1];
 6438: sp++;
 6439: sp[0]=n;
 6440: NEXT;
 6441: @end example
 6442: the NEXT comes strictly after the other code, i.e., there is nearly no
 6443: scheduling. After a little thought the problem becomes clear: The
 6444: compiler cannot know that sp and ip point to different addresses (and
 6445: the version of @code{gcc} we used would not know it even if it was
 6446: possible), so it could not move the load of the cfa above the store to
 6447: the TOS. Indeed the pointers could be the same, if code on or very near
 6448: the top of stack were executed. In the interest of speed we chose to
 6449: forbid this probably unused ``feature'' and helped the compiler in
 6450: scheduling: NEXT is divided into the loading part (@code{NEXT_P1}) and
 6451: the goto part (@code{NEXT_P2}). @code{+} now looks like:
 6452: @example
 6453: n=sp[0]+sp[1];
 6454: sp++;
 6455: NEXT_P1;
 6456: sp[0]=n;
 6457: NEXT_P2;
 6458: @end example
 6459: This can be scheduled optimally by the compiler.
 6460: 
 6461: This division can be turned off with the switch @code{-DCISC_NEXT}. This
 6462: switch is on by default on machines that do not profit from scheduling
 6463: (e.g., the 80386), in order to preserve registers.
 6464: 
 6465: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
 6466: @subsection Direct or Indirect Threaded?
 6467: @cindex threading, direct or indirect?
 6468: 
 6469: @cindex -DDIRECT_THREADED
 6470: Both! After packaging the nasty details in macro definitions we
 6471: realized that we could switch between direct and indirect threading by
 6472: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
 6473: defining a few machine-specific macros for the direct-threading case.
 6474: On the Forth level we also offer access words that hide the
 6475: differences between the threading methods (@pxref{Threading Words}).
 6476: 
 6477: Indirect threading is implemented completely machine-independently.
 6478: Direct threading needs routines for creating jumps to the executable
 6479: code (e.g. to docol or dodoes). These routines are inherently
 6480: machine-dependent, but they do not amount to many source lines. I.e.,
 6481: even porting direct threading to a new machine is a small effort.
 6482: 
 6483: @cindex --enable-indirect-threaded, configuration flag
 6484: @cindex --enable-direct-threaded, configuration flag
 6485: The default threading method is machine-dependent. You can enforce a
 6486: specific threading method when building Gforth with the configuration
 6487: flag @code{--enable-direct-threaded} or
 6488: @code{--enable-indirect-threaded}. Note that direct threading is not
 6489: supported on all machines.
 6490: 
 6491: @node DOES>,  , Direct or Indirect Threaded?, Threading
 6492: @subsection DOES>
 6493: @cindex @code{DOES>} implementation
 6494: 
 6495: @cindex dodoes routine
 6496: @cindex DOES-code
 6497: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
 6498: the chunk of code executed by every word defined by a
 6499: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
 6500: the Forth code to be executed, i.e. the code after the
 6501: @code{DOES>} (the DOES-code)? There are two solutions:
 6502: 
 6503: In fig-Forth the code field points directly to the dodoes and the
 6504: DOES-code address is stored in the cell after the code address (i.e. at
 6505: @code{@var{cfa} cell+}). It may seem that this solution is illegal in
 6506: the Forth-79 and all later standards, because in fig-Forth this address
 6507: lies in the body (which is illegal in these standards). However, by
 6508: making the code field larger for all words this solution becomes legal
 6509: again. We use this approach for the indirect threaded version and for
 6510: direct threading on some machines. Leaving a cell unused in most words
 6511: is a bit wasteful, but on the machines we are targeting this is hardly a
 6512: problem. The other reason for having a code field size of two cells is
 6513: to avoid having different image files for direct and indirect threaded
 6514: systems (direct threaded systems require two-cell code fields on many
 6515: machines).
 6516: 
 6517: @cindex DOES-handler
 6518: The other approach is that the code field points or jumps to the cell
 6519: after @code{DOES}. In this variant there is a jump to @code{dodoes} at
 6520: this address (the DOES-handler). @code{dodoes} can then get the
 6521: DOES-code address by computing the code address, i.e., the address of
 6522: the jump to dodoes, and add the length of that jump field. A variant of
 6523: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
 6524: return address (which can be found in the return register on RISCs) is
 6525: the DOES-code address. Since the two cells available in the code field
 6526: are used up by the jump to the code address in direct threading on many
 6527: architectures, we use this approach for direct threading on these
 6528: architectures. We did not want to add another cell to the code field.
 6529: 
 6530: @node Primitives, Performance, Threading, Engine
 6531: @section Primitives
 6532: @cindex primitives, implementation
 6533: @cindex virtual machine instructions, implementation
 6534: 
 6535: @menu
 6536: * Automatic Generation::        
 6537: * TOS Optimization::            
 6538: * Produced code::               
 6539: @end menu
 6540: 
 6541: @node Automatic Generation, TOS Optimization, Primitives, Primitives
 6542: @subsection Automatic Generation
 6543: @cindex primitives, automatic generation
 6544: 
 6545: @cindex @file{prims2x.fs}
 6546: Since the primitives are implemented in a portable language, there is no
 6547: longer any need to minimize the number of primitives. On the contrary,
 6548: having many primitives has an advantage: speed. In order to reduce the
 6549: number of errors in primitives and to make programming them easier, we
 6550: provide a tool, the primitive generator (@file{prims2x.fs}), that
 6551: automatically generates most (and sometimes all) of the C code for a
 6552: primitive from the stack effect notation.  The source for a primitive
 6553: has the following form:
 6554: 
 6555: @cindex primitive source format
 6556: @format
 6557: @var{Forth-name}	@var{stack-effect}	@var{category}	[@var{pronounc.}]
 6558: [@code{""}@var{glossary entry}@code{""}]
 6559: @var{C code}
 6560: [@code{:}
 6561: @var{Forth code}]
 6562: @end format
 6563: 
 6564: The items in brackets are optional. The category and glossary fields
 6565: are there for generating the documentation, the Forth code is there
 6566: for manual implementations on machines without GNU C. E.g., the source
 6567: for the primitive @code{+} is:
 6568: @example
 6569: +    n1 n2 -- n    core    plus
 6570: n = n1+n2;
 6571: @end example
 6572: 
 6573: This looks like a specification, but in fact @code{n = n1+n2} is C
 6574: code. Our primitive generation tool extracts a lot of information from
 6575: the stack effect notations@footnote{We use a one-stack notation, even
 6576: though we have separate data and floating-point stacks; The separate
 6577: notation can be generated easily from the unified notation.}: The number
 6578: of items popped from and pushed on the stack, their type, and by what
 6579: name they are referred to in the C code. It then generates a C code
 6580: prelude and postlude for each primitive. The final C code for @code{+}
 6581: looks like this:
 6582: 
 6583: @example
 6584: I_plus:	/* + ( n1 n2 -- n ) */  /* label, stack effect */
 6585: /*  */                          /* documentation */
 6586: @{
 6587: DEF_CA                          /* definition of variable ca (indirect threading) */
 6588: Cell n1;                        /* definitions of variables */
 6589: Cell n2;
 6590: Cell n;
 6591: n1 = (Cell) sp[1];              /* input */
 6592: n2 = (Cell) TOS;
 6593: sp += 1;                        /* stack adjustment */
 6594: NAME("+")                       /* debugging output (with -DDEBUG) */
 6595: @{
 6596: n = n1+n2;                      /* C code taken from the source */
 6597: @}
 6598: NEXT_P1;                        /* NEXT part 1 */
 6599: TOS = (Cell)n;                  /* output */
 6600: NEXT_P2;                        /* NEXT part 2 */
 6601: @}
 6602: @end example
 6603: 
 6604: This looks long and inefficient, but the GNU C compiler optimizes quite
 6605: well and produces optimal code for @code{+} on, e.g., the R3000 and the
 6606: HP RISC machines: Defining the @code{n}s does not produce any code, and
 6607: using them as intermediate storage also adds no cost.
 6608: 
 6609: There are also other optimizations, that are not illustrated by this
 6610: example: Assignments between simple variables are usually for free (copy
 6611: propagation). If one of the stack items is not used by the primitive
 6612: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
 6613: (dead code elimination). On the other hand, there are some things that
 6614: the compiler does not do, therefore they are performed by
 6615: @file{prims2x.fs}: The compiler does not optimize code away that stores
 6616: a stack item to the place where it just came from (e.g., @code{over}).
 6617: 
 6618: While programming a primitive is usually easy, there are a few cases
 6619: where the programmer has to take the actions of the generator into
 6620: account, most notably @code{?dup}, but also words that do not (always)
 6621: fall through to NEXT.
 6622: 
 6623: @node TOS Optimization, Produced code, Automatic Generation, Primitives
 6624: @subsection TOS Optimization
 6625: @cindex TOS optimization for primitives
 6626: @cindex primitives, keeping the TOS in a register
 6627: 
 6628: An important optimization for stack machine emulators, e.g., Forth
 6629: engines, is keeping  one or more of the top stack items in
 6630: registers.  If a word has the stack effect @var{in1}...@var{inx} @code{--}
 6631: @var{out1}...@var{outy}, keeping the top @var{n} items in registers
 6632: @itemize @bullet
 6633: @item
 6634: is better than keeping @var{n-1} items, if @var{x>=n} and @var{y>=n},
 6635: due to fewer loads from and stores to the stack.
 6636: @item is slower than keeping @var{n-1} items, if @var{x<>y} and @var{x<n} and
 6637: @var{y<n}, due to additional moves between registers.
 6638: @end itemize
 6639: 
 6640: @cindex -DUSE_TOS
 6641: @cindex -DUSE_NO_TOS
 6642: In particular, keeping one item in a register is never a disadvantage,
 6643: if there are enough registers. Keeping two items in registers is a
 6644: disadvantage for frequent words like @code{?branch}, constants,
 6645: variables, literals and @code{i}. Therefore our generator only produces
 6646: code that keeps zero or one items in registers. The generated C code
 6647: covers both cases; the selection between these alternatives is made at
 6648: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
 6649: code for @code{+} is just a simple variable name in the one-item case,
 6650: otherwise it is a macro that expands into @code{sp[0]}. Note that the
 6651: GNU C compiler tries to keep simple variables like @code{TOS} in
 6652: registers, and it usually succeeds, if there are enough registers.
 6653: 
 6654: @cindex -DUSE_FTOS
 6655: @cindex -DUSE_NO_FTOS
 6656: The primitive generator performs the TOS optimization for the
 6657: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
 6658: operations the benefit of this optimization is even larger:
 6659: floating-point operations take quite long on most processors, but can be
 6660: performed in parallel with other operations as long as their results are
 6661: not used. If the FP-TOS is kept in a register, this works. If
 6662: it is kept on the stack, i.e., in memory, the store into memory has to
 6663: wait for the result of the floating-point operation, lengthening the
 6664: execution time of the primitive considerably.
 6665: 
 6666: The TOS optimization makes the automatic generation of primitives a
 6667: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
 6668: @code{TOS} is not sufficient. There are some special cases to
 6669: consider:
 6670: @itemize @bullet
 6671: @item In the case of @code{dup ( w -- w w )} the generator must not
 6672: eliminate the store to the original location of the item on the stack,
 6673: if the TOS optimization is turned on.
 6674: @item Primitives with stack effects of the form @code{--}
 6675: @var{out1}...@var{outy} must store the TOS to the stack at the start.
 6676: Likewise, primitives with the stack effect @var{in1}...@var{inx} @code{--}
 6677: must load the TOS from the stack at the end. But for the null stack
 6678: effect @code{--} no stores or loads should be generated.
 6679: @end itemize
 6680: 
 6681: @node Produced code,  , TOS Optimization, Primitives
 6682: @subsection Produced code
 6683: @cindex primitives, assembly code listing
 6684: 
 6685: @cindex @file{engine.s}
 6686: To see what assembly code is produced for the primitives on your machine
 6687: with your compiler and your flag settings, type @code{make engine.s} and
 6688: look at the resulting file @file{engine.s}.
 6689: 
 6690: @node  Performance,  , Primitives, Engine
 6691: @section Performance
 6692: @cindex performance of some Forth interpreters
 6693: @cindex engine performance
 6694: @cindex benchmarking Forth systems
 6695: @cindex Gforth performance
 6696: 
 6697: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
 6698: impossible to write a significantly faster engine.
 6699: 
 6700: On register-starved machines like the 386 architecture processors
 6701: improvements are possible, because @code{gcc} does not utilize the
 6702: registers as well as a human, even with explicit register declarations;
 6703: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
 6704: and hand-tuned it for the 486; this system is 1.19 times faster on the
 6705: Sieve benchmark on a 486DX2/66 than Gforth compiled with
 6706: @code{gcc-2.6.3} with @code{-DFORCE_REG}.
 6707: 
 6708: @cindex Win32Forth performance
 6709: @cindex NT Forth performance
 6710: @cindex eforth performance
 6711: @cindex ThisForth performance
 6712: @cindex PFE performance
 6713: @cindex TILE performance
 6714: However, this potential advantage of assembly language implementations
 6715: is not necessarily realized in complete Forth systems: We compared
 6716: Gforth (direct threaded, compiled with @code{gcc-2.6.3} and
 6717: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
 6718: 1994) and Eforth (with and without peephole (aka pinhole) optimization
 6719: of the threaded code); all these systems were written in assembly
 6720: language. We also compared Gforth with three systems written in C:
 6721: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
 6722: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
 6723: -DUNROLL_NEXT}), ThisForth Beta (compiled with gcc-2.6.3 -O3
 6724: -fomit-frame-pointer; ThisForth employs peephole optimization of the
 6725: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
 6726: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
 6727: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
 6728: 486DX2/66 with similar memory performance under Windows NT. Marcel
 6729: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
 6730: added the peephole optimizer, ran the benchmarks and reported the
 6731: results.
 6732:  
 6733: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
 6734: matrix multiplication come from the Stanford integer benchmarks and have
 6735: been translated into Forth by Martin Fraeman; we used the versions
 6736: included in the TILE Forth package, but with bigger data set sizes; and
 6737: a recursive Fibonacci number computation for benchmarking calling
 6738: performance. The following table shows the time taken for the benchmarks
 6739: scaled by the time taken by Gforth (in other words, it shows the speedup
 6740: factor that Gforth achieved over the other systems).
 6741: 
 6742: @example
 6743: relative      Win32-    NT       eforth       This-
 6744:   time  Gforth Forth Forth eforth  +opt   PFE Forth  TILE
 6745: sieve     1.00  1.39  1.14   1.39  0.85  1.58  3.18  8.58
 6746: bubble    1.00  1.31  1.41   1.48  0.88  1.50        3.88
 6747: matmul    1.00  1.47  1.35   1.46  0.74  1.58        4.09
 6748: fib       1.00  1.52  1.34   1.22  0.86  1.74  2.99  4.30
 6749: @end example
 6750: 
 6751: You may find the good performance of Gforth compared with the systems
 6752: written in assembly language quite surprising. One important reason for
 6753: the disappointing performance of these systems is probably that they are
 6754: not written optimally for the 486 (e.g., they use the @code{lods}
 6755: instruction). In addition, Win32Forth uses a comfortable, but costly
 6756: method for relocating the Forth image: like @code{cforth}, it computes
 6757: the actual addresses at run time, resulting in two address computations
 6758: per NEXT (@pxref{Image File Background}).
 6759: 
 6760: Only Eforth with the peephole optimizer performs comparable to
 6761: Gforth. The speedups achieved with peephole optimization of threaded
 6762: code are quite remarkable. Adding a peephole optimizer to Gforth should
 6763: cause similar speedups.
 6764: 
 6765: The speedup of Gforth over PFE, ThisForth and TILE can be easily
 6766: explained with the self-imposed restriction of the latter systems to
 6767: standard C, which makes efficient threading impossible (however, the
 6768: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
 6769: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
 6770: Moreover, current C compilers have a hard time optimizing other aspects
 6771: of the ThisForth and the TILE source.
 6772: 
 6773: Note that the performance of Gforth on 386 architecture processors
 6774: varies widely with the version of @code{gcc} used. E.g., @code{gcc-2.5.8}
 6775: failed to allocate any of the virtual machine registers into real
 6776: machine registers by itself and would not work correctly with explicit
 6777: register declarations, giving a 1.3 times slower engine (on a 486DX2/66
 6778: running the Sieve) than the one measured above.
 6779: 
 6780: Note also that there have been several releases of Win32Forth since the
 6781: release presented here, so the results presented here may have little
 6782: predictive value for the performance of Win32Forth today.
 6783: 
 6784: @cindex @file{Benchres}
 6785: In @cite{Translating Forth to Efficient C} by M. Anton Ertl and Martin
 6786: Maierhofer (presented at EuroForth '95), an indirect threaded version of
 6787: Gforth is compared with Win32Forth, NT Forth, PFE, and ThisForth; that
 6788: version of Gforth is 2%@minus{}8% slower on a 486 than the direct
 6789: threaded version used here. The paper available at
 6790: @*@url{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz};
 6791: it also contains numbers for some native code systems. You can find a
 6792: newer version of these measurements at
 6793: @url{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
 6794: find numbers for Gforth on various machines in @file{Benchres}.
 6795: 
 6796: @node Bugs, Origin, Engine, Top
 6797: @chapter Bugs
 6798: @cindex bug reporting
 6799: 
 6800: Known bugs are described in the file BUGS in the Gforth distribution.
 6801: 
 6802: If you find a bug, please send a bug report to
 6803: @email{bug-gforth@@gnu.ai.mit.edu}. A bug report should
 6804: describe the Gforth version used (it is announced at the start of an
 6805: interactive Gforth session), the machine and operating system (on Unix
 6806: systems you can use @code{uname -a} to produce this information), the
 6807: installation options (send the @file{config.status} file), and a
 6808: complete list of changes you (or your installer) have made to the Gforth
 6809: sources (if any); it should contain a program (or a sequence of keyboard
 6810: commands) that reproduces the bug and a description of what you think
 6811: constitutes the buggy behaviour.
 6812: 
 6813: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
 6814: to Report Bugs, gcc.info, GNU C Manual}.
 6815: 
 6816: 
 6817: @node Origin, Word Index, Bugs, Top
 6818: @chapter Authors and Ancestors of Gforth
 6819: 
 6820: @section Authors and Contributors
 6821: @cindex authors of Gforth
 6822: @cindex contributors to Gforth
 6823: 
 6824: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
 6825: Ertl. The third major author was Jens Wilke.  Lennart Benschop (who was
 6826: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
 6827: with their continuous feedback. Lennart Benshop contributed
 6828: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
 6829: support for calling C libraries. Helpful comments also came from Paul
 6830: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
 6831: Wavrik, Barrie Stott and Marc de Groot.
 6832: 
 6833: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
 6834: and autoconf, among others), and to the creators of the Internet: Gforth
 6835: was developed across the Internet, and its authors have not met
 6836: physically yet.
 6837: 
 6838: @section Pedigree
 6839: @cindex Pedigree of Gforth
 6840: 
 6841: Gforth descends from BigForth (1993) and fig-Forth. Gforth and PFE (by
 6842: Dirk Zoller) will cross-fertilize each other. Of course, a significant
 6843: part of the design of Gforth was prescribed by ANS Forth.
 6844: 
 6845: Bernd Paysan wrote BigForth, a descendent from TurboForth, an unreleased
 6846: 32 bit native code version of VolksForth for the Atari ST, written
 6847: mostly by Dietrich Weineck.
 6848: 
 6849: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
 6850: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
 6851: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
 6852: 
 6853: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
 6854: Forth-83 standard. !! Pedigree? When?
 6855: 
 6856: A team led by Bill Ragsdale implemented fig-Forth on many processors in
 6857: 1979. Robert Selzer and Bill Ragsdale developed the original
 6858: implementation of fig-Forth for the 6502 based on microForth.
 6859: 
 6860: The principal architect of microForth was Dean Sanderson. microForth was
 6861: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
 6862: the 1802, and subsequently implemented on the 8080, the 6800 and the
 6863: Z80.
 6864: 
 6865: All earlier Forth systems were custom-made, usually by Charles Moore,
 6866: who discovered (as he puts it) Forth during the late 60s. The first full
 6867: Forth existed in 1971.
 6868: 
 6869: A part of the information in this section comes from @cite{The Evolution
 6870: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
 6871: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
 6872: Notices 28(3), 1993.  You can find more historical and genealogical
 6873: information about Forth there.
 6874: 
 6875: @node Word Index, Concept Index, Origin, Top
 6876: @unnumbered Word Index
 6877: 
 6878: This index is as incomplete as the manual. Each word is listed with
 6879: stack effect and wordset.
 6880: 
 6881: @printindex fn
 6882: 
 6883: @node Concept Index,  , Word Index, Top
 6884: @unnumbered Concept and Word Index
 6885: 
 6886: This index is as incomplete as the manual. Not all entries listed are
 6887: present verbatim in the text. Only the names are listed for the words
 6888: here.
 6889: 
 6890: @printindex cp
 6891: 
 6892: @contents
 6893: @bye
 6894: 

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