File:  [gforth] / gforth / Attic / gforth.ds
Revision 1.36: download - view: text, annotated - select for diffs
Mon Sep 23 08:52:47 1996 UTC (27 years, 7 months ago) by anton
Branches: MAIN
CVS tags: HEAD
documentation changes

    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: @comment @setchapternewpage odd
    7: @comment %**end of header (This is for running Texinfo on a region.)
    8: 
    9: @ifinfo
   10: This file documents Gforth 0.2
   11: 
   12: Copyright @copyright{} 1995,1996 Free Software Foundation, Inc.
   13: 
   14:      Permission is granted to make and distribute verbatim copies of
   15:      this manual provided the copyright notice and this permission notice
   16:      are preserved on all copies.
   17:      
   18: @ignore
   19:      Permission is granted to process this file through TeX and print the
   20:      results, provided the printed document carries a copying permission
   21:      notice identical to this one except for the removal of this paragraph
   22:      (this paragraph not being relevant to the printed manual).
   23:      
   24: @end ignore
   25:      Permission is granted to copy and distribute modified versions of this
   26:      manual under the conditions for verbatim copying, provided also that the
   27:      sections entitled "Distribution" and "General Public License" are
   28:      included exactly as in the original, and provided that the entire
   29:      resulting derived work is distributed under the terms of a permission
   30:      notice identical to this one.
   31:      
   32:      Permission is granted to copy and distribute translations of this manual
   33:      into another language, under the above conditions for modified versions,
   34:      except that the sections entitled "Distribution" and "General Public
   35:      License" may be included in a translation approved by the author instead
   36:      of in the original English.
   37: @end ifinfo
   38: 
   39: @finalout
   40: @titlepage
   41: @sp 10
   42: @center @titlefont{Gforth Manual}
   43: @sp 2
   44: @center for version 0.2
   45: @sp 2
   46: @center Anton Ertl
   47: @center Bernd Paysan
   48: @sp 3
   49: @center This manual is under construction
   50: 
   51: @comment  The following two commands start the copyright page.
   52: @page
   53: @vskip 0pt plus 1filll
   54: Copyright @copyright{} 1995,1996 Free Software Foundation, Inc.
   55: 
   56: @comment !! Published by ... or You can get a copy of this manual ...
   57: 
   58:      Permission is granted to make and distribute verbatim copies of
   59:      this manual provided the copyright notice and this permission notice
   60:      are preserved on all copies.
   61:      
   62:      Permission is granted to copy and distribute modified versions of this
   63:      manual under the conditions for verbatim copying, provided also that the
   64:      sections entitled "Distribution" and "General Public License" are
   65:      included exactly as in the original, and provided that the entire
   66:      resulting derived work is distributed under the terms of a permission
   67:      notice identical to this one.
   68:      
   69:      Permission is granted to copy and distribute translations of this manual
   70:      into another language, under the above conditions for modified versions,
   71:      except that the sections entitled "Distribution" and "General Public
   72:      License" may be included in a translation approved by the author instead
   73:      of in the original English.
   74: @end titlepage
   75: 
   76: 
   77: @node Top, License, (dir), (dir)
   78: @ifinfo
   79: Gforth is a free implementation of ANS Forth available on many
   80: personal machines. This manual corresponds to version 0.2.
   81: @end ifinfo
   82: 
   83: @menu
   84: * License::                     
   85: * Goals::                       About the Gforth Project
   86: * Other Books::                 Things you might want to read
   87: * Invocation::                  Starting Gforth
   88: * Words::                       Forth words available in Gforth
   89: * ANS conformance::             Implementation-defined options etc.
   90: * Model::                       The abstract machine of Gforth
   91: * Integrating Gforth::          Forth as scripting language for applications.
   92: * Emacs and Gforth::            The Gforth Mode
   93: * Internals::                   Implementation details
   94: * Bugs::                        How to report them
   95: * Origin::                      Authors and ancestors of Gforth
   96: * Word Index::                  An item for each Forth word
   97: * Node Index::                  An item for each node
   98: @end menu
   99: 
  100: @node License, Goals, Top, Top
  101: @unnumbered GNU GENERAL PUBLIC LICENSE
  102: @center Version 2, June 1991
  103: 
  104: @display
  105: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
  106: 675 Mass Ave, Cambridge, MA 02139, USA
  107: 
  108: Everyone is permitted to copy and distribute verbatim copies
  109: of this license document, but changing it is not allowed.
  110: @end display
  111: 
  112: @unnumberedsec Preamble
  113: 
  114:   The licenses for most software are designed to take away your
  115: freedom to share and change it.  By contrast, the GNU General Public
  116: License is intended to guarantee your freedom to share and change free
  117: software---to make sure the software is free for all its users.  This
  118: General Public License applies to most of the Free Software
  119: Foundation's software and to any other program whose authors commit to
  120: using it.  (Some other Free Software Foundation software is covered by
  121: the GNU Library General Public License instead.)  You can apply it to
  122: your programs, too.
  123: 
  124:   When we speak of free software, we are referring to freedom, not
  125: price.  Our General Public Licenses are designed to make sure that you
  126: have the freedom to distribute copies of free software (and charge for
  127: this service if you wish), that you receive source code or can get it
  128: if you want it, that you can change the software or use pieces of it
  129: in new free programs; and that you know you can do these things.
  130: 
  131:   To protect your rights, we need to make restrictions that forbid
  132: anyone to deny you these rights or to ask you to surrender the rights.
  133: These restrictions translate to certain responsibilities for you if you
  134: distribute copies of the software, or if you modify it.
  135: 
  136:   For example, if you distribute copies of such a program, whether
  137: gratis or for a fee, you must give the recipients all the rights that
  138: you have.  You must make sure that they, too, receive or can get the
  139: source code.  And you must show them these terms so they know their
  140: rights.
  141: 
  142:   We protect your rights with two steps: (1) copyright the software, and
  143: (2) offer you this license which gives you legal permission to copy,
  144: distribute and/or modify the software.
  145: 
  146:   Also, for each author's protection and ours, we want to make certain
  147: that everyone understands that there is no warranty for this free
  148: software.  If the software is modified by someone else and passed on, we
  149: want its recipients to know that what they have is not the original, so
  150: that any problems introduced by others will not reflect on the original
  151: authors' reputations.
  152: 
  153:   Finally, any free program is threatened constantly by software
  154: patents.  We wish to avoid the danger that redistributors of a free
  155: program will individually obtain patent licenses, in effect making the
  156: program proprietary.  To prevent this, we have made it clear that any
  157: patent must be licensed for everyone's free use or not licensed at all.
  158: 
  159:   The precise terms and conditions for copying, distribution and
  160: modification follow.
  161: 
  162: @iftex
  163: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  164: @end iftex
  165: @ifinfo
  166: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  167: @end ifinfo
  168: 
  169: @enumerate 0
  170: @item
  171: This License applies to any program or other work which contains
  172: a notice placed by the copyright holder saying it may be distributed
  173: under the terms of this General Public License.  The ``Program'', below,
  174: refers to any such program or work, and a ``work based on the Program''
  175: means either the Program or any derivative work under copyright law:
  176: that is to say, a work containing the Program or a portion of it,
  177: either verbatim or with modifications and/or translated into another
  178: language.  (Hereinafter, translation is included without limitation in
  179: the term ``modification''.)  Each licensee is addressed as ``you''.
  180: 
  181: Activities other than copying, distribution and modification are not
  182: covered by this License; they are outside its scope.  The act of
  183: running the Program is not restricted, and the output from the Program
  184: is covered only if its contents constitute a work based on the
  185: Program (independent of having been made by running the Program).
  186: Whether that is true depends on what the Program does.
  187: 
  188: @item
  189: You may copy and distribute verbatim copies of the Program's
  190: source code as you receive it, in any medium, provided that you
  191: conspicuously and appropriately publish on each copy an appropriate
  192: copyright notice and disclaimer of warranty; keep intact all the
  193: notices that refer to this License and to the absence of any warranty;
  194: and give any other recipients of the Program a copy of this License
  195: along with the Program.
  196: 
  197: You may charge a fee for the physical act of transferring a copy, and
  198: you may at your option offer warranty protection in exchange for a fee.
  199: 
  200: @item
  201: You may modify your copy or copies of the Program or any portion
  202: of it, thus forming a work based on the Program, and copy and
  203: distribute such modifications or work under the terms of Section 1
  204: above, provided that you also meet all of these conditions:
  205: 
  206: @enumerate a
  207: @item
  208: You must cause the modified files to carry prominent notices
  209: stating that you changed the files and the date of any change.
  210: 
  211: @item
  212: You must cause any work that you distribute or publish, that in
  213: whole or in part contains or is derived from the Program or any
  214: part thereof, to be licensed as a whole at no charge to all third
  215: parties under the terms of this License.
  216: 
  217: @item
  218: If the modified program normally reads commands interactively
  219: when run, you must cause it, when started running for such
  220: interactive use in the most ordinary way, to print or display an
  221: announcement including an appropriate copyright notice and a
  222: notice that there is no warranty (or else, saying that you provide
  223: a warranty) and that users may redistribute the program under
  224: these conditions, and telling the user how to view a copy of this
  225: License.  (Exception: if the Program itself is interactive but
  226: does not normally print such an announcement, your work based on
  227: the Program is not required to print an announcement.)
  228: @end enumerate
  229: 
  230: These requirements apply to the modified work as a whole.  If
  231: identifiable sections of that work are not derived from the Program,
  232: and can be reasonably considered independent and separate works in
  233: themselves, then this License, and its terms, do not apply to those
  234: sections when you distribute them as separate works.  But when you
  235: distribute the same sections as part of a whole which is a work based
  236: on the Program, the distribution of the whole must be on the terms of
  237: this License, whose permissions for other licensees extend to the
  238: entire whole, and thus to each and every part regardless of who wrote it.
  239: 
  240: Thus, it is not the intent of this section to claim rights or contest
  241: your rights to work written entirely by you; rather, the intent is to
  242: exercise the right to control the distribution of derivative or
  243: collective works based on the Program.
  244: 
  245: In addition, mere aggregation of another work not based on the Program
  246: with the Program (or with a work based on the Program) on a volume of
  247: a storage or distribution medium does not bring the other work under
  248: the scope of this License.
  249: 
  250: @item
  251: You may copy and distribute the Program (or a work based on it,
  252: under Section 2) in object code or executable form under the terms of
  253: Sections 1 and 2 above provided that you also do one of the following:
  254: 
  255: @enumerate a
  256: @item
  257: Accompany it with the complete corresponding machine-readable
  258: source code, which must be distributed under the terms of Sections
  259: 1 and 2 above on a medium customarily used for software interchange; or,
  260: 
  261: @item
  262: Accompany it with a written offer, valid for at least three
  263: years, to give any third party, for a charge no more than your
  264: cost of physically performing source distribution, a complete
  265: machine-readable copy of the corresponding source code, to be
  266: distributed under the terms of Sections 1 and 2 above on a medium
  267: customarily used for software interchange; or,
  268: 
  269: @item
  270: Accompany it with the information you received as to the offer
  271: to distribute corresponding source code.  (This alternative is
  272: allowed only for noncommercial distribution and only if you
  273: received the program in object code or executable form with such
  274: an offer, in accord with Subsection b above.)
  275: @end enumerate
  276: 
  277: The source code for a work means the preferred form of the work for
  278: making modifications to it.  For an executable work, complete source
  279: code means all the source code for all modules it contains, plus any
  280: associated interface definition files, plus the scripts used to
  281: control compilation and installation of the executable.  However, as a
  282: special exception, the source code distributed need not include
  283: anything that is normally distributed (in either source or binary
  284: form) with the major components (compiler, kernel, and so on) of the
  285: operating system on which the executable runs, unless that component
  286: itself accompanies the executable.
  287: 
  288: If distribution of executable or object code is made by offering
  289: access to copy from a designated place, then offering equivalent
  290: access to copy the source code from the same place counts as
  291: distribution of the source code, even though third parties are not
  292: compelled to copy the source along with the object code.
  293: 
  294: @item
  295: You may not copy, modify, sublicense, or distribute the Program
  296: except as expressly provided under this License.  Any attempt
  297: otherwise to copy, modify, sublicense or distribute the Program is
  298: void, and will automatically terminate your rights under this License.
  299: However, parties who have received copies, or rights, from you under
  300: this License will not have their licenses terminated so long as such
  301: parties remain in full compliance.
  302: 
  303: @item
  304: You are not required to accept this License, since you have not
  305: signed it.  However, nothing else grants you permission to modify or
  306: distribute the Program or its derivative works.  These actions are
  307: prohibited by law if you do not accept this License.  Therefore, by
  308: modifying or distributing the Program (or any work based on the
  309: Program), you indicate your acceptance of this License to do so, and
  310: all its terms and conditions for copying, distributing or modifying
  311: the Program or works based on it.
  312: 
  313: @item
  314: Each time you redistribute the Program (or any work based on the
  315: Program), the recipient automatically receives a license from the
  316: original licensor to copy, distribute or modify the Program subject to
  317: these terms and conditions.  You may not impose any further
  318: restrictions on the recipients' exercise of the rights granted herein.
  319: You are not responsible for enforcing compliance by third parties to
  320: this License.
  321: 
  322: @item
  323: If, as a consequence of a court judgment or allegation of patent
  324: infringement or for any other reason (not limited to patent issues),
  325: conditions are imposed on you (whether by court order, agreement or
  326: otherwise) that contradict the conditions of this License, they do not
  327: excuse you from the conditions of this License.  If you cannot
  328: distribute so as to satisfy simultaneously your obligations under this
  329: License and any other pertinent obligations, then as a consequence you
  330: may not distribute the Program at all.  For example, if a patent
  331: license would not permit royalty-free redistribution of the Program by
  332: all those who receive copies directly or indirectly through you, then
  333: the only way you could satisfy both it and this License would be to
  334: refrain entirely from distribution of the Program.
  335: 
  336: If any portion of this section is held invalid or unenforceable under
  337: any particular circumstance, the balance of the section is intended to
  338: apply and the section as a whole is intended to apply in other
  339: circumstances.
  340: 
  341: It is not the purpose of this section to induce you to infringe any
  342: patents or other property right claims or to contest validity of any
  343: such claims; this section has the sole purpose of protecting the
  344: integrity of the free software distribution system, which is
  345: implemented by public license practices.  Many people have made
  346: generous contributions to the wide range of software distributed
  347: through that system in reliance on consistent application of that
  348: system; it is up to the author/donor to decide if he or she is willing
  349: to distribute software through any other system and a licensee cannot
  350: impose that choice.
  351: 
  352: This section is intended to make thoroughly clear what is believed to
  353: be a consequence of the rest of this License.
  354: 
  355: @item
  356: If the distribution and/or use of the Program is restricted in
  357: certain countries either by patents or by copyrighted interfaces, the
  358: original copyright holder who places the Program under this License
  359: may add an explicit geographical distribution limitation excluding
  360: those countries, so that distribution is permitted only in or among
  361: countries not thus excluded.  In such case, this License incorporates
  362: the limitation as if written in the body of this License.
  363: 
  364: @item
  365: The Free Software Foundation may publish revised and/or new versions
  366: of the General Public License from time to time.  Such new versions will
  367: be similar in spirit to the present version, but may differ in detail to
  368: address new problems or concerns.
  369: 
  370: Each version is given a distinguishing version number.  If the Program
  371: specifies a version number of this License which applies to it and ``any
  372: later version'', you have the option of following the terms and conditions
  373: either of that version or of any later version published by the Free
  374: Software Foundation.  If the Program does not specify a version number of
  375: this License, you may choose any version ever published by the Free Software
  376: Foundation.
  377: 
  378: @item
  379: If you wish to incorporate parts of the Program into other free
  380: programs whose distribution conditions are different, write to the author
  381: to ask for permission.  For software which is copyrighted by the Free
  382: Software Foundation, write to the Free Software Foundation; we sometimes
  383: make exceptions for this.  Our decision will be guided by the two goals
  384: of preserving the free status of all derivatives of our free software and
  385: of promoting the sharing and reuse of software generally.
  386: 
  387: @iftex
  388: @heading NO WARRANTY
  389: @end iftex
  390: @ifinfo
  391: @center NO WARRANTY
  392: @end ifinfo
  393: 
  394: @item
  395: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
  396: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
  397: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
  398: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
  399: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  400: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
  401: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
  402: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
  403: REPAIR OR CORRECTION.
  404: 
  405: @item
  406: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
  407: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
  408: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
  409: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
  410: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
  411: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
  412: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
  413: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
  414: POSSIBILITY OF SUCH DAMAGES.
  415: @end enumerate
  416: 
  417: @iftex
  418: @heading END OF TERMS AND CONDITIONS
  419: @end iftex
  420: @ifinfo
  421: @center END OF TERMS AND CONDITIONS
  422: @end ifinfo
  423: 
  424: @page
  425: @unnumberedsec How to Apply These Terms to Your New Programs
  426: 
  427:   If you develop a new program, and you want it to be of the greatest
  428: possible use to the public, the best way to achieve this is to make it
  429: free software which everyone can redistribute and change under these terms.
  430: 
  431:   To do so, attach the following notices to the program.  It is safest
  432: to attach them to the start of each source file to most effectively
  433: convey the exclusion of warranty; and each file should have at least
  434: the ``copyright'' line and a pointer to where the full notice is found.
  435: 
  436: @smallexample
  437: @var{one line to give the program's name and a brief idea of what it does.}
  438: Copyright (C) 19@var{yy}  @var{name of author}
  439: 
  440: This program is free software; you can redistribute it and/or modify 
  441: it under the terms of the GNU General Public License as published by 
  442: the Free Software Foundation; either version 2 of the License, or 
  443: (at your option) any later version.
  444: 
  445: This program is distributed in the hope that it will be useful,
  446: but WITHOUT ANY WARRANTY; without even the implied warranty of
  447: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  448: GNU General Public License for more details.
  449: 
  450: You should have received a copy of the GNU General Public License
  451: along with this program; if not, write to the Free Software
  452: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  453: @end smallexample
  454: 
  455: Also add information on how to contact you by electronic and paper mail.
  456: 
  457: If the program is interactive, make it output a short notice like this
  458: when it starts in an interactive mode:
  459: 
  460: @smallexample
  461: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
  462: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
  463: type `show w'.  
  464: This is free software, and you are welcome to redistribute it 
  465: under certain conditions; type `show c' for details.
  466: @end smallexample
  467: 
  468: The hypothetical commands @samp{show w} and @samp{show c} should show
  469: the appropriate parts of the General Public License.  Of course, the
  470: commands you use may be called something other than @samp{show w} and
  471: @samp{show c}; they could even be mouse-clicks or menu items---whatever
  472: suits your program.
  473: 
  474: You should also get your employer (if you work as a programmer) or your
  475: school, if any, to sign a ``copyright disclaimer'' for the program, if
  476: necessary.  Here is a sample; alter the names:
  477: 
  478: @smallexample
  479: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  480: `Gnomovision' (which makes passes at compilers) written by James Hacker.
  481: 
  482: @var{signature of Ty Coon}, 1 April 1989
  483: Ty Coon, President of Vice
  484: @end smallexample
  485: 
  486: This General Public License does not permit incorporating your program into
  487: proprietary programs.  If your program is a subroutine library, you may
  488: consider it more useful to permit linking proprietary applications with the
  489: library.  If this is what you want to do, use the GNU Library General
  490: Public License instead of this License.
  491: 
  492: @iftex
  493: @node    Preface
  494: @comment node-name,     next,           previous, up
  495: @unnumbered Preface
  496: @cindex Preface
  497: This manual documents Gforth. The reader is expected to know
  498: Forth. This manual is primarily a reference manual. @xref{Other Books}
  499: for introductory material.
  500: @end iftex
  501: 
  502: @node    Goals, Other Books, License, Top
  503: @comment node-name,     next,           previous, up
  504: @chapter Goals of Gforth
  505: @cindex Goals
  506: The goal of the Gforth Project is to develop a standard model for
  507: ANSI Forth. This can be split into several subgoals:
  508: 
  509: @itemize @bullet
  510: @item
  511: Gforth should conform to the ANSI Forth standard.
  512: @item
  513: It should be a model, i.e. it should define all the
  514: implementation-dependent things.
  515: @item
  516: It should become standard, i.e. widely accepted and used. This goal
  517: is the most difficult one.
  518: @end itemize
  519: 
  520: To achieve these goals Gforth should be
  521: @itemize @bullet
  522: @item
  523: Similar to previous models (fig-Forth, F83)
  524: @item
  525: Powerful. It should provide for all the things that are considered
  526: necessary today and even some that are not yet considered necessary.
  527: @item
  528: Efficient. It should not get the reputation of being exceptionally
  529: slow.
  530: @item
  531: Free.
  532: @item
  533: Available on many machines/easy to port.
  534: @end itemize
  535: 
  536: Have we achieved these goals? Gforth conforms to the ANS Forth
  537: standard. It may be considered a model, but we have not yet documented
  538: which parts of the model are stable and which parts we are likely to
  539: change. It certainly has not yet become a de facto standard. It has some
  540: similarities and some differences to previous models. It has some
  541: powerful features, but not yet everything that we envisioned. We
  542: certainly have achieved our execution speed goals (@pxref{Performance}).
  543: It is free and available on many machines.
  544: 
  545: @node Other Books, Invocation, Goals, Top
  546: @chapter Other books on ANS Forth
  547: 
  548: As the standard is relatively new, there are not many books out yet. It
  549: is not recommended to learn Forth by using Gforth and a book that is
  550: not written for ANS Forth, as you will not know your mistakes from the
  551: deviations of the book.
  552: 
  553: There is, of course, the standard, the definite reference if you want to
  554: write ANS Forth programs. It is available in printed form from the
  555: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
  556: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about $200. You
  557: can also get it from Global Engineering Documents (Tel.: USA (800)
  558: 854-7179; Fax.: (303) 843-9880) for about $300.
  559: 
  560: @cite{dpANS6}, the last draft of the standard, which was then submitted to ANSI
  561: for publication is available electronically and for free in some MS Word
  562: format, and it has been converted to HTML. Some pointers to these
  563: versions can be found through
  564: @*@file{http://www.complang.tuwien.ac.at/projects/forth.html}.
  565: 
  566: @cite{Forth: The new model} by Jack Woehr (Prentice-Hall, 1993) is an
  567: introductory book based on a draft version of the standard. It does not
  568: cover the whole standard. It also contains interesting background
  569: information (Jack Woehr was in the ANS Forth Technical Committe). It is
  570: not appropriate for complete newbies, but programmers experienced in
  571: other languages should find it ok.
  572: 
  573: @node Invocation, Words, Other Books, Top
  574: @chapter Invocation
  575: 
  576: You will usually just say @code{gforth}. In many other cases the default
  577: Gforth image will be invoked like this:
  578: 
  579: @example
  580: gforth [files] [-e forth-code]
  581: @end example
  582: 
  583: executing the contents of the files and the Forth code in the order they
  584: are given.
  585: 
  586: In general, the command line looks like this:
  587: 
  588: @example
  589: gforth [initialization options] [image-specific options]
  590: @end example
  591: 
  592: The initialization options must come before the rest of the command
  593: line. They are:
  594: 
  595: @table @code
  596: @item --image-file @var{file}
  597: @item -i @var{file}
  598: Loads the Forth image @var{file} instead of the default
  599: @file{gforth.fi}.
  600: 
  601: @item --path @var{path}
  602: @item -p @var{path}
  603: Uses @var{path} for searching the image file and Forth source code
  604: files instead of the default in the environment variable
  605: @code{GFORTHPATH} or the path specified at installation time (typically
  606: @file{/usr/local/lib/gforth:.}). A path is given as a @code{:}-separated
  607: list.
  608: 
  609: @item --dictionary-size @var{size}
  610: @item -m @var{size}
  611: Allocate @var{size} space for the Forth dictionary space instead of
  612: using the default specified in the image (typically 256K). The
  613: @var{size} specification consists of an integer and a unit (e.g.,
  614: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
  615: size, in this case Cells), @code{k} (kilobytes), and @code{M}
  616: (Megabytes). If no unit is specified, @code{e} is used.
  617: 
  618: @item --data-stack-size @var{size}
  619: @item -d @var{size}
  620: Allocate @var{size} space for the data stack instead of using the
  621: default specified in the image (typically 16K).
  622: 
  623: @item --return-stack-size @var{size}
  624: @item -r @var{size}
  625: Allocate @var{size} space for the return stack instead of using the
  626: default specified in the image (typically 16K).
  627: 
  628: @item --fp-stack-size @var{size}
  629: @item -f @var{size}
  630: Allocate @var{size} space for the floating point stack instead of
  631: using the default specified in the image (typically 16K). In this case
  632: the unit specifier @code{e} refers to floating point numbers.
  633: 
  634: @item --locals-stack-size @var{size}
  635: @item -l @var{size}
  636: Allocate @var{size} space for the locals stack instead of using the
  637: default specified in the image (typically 16K).
  638: 
  639: @end table
  640: 
  641: As explained above, the image-specific command-line arguments for the
  642: default image @file{gforth.fi} consist of a sequence of filenames and
  643: @code{-e @var{forth-code}} options that are interpreted in the seqence
  644: in which they are given. The @code{-e @var{forth-code}} or
  645: @code{--evaluate @var{forth-code}} option evaluates the forth
  646: code. This option takes only one argument; if you want to evaluate more
  647: Forth words, you have to quote them or use several @code{-e}s. To exit
  648: after processing the command line (instead of entering interactive mode)
  649: append @code{-e bye} to the command line.
  650: 
  651: If you have several versions of Gforth installed, @code{gforth} will
  652: invoke the version that was installed last. @code{gforth-@var{version}}
  653: invokes a specific version. You may want to use the option
  654: @code{--path}, if your environment contains the variable
  655: @code{GFORTHPATH}.
  656: 
  657: Not yet implemented:
  658: On startup the system first executes the system initialization file
  659: (unless the option @code{--no-init-file} is given; note that the system
  660: resulting from using this option may not be ANS Forth conformant). Then
  661: the user initialization file @file{.gforth.fs} is executed, unless the
  662: option @code{--no-rc} is given; this file is first searched in @file{.},
  663: then in @file{~}, then in the normal path (see above).
  664: 
  665: @node Words, ANS conformance, Invocation, Top
  666: @chapter Forth Words
  667: 
  668: @menu
  669: * Notation::                    
  670: * Arithmetic::                  
  671: * Stack Manipulation::          
  672: * Memory access::               
  673: * Control Structures::          
  674: * Locals::                      
  675: * Defining Words::              
  676: * Wordlists::                   
  677: * Files::                       
  678: * Blocks::                      
  679: * Other I/O::                   
  680: * Programming Tools::           
  681: * Assembler and Code words::    
  682: * Threading Words::             
  683: @end menu
  684: 
  685: @node Notation, Arithmetic, Words, Words
  686: @section Notation
  687: 
  688: The Forth words are described in this section in the glossary notation
  689: that has become a de-facto standard for Forth texts, i.e.
  690: 
  691: @format
  692: @var{word}     @var{Stack effect}   @var{wordset}   @var{pronunciation}
  693: @end format
  694: @var{Description}
  695: 
  696: @table @var
  697: @item word
  698: The name of the word. BTW, Gforth is case insensitive, so you can
  699: type the words in in lower case (However, @pxref{core-idef}).
  700: 
  701: @item Stack effect
  702: The stack effect is written in the notation @code{@var{before} --
  703: @var{after}}, where @var{before} and @var{after} describe the top of
  704: stack entries before and after the execution of the word. The rest of
  705: the stack is not touched by the word. The top of stack is rightmost,
  706: i.e., a stack sequence is written as it is typed in. Note that Gforth
  707: uses a separate floating point stack, but a unified stack
  708: notation. Also, return stack effects are not shown in @var{stack
  709: effect}, but in @var{Description}. The name of a stack item describes
  710: the type and/or the function of the item. See below for a discussion of
  711: the types.
  712: 
  713: All words have two stack effects: A compile-time stack effect and a
  714: run-time stack effect. The compile-time stack-effect of most words is
  715: @var{ -- }. If the compile-time stack-effect of a word deviates from
  716: this standard behaviour, or the word does other unusual things at
  717: compile time, both stack effects are shown; otherwise only the run-time
  718: stack effect is shown.
  719: 
  720: @item pronunciation
  721: How the word is pronounced
  722: 
  723: @item wordset
  724: The ANS Forth standard is divided into several wordsets. A standard
  725: system need not support all of them. So, the fewer wordsets your program
  726: uses the more portable it will be in theory. However, we suspect that
  727: most ANS Forth systems on personal machines will feature all
  728: wordsets. Words that are not defined in the ANS standard have
  729: @code{gforth} or @code{gforth-internal} as wordset. @code{gforth}
  730: describes words that will work in future releases of Gforth;
  731: @code{gforth-internal} words are more volatile. Environmental query
  732: strings are also displayed like words; you can recognize them by the
  733: @code{environment} in the wordset field.
  734: 
  735: @item Description
  736: A description of the behaviour of the word.
  737: @end table
  738: 
  739: The type of a stack item is specified by the character(s) the name
  740: starts with:
  741: 
  742: @table @code
  743: @item f
  744: Bool, i.e. @code{false} or @code{true}.
  745: @item c
  746: Char
  747: @item w
  748: Cell, can contain an integer or an address
  749: @item n
  750: signed integer
  751: @item u
  752: unsigned integer
  753: @item d
  754: double sized signed integer
  755: @item ud
  756: double sized unsigned integer
  757: @item r
  758: Float (on the FP stack)
  759: @item a_
  760: Cell-aligned address
  761: @item c_
  762: Char-aligned address (note that a Char may have two bytes in Windows NT)
  763: @item f_
  764: Float-aligned address
  765: @item df_
  766: Address aligned for IEEE double precision float
  767: @item sf_
  768: Address aligned for IEEE single precision float
  769: @item xt
  770: Execution token, same size as Cell
  771: @item wid
  772: Wordlist ID, same size as Cell
  773: @item f83name
  774: Pointer to a name structure
  775: @item "
  776: string in the input stream (not the stack). The terminating character is
  777: a blank by default. If it is not a blank, it is shown in @code{<>}
  778: quotes.
  779: 
  780: @end table
  781: 
  782: @node Arithmetic, Stack Manipulation, Notation, Words
  783: @section Arithmetic
  784: Forth arithmetic is not checked, i.e., you will not hear about integer
  785: overflow on addition or multiplication, you may hear about division by
  786: zero if you are lucky. The operator is written after the operands, but
  787: the operands are still in the original order. I.e., the infix @code{2-1}
  788: corresponds to @code{2 1 -}. Forth offers a variety of division
  789: operators. If you perform division with potentially negative operands,
  790: you do not want to use @code{/} or @code{/mod} with its undefined
  791: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
  792: former, @pxref{Mixed precision}).
  793: 
  794: @menu
  795: * Single precision::            
  796: * Bitwise operations::          
  797: * Mixed precision::             operations with single and double-cell integers
  798: * Double precision::            Double-cell integer arithmetic
  799: * Floating Point::              
  800: @end menu
  801: 
  802: @node Single precision, Bitwise operations, Arithmetic, Arithmetic
  803: @subsection Single precision
  804: doc-+
  805: doc--
  806: doc-*
  807: doc-/
  808: doc-mod
  809: doc-/mod
  810: doc-negate
  811: doc-abs
  812: doc-min
  813: doc-max
  814: 
  815: @node Bitwise operations, Mixed precision, Single precision, Arithmetic
  816: @subsection Bitwise operations
  817: doc-and
  818: doc-or
  819: doc-xor
  820: doc-invert
  821: doc-2*
  822: doc-2/
  823: 
  824: @node Mixed precision, Double precision, Bitwise operations, Arithmetic
  825: @subsection Mixed precision
  826: doc-m+
  827: doc-*/
  828: doc-*/mod
  829: doc-m*
  830: doc-um*
  831: doc-m*/
  832: doc-um/mod
  833: doc-fm/mod
  834: doc-sm/rem
  835: 
  836: @node Double precision, Floating Point, Mixed precision, Arithmetic
  837: @subsection Double precision
  838: 
  839: The outer (aka text) interpreter converts numbers containing a dot into
  840: a double precision number. Note that only numbers with the dot as last
  841: character are standard-conforming.
  842: 
  843: doc-d+
  844: doc-d-
  845: doc-dnegate
  846: doc-dabs
  847: doc-dmin
  848: doc-dmax
  849: 
  850: @node Floating Point,  , Double precision, Arithmetic
  851: @subsection Floating Point
  852: 
  853: The format of floating point numbers recognized by the outer (aka text)
  854: interpreter is: a signed decimal number, possibly containing a decimal
  855: point (@code{.}), followed by @code{E} or @code{e}, optionally followed
  856: by a signed integer (the exponent). E.g., @code{1e} ist the same as
  857: @code{+1.0e+0}. Note that a number without @code{e}
  858: is not interpreted as floating-point number, but as double (if the
  859: number contains a @code{.}) or single precision integer. Also,
  860: conversions between string and floating point numbers always use base
  861: 10, irrespective of the value of @code{BASE}. If @code{BASE} contains a
  862: value greater then 14, the @code{E} may be interpreted as digit and the
  863: number will be interpreted as integer, unless it has a signed exponent
  864: (both @code{+} and @code{-} are allowed as signs).
  865: 
  866: Angles in floating point operations are given in radians (a full circle
  867: has 2 pi radians). Note, that Gforth has a separate floating point
  868: stack, but we use the unified notation.
  869: 
  870: Floating point numbers have a number of unpleasant surprises for the
  871: unwary (e.g., floating point addition is not associative) and even a few
  872: for the wary. You should not use them unless you know what you are doing
  873: or you don't care that the results you get are totally bogus. If you
  874: want to learn about the problems of floating point numbers (and how to
  875: avoid them), you might start with @cite{David Goldberg, What Every
  876: Computer Scientist Should Know About Floating-Point Arithmetic, ACM
  877: Computing Surveys 23(1):5@minus{}48, March 1991}.
  878: 
  879: doc-f+
  880: doc-f-
  881: doc-f*
  882: doc-f/
  883: doc-fnegate
  884: doc-fabs
  885: doc-fmax
  886: doc-fmin
  887: doc-floor
  888: doc-fround
  889: doc-f**
  890: doc-fsqrt
  891: doc-fexp
  892: doc-fexpm1
  893: doc-fln
  894: doc-flnp1
  895: doc-flog
  896: doc-falog
  897: doc-fsin
  898: doc-fcos
  899: doc-fsincos
  900: doc-ftan
  901: doc-fasin
  902: doc-facos
  903: doc-fatan
  904: doc-fatan2
  905: doc-fsinh
  906: doc-fcosh
  907: doc-ftanh
  908: doc-fasinh
  909: doc-facosh
  910: doc-fatanh
  911: 
  912: @node Stack Manipulation, Memory access, Arithmetic, Words
  913: @section Stack Manipulation
  914: 
  915: Gforth has a data stack (aka parameter stack) for characters, cells,
  916: addresses, and double cells, a floating point stack for floating point
  917: numbers, a return stack for storing the return addresses of colon
  918: definitions and other data, and a locals stack for storing local
  919: variables. Note that while every sane Forth has a separate floating
  920: point stack, this is not strictly required; an ANS Forth system could
  921: theoretically keep floating point numbers on the data stack. As an
  922: additional difficulty, you don't know how many cells a floating point
  923: number takes. It is reportedly possible to write words in a way that
  924: they work also for a unified stack model, but we do not recommend trying
  925: it. Instead, just say that your program has an environmental dependency
  926: on a separate FP stack.
  927: 
  928: Also, a Forth system is allowed to keep the local variables on the
  929: return stack. This is reasonable, as local variables usually eliminate
  930: the need to use the return stack explicitly. So, if you want to produce
  931: a standard complying program and if you are using local variables in a
  932: word, forget about return stack manipulations in that word (see the
  933: standard document for the exact rules).
  934: 
  935: @menu
  936: * Data stack::                  
  937: * Floating point stack::        
  938: * Return stack::                
  939: * Locals stack::                
  940: * Stack pointer manipulation::  
  941: @end menu
  942: 
  943: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
  944: @subsection Data stack
  945: doc-drop
  946: doc-nip
  947: doc-dup
  948: doc-over
  949: doc-tuck
  950: doc-swap
  951: doc-rot
  952: doc--rot
  953: doc-?dup
  954: doc-pick
  955: doc-roll
  956: doc-2drop
  957: doc-2nip
  958: doc-2dup
  959: doc-2over
  960: doc-2tuck
  961: doc-2swap
  962: doc-2rot
  963: 
  964: @node Floating point stack, Return stack, Data stack, Stack Manipulation
  965: @subsection Floating point stack
  966: doc-fdrop
  967: doc-fnip
  968: doc-fdup
  969: doc-fover
  970: doc-ftuck
  971: doc-fswap
  972: doc-frot
  973: 
  974: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
  975: @subsection Return stack
  976: doc->r
  977: doc-r>
  978: doc-r@
  979: doc-rdrop
  980: doc-2>r
  981: doc-2r>
  982: doc-2r@
  983: doc-2rdrop
  984: 
  985: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
  986: @subsection Locals stack
  987: 
  988: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
  989: @subsection Stack pointer manipulation
  990: doc-sp@
  991: doc-sp!
  992: doc-fp@
  993: doc-fp!
  994: doc-rp@
  995: doc-rp!
  996: doc-lp@
  997: doc-lp!
  998: 
  999: @node Memory access, Control Structures, Stack Manipulation, Words
 1000: @section Memory access
 1001: 
 1002: @menu
 1003: * Stack-Memory transfers::      
 1004: * Address arithmetic::          
 1005: * Memory block access::         
 1006: @end menu
 1007: 
 1008: @node Stack-Memory transfers, Address arithmetic, Memory access, Memory access
 1009: @subsection Stack-Memory transfers
 1010: 
 1011: doc-@
 1012: doc-!
 1013: doc-+!
 1014: doc-c@
 1015: doc-c!
 1016: doc-2@
 1017: doc-2!
 1018: doc-f@
 1019: doc-f!
 1020: doc-sf@
 1021: doc-sf!
 1022: doc-df@
 1023: doc-df!
 1024: 
 1025: @node Address arithmetic, Memory block access, Stack-Memory transfers, Memory access
 1026: @subsection Address arithmetic
 1027: 
 1028: ANS Forth does not specify the sizes of the data types. Instead, it
 1029: offers a number of words for computing sizes and doing address
 1030: arithmetic. Basically, address arithmetic is performed in terms of
 1031: address units (aus); on most systems the address unit is one byte. Note
 1032: that a character may have more than one au, so @code{chars} is no noop
 1033: (on systems where it is a noop, it compiles to nothing).
 1034: 
 1035: ANS Forth also defines words for aligning addresses for specific
 1036: addresses. Many computers require that accesses to specific data types
 1037: must only occur at specific addresses; e.g., that cells may only be
 1038: accessed at addresses divisible by 4. Even if a machine allows unaligned
 1039: accesses, it can usually perform aligned accesses faster. 
 1040: 
 1041: For the performance-conscious: alignment operations are usually only
 1042: necessary during the definition of a data structure, not during the
 1043: (more frequent) accesses to it.
 1044: 
 1045: ANS Forth defines no words for character-aligning addresses. This is not
 1046: an oversight, but reflects the fact that addresses that are not
 1047: char-aligned have no use in the standard and therefore will not be
 1048: created.
 1049: 
 1050: The standard guarantees that addresses returned by @code{CREATE}d words
 1051: are cell-aligned; in addition, Gforth guarantees that these addresses
 1052: are aligned for all purposes.
 1053: 
 1054: Note that the standard defines a word @code{char}, which has nothing to
 1055: do with address arithmetic.
 1056: 
 1057: doc-chars
 1058: doc-char+
 1059: doc-cells
 1060: doc-cell+
 1061: doc-align
 1062: doc-aligned
 1063: doc-floats
 1064: doc-float+
 1065: doc-falign
 1066: doc-faligned
 1067: doc-sfloats
 1068: doc-sfloat+
 1069: doc-sfalign
 1070: doc-sfaligned
 1071: doc-dfloats
 1072: doc-dfloat+
 1073: doc-dfalign
 1074: doc-dfaligned
 1075: doc-maxalign
 1076: doc-maxaligned
 1077: doc-cfalign
 1078: doc-cfaligned
 1079: doc-address-unit-bits
 1080: 
 1081: @node Memory block access,  , Address arithmetic, Memory access
 1082: @subsection Memory block access
 1083: 
 1084: doc-move
 1085: doc-erase
 1086: 
 1087: While the previous words work on address units, the rest works on
 1088: characters.
 1089: 
 1090: doc-cmove
 1091: doc-cmove>
 1092: doc-fill
 1093: doc-blank
 1094: 
 1095: @node Control Structures, Locals, Memory access, Words
 1096: @section Control Structures
 1097: 
 1098: Control structures in Forth cannot be used in interpret state, only in
 1099: compile state, i.e., in a colon definition. We do not like this
 1100: limitation, but have not seen a satisfying way around it yet, although
 1101: many schemes have been proposed.
 1102: 
 1103: @menu
 1104: * Selection::                   
 1105: * Simple Loops::                
 1106: * Counted Loops::               
 1107: * Arbitrary control structures::  
 1108: * Calls and returns::           
 1109: * Exception Handling::          
 1110: @end menu
 1111: 
 1112: @node Selection, Simple Loops, Control Structures, Control Structures
 1113: @subsection Selection
 1114: 
 1115: @example
 1116: @var{flag}
 1117: IF
 1118:   @var{code}
 1119: ENDIF
 1120: @end example
 1121: or
 1122: @example
 1123: @var{flag}
 1124: IF
 1125:   @var{code1}
 1126: ELSE
 1127:   @var{code2}
 1128: ENDIF
 1129: @end example
 1130: 
 1131: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
 1132: standard, and @code{ENDIF} is not, although it is quite popular. We
 1133: recommend using @code{ENDIF}, because it is less confusing for people
 1134: who also know other languages (and is not prone to reinforcing negative
 1135: prejudices against Forth in these people). Adding @code{ENDIF} to a
 1136: system that only supplies @code{THEN} is simple:
 1137: @example
 1138: : endif   POSTPONE then ; immediate
 1139: @end example
 1140: 
 1141: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
 1142: (adv.)}  has the following meanings:
 1143: @quotation
 1144: ... 2b: following next after in order ... 3d: as a necessary consequence
 1145: (if you were there, then you saw them).
 1146: @end quotation
 1147: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
 1148: and many other programming languages has the meaning 3d.]
 1149: 
 1150: Gforth also provides the words @code{?dup-if} and @code{?dup-0=-if}, so
 1151: you can avoid using @code{?dup}. Using these alternatives is also more
 1152: efficient than using @code{?dup}. Definitions in plain standard Forth
 1153: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
 1154: @file{compat/control.fs}.
 1155: 
 1156: @example
 1157: @var{n}
 1158: CASE
 1159:   @var{n1} OF @var{code1} ENDOF
 1160:   @var{n2} OF @var{code2} ENDOF
 1161:   @dots{}
 1162: ENDCASE
 1163: @end example
 1164: 
 1165: Executes the first @var{codei}, where the @var{ni} is equal to
 1166: @var{n}. A default case can be added by simply writing the code after
 1167: the last @code{ENDOF}. It may use @var{n}, which is on top of the stack,
 1168: but must not consume it.
 1169: 
 1170: @node Simple Loops, Counted Loops, Selection, Control Structures
 1171: @subsection Simple Loops
 1172: 
 1173: @example
 1174: BEGIN
 1175:   @var{code1}
 1176:   @var{flag}
 1177: WHILE
 1178:   @var{code2}
 1179: REPEAT
 1180: @end example
 1181: 
 1182: @var{code1} is executed and @var{flag} is computed. If it is true,
 1183: @var{code2} is executed and the loop is restarted; If @var{flag} is false, execution continues after the @code{REPEAT}.
 1184: 
 1185: @example
 1186: BEGIN
 1187:   @var{code}
 1188:   @var{flag}
 1189: UNTIL
 1190: @end example
 1191: 
 1192: @var{code} is executed. The loop is restarted if @code{flag} is false.
 1193: 
 1194: @example
 1195: BEGIN
 1196:   @var{code}
 1197: AGAIN
 1198: @end example
 1199: 
 1200: This is an endless loop.
 1201: 
 1202: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
 1203: @subsection Counted Loops
 1204: 
 1205: The basic counted loop is:
 1206: @example
 1207: @var{limit} @var{start}
 1208: ?DO
 1209:   @var{body}
 1210: LOOP
 1211: @end example
 1212: 
 1213: This performs one iteration for every integer, starting from @var{start}
 1214: and up to, but excluding @var{limit}. The counter, aka index, can be
 1215: accessed with @code{i}. E.g., the loop
 1216: @example
 1217: 10 0 ?DO
 1218:   i .
 1219: LOOP
 1220: @end example
 1221: prints
 1222: @example
 1223: 0 1 2 3 4 5 6 7 8 9
 1224: @end example
 1225: The index of the innermost loop can be accessed with @code{i}, the index
 1226: of the next loop with @code{j}, and the index of the third loop with
 1227: @code{k}.
 1228: 
 1229: The loop control data are kept on the return stack, so there are some
 1230: restrictions on mixing return stack accesses and counted loop
 1231: words. E.g., if you put values on the return stack outside the loop, you
 1232: cannot read them inside the loop. If you put values on the return stack
 1233: within a loop, you have to remove them before the end of the loop and
 1234: before accessing the index of the loop.
 1235: 
 1236: There are several variations on the counted loop:
 1237: 
 1238: @code{LEAVE} leaves the innermost counted loop immediately.
 1239: 
 1240: If @var{start} is greater than @var{limit}, a @code{?DO} loop is entered
 1241: (and @code{LOOP} iterates until they become equal by wrap-around
 1242: arithmetic). This behaviour is usually not what you want. Therefore,
 1243: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
 1244: @code{?DO}), which do not enter the loop if @var{start} is greater than
 1245: @var{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
 1246: unsigned loop parameters.
 1247: 
 1248: @code{LOOP} can be replaced with @code{@var{n} +LOOP}; this updates the
 1249: index by @var{n} instead of by 1. The loop is terminated when the border
 1250: between @var{limit-1} and @var{limit} is crossed. E.g.:
 1251: 
 1252: @code{4 0 +DO  i .  2 +LOOP}   prints @code{0 2}
 1253: 
 1254: @code{4 1 +DO  i .  2 +LOOP}   prints @code{1 3}
 1255: 
 1256: The behaviour of @code{@var{n} +LOOP} is peculiar when @var{n} is negative:
 1257: 
 1258: @code{-1 0 ?DO  i .  -1 +LOOP}  prints @code{0 -1}
 1259: 
 1260: @code{ 0 0 ?DO  i .  -1 +LOOP}  prints nothing
 1261: 
 1262: Therefore we recommend avoiding @code{@var{n} +LOOP} with negative
 1263: @var{n}. One alternative is @code{@var{u} -LOOP}, which reduces the
 1264: index by @var{u} each iteration. The loop is terminated when the border
 1265: between @var{limit+1} and @var{limit} is crossed. Gforth also provides
 1266: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
 1267: 
 1268: @code{-2 0 -DO  i .  1 -LOOP}  prints @code{0 -1}
 1269: 
 1270: @code{-1 0 -DO  i .  1 -LOOP}  prints @code{0}
 1271: 
 1272: @code{ 0 0 -DO  i .  1 -LOOP}  prints nothing
 1273: 
 1274: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
 1275: @code{-LOOP} are not in the ANS Forth standard. However, an
 1276: implementation for these words that uses only standard words is provided
 1277: in @file{compat/loops.fs}.
 1278: 
 1279: @code{?DO} can also be replaced by @code{DO}. @code{DO} always enters
 1280: the loop, independent of the loop parameters. Do not use @code{DO}, even
 1281: if you know that the loop is entered in any case. Such knowledge tends
 1282: to become invalid during maintenance of a program, and then the
 1283: @code{DO} will make trouble.
 1284: 
 1285: @code{UNLOOP} is used to prepare for an abnormal loop exit, e.g., via
 1286: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
 1287: return stack so @code{EXIT} can get to its return address.
 1288: 
 1289: Another counted loop is
 1290: @example
 1291: @var{n}
 1292: FOR
 1293:   @var{body}
 1294: NEXT
 1295: @end example
 1296: This is the preferred loop of native code compiler writers who are too
 1297: lazy to optimize @code{?DO} loops properly. In Gforth, this loop
 1298: iterates @var{n+1} times; @code{i} produces values starting with @var{n}
 1299: and ending with 0. Other Forth systems may behave differently, even if
 1300: they support @code{FOR} loops. To avoid problems, don't use @code{FOR}
 1301: loops.
 1302: 
 1303: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
 1304: @subsection Arbitrary control structures
 1305: 
 1306: ANS Forth permits and supports using control structures in a non-nested
 1307: way. Information about incomplete control structures is stored on the
 1308: control-flow stack. This stack may be implemented on the Forth data
 1309: stack, and this is what we have done in Gforth.
 1310: 
 1311: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
 1312: entry represents a backward branch target. A few words are the basis for
 1313: building any control structure possible (except control structures that
 1314: need storage, like calls, coroutines, and backtracking).
 1315: 
 1316: doc-if
 1317: doc-ahead
 1318: doc-then
 1319: doc-begin
 1320: doc-until
 1321: doc-again
 1322: doc-cs-pick
 1323: doc-cs-roll
 1324: 
 1325: On many systems control-flow stack items take one word, in Gforth they
 1326: currently take three (this may change in the future). Therefore it is a
 1327: really good idea to manipulate the control flow stack with
 1328: @code{cs-pick} and @code{cs-roll}, not with data stack manipulation
 1329: words.
 1330: 
 1331: Some standard control structure words are built from these words:
 1332: 
 1333: doc-else
 1334: doc-while
 1335: doc-repeat
 1336: 
 1337: Gforth adds some more control-structure words:
 1338: 
 1339: doc-endif
 1340: doc-?dup-if
 1341: doc-?dup-0=-if
 1342: 
 1343: Counted loop words constitute a separate group of words:
 1344: 
 1345: doc-?do
 1346: doc-+do
 1347: doc-u+do
 1348: doc--do
 1349: doc-u-do
 1350: doc-do
 1351: doc-for
 1352: doc-loop
 1353: doc-+loop
 1354: doc--loop
 1355: doc-next
 1356: doc-leave
 1357: doc-?leave
 1358: doc-unloop
 1359: doc-done
 1360: 
 1361: The standard does not allow using @code{cs-pick} and @code{cs-roll} on
 1362: @i{do-sys}. Our system allows it, but it's your job to ensure that for
 1363: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
 1364: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
 1365: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
 1366: resolved (by using one of the loop-ending words or @code{DONE}).
 1367: 
 1368: Another group of control structure words are
 1369: 
 1370: doc-case
 1371: doc-endcase
 1372: doc-of
 1373: doc-endof
 1374: 
 1375: @i{case-sys} and @i{of-sys} cannot be processed using @code{cs-pick} and
 1376: @code{cs-roll}.
 1377: 
 1378: @subsubsection Programming Style
 1379: 
 1380: In order to ensure readability we recommend that you do not create
 1381: arbitrary control structures directly, but define new control structure
 1382: words for the control structure you want and use these words in your
 1383: program.
 1384: 
 1385: E.g., instead of writing
 1386: 
 1387: @example
 1388: begin
 1389:   ...
 1390: if [ 1 cs-roll ]
 1391:   ...
 1392: again then
 1393: @end example
 1394: 
 1395: we recommend defining control structure words, e.g.,
 1396: 
 1397: @example
 1398: : while ( dest -- orig dest )
 1399:  POSTPONE if
 1400:  1 cs-roll ; immediate
 1401: 
 1402: : repeat ( orig dest -- )
 1403:  POSTPONE again
 1404:  POSTPONE then ; immediate
 1405: @end example
 1406: 
 1407: and then using these to create the control structure:
 1408: 
 1409: @example
 1410: begin
 1411:   ...
 1412: while
 1413:   ...
 1414: repeat
 1415: @end example
 1416: 
 1417: That's much easier to read, isn't it? Of course, @code{REPEAT} and
 1418: @code{WHILE} are predefined, so in this example it would not be
 1419: necessary to define them.
 1420: 
 1421: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
 1422: @subsection Calls and returns
 1423: 
 1424: A definition can be called simply be writing the name of the
 1425: definition. When the end of the definition is reached, it returns. An
 1426: earlier return can be forced using
 1427: 
 1428: doc-exit
 1429: 
 1430: Don't forget to clean up the return stack and @code{UNLOOP} any
 1431: outstanding @code{?DO}...@code{LOOP}s before @code{EXIT}ing. The
 1432: primitive compiled by @code{EXIT} is
 1433: 
 1434: doc-;s
 1435: 
 1436: @node Exception Handling,  , Calls and returns, Control Structures
 1437: @subsection Exception Handling
 1438: 
 1439: doc-catch
 1440: doc-throw
 1441: 
 1442: @node Locals, Defining Words, Control Structures, Words
 1443: @section Locals
 1444: 
 1445: Local variables can make Forth programming more enjoyable and Forth
 1446: programs easier to read. Unfortunately, the locals of ANS Forth are
 1447: laden with restrictions. Therefore, we provide not only the ANS Forth
 1448: locals wordset, but also our own, more powerful locals wordset (we
 1449: implemented the ANS Forth locals wordset through our locals wordset).
 1450: 
 1451: The ideas in this section have also been published in the paper
 1452: @cite{Automatic Scoping of Local Variables} by M. Anton Ertl, presented
 1453: at EuroForth '94; it is available at
 1454: @*@file{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz}.
 1455: 
 1456: @menu
 1457: * Gforth locals::               
 1458: * ANS Forth locals::            
 1459: @end menu
 1460: 
 1461: @node Gforth locals, ANS Forth locals, Locals, Locals
 1462: @subsection Gforth locals
 1463: 
 1464: Locals can be defined with
 1465: 
 1466: @example
 1467: @{ local1 local2 ... -- comment @}
 1468: @end example
 1469: or
 1470: @example
 1471: @{ local1 local2 ... @}
 1472: @end example
 1473: 
 1474: E.g.,
 1475: @example
 1476: : max @{ n1 n2 -- n3 @}
 1477:  n1 n2 > if
 1478:    n1
 1479:  else
 1480:    n2
 1481:  endif ;
 1482: @end example
 1483: 
 1484: The similarity of locals definitions with stack comments is intended. A
 1485: locals definition often replaces the stack comment of a word. The order
 1486: of the locals corresponds to the order in a stack comment and everything
 1487: after the @code{--} is really a comment.
 1488: 
 1489: This similarity has one disadvantage: It is too easy to confuse locals
 1490: declarations with stack comments, causing bugs and making them hard to
 1491: find. However, this problem can be avoided by appropriate coding
 1492: conventions: Do not use both notations in the same program. If you do,
 1493: they should be distinguished using additional means, e.g. by position.
 1494: 
 1495: The name of the local may be preceded by a type specifier, e.g.,
 1496: @code{F:} for a floating point value:
 1497: 
 1498: @example
 1499: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
 1500: \ complex multiplication
 1501:  Ar Br f* Ai Bi f* f-
 1502:  Ar Bi f* Ai Br f* f+ ;
 1503: @end example
 1504: 
 1505: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
 1506: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
 1507: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
 1508: with @code{W:}, @code{D:} etc.) produces its value and can be changed
 1509: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
 1510: produces its address (which becomes invalid when the variable's scope is
 1511: left). E.g., the standard word @code{emit} can be defined in therms of
 1512: @code{type} like this:
 1513: 
 1514: @example
 1515: : emit @{ C^ char* -- @}
 1516:     char* 1 type ;
 1517: @end example
 1518: 
 1519: A local without type specifier is a @code{W:} local. Both flavours of
 1520: locals are initialized with values from the data or FP stack.
 1521: 
 1522: Currently there is no way to define locals with user-defined data
 1523: structures, but we are working on it.
 1524: 
 1525: Gforth allows defining locals everywhere in a colon definition. This
 1526: poses the following questions:
 1527: 
 1528: @menu
 1529: * Where are locals visible by name?::  
 1530: * How long do locals live?::    
 1531: * Programming Style::           
 1532: * Implementation::              
 1533: @end menu
 1534: 
 1535: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
 1536: @subsubsection Where are locals visible by name?
 1537: 
 1538: Basically, the answer is that locals are visible where you would expect
 1539: it in block-structured languages, and sometimes a little longer. If you
 1540: want to restrict the scope of a local, enclose its definition in
 1541: @code{SCOPE}...@code{ENDSCOPE}.
 1542: 
 1543: doc-scope
 1544: doc-endscope
 1545: 
 1546: These words behave like control structure words, so you can use them
 1547: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
 1548: arbitrary ways.
 1549: 
 1550: If you want a more exact answer to the visibility question, here's the
 1551: basic principle: A local is visible in all places that can only be
 1552: reached through the definition of the local@footnote{In compiler
 1553: construction terminology, all places dominated by the definition of the
 1554: local.}. In other words, it is not visible in places that can be reached
 1555: without going through the definition of the local. E.g., locals defined
 1556: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
 1557: defined in @code{BEGIN}...@code{UNTIL} are visible after the
 1558: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
 1559: 
 1560: The reasoning behind this solution is: We want to have the locals
 1561: visible as long as it is meaningful. The user can always make the
 1562: visibility shorter by using explicit scoping. In a place that can
 1563: only be reached through the definition of a local, the meaning of a
 1564: local name is clear. In other places it is not: How is the local
 1565: initialized at the control flow path that does not contain the
 1566: definition? Which local is meant, if the same name is defined twice in
 1567: two independent control flow paths?
 1568: 
 1569: This should be enough detail for nearly all users, so you can skip the
 1570: rest of this section. If you relly must know all the gory details and
 1571: options, read on.
 1572: 
 1573: In order to implement this rule, the compiler has to know which places
 1574: are unreachable. It knows this automatically after @code{AHEAD},
 1575: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
 1576: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
 1577: compiler that the control flow never reaches that place. If
 1578: @code{UNREACHABLE} is not used where it could, the only consequence is
 1579: that the visibility of some locals is more limited than the rule above
 1580: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
 1581: lie to the compiler), buggy code will be produced.
 1582: 
 1583: Another problem with this rule is that at @code{BEGIN}, the compiler
 1584: does not know which locals will be visible on the incoming
 1585: back-edge. All problems discussed in the following are due to this
 1586: ignorance of the compiler (we discuss the problems using @code{BEGIN}
 1587: loops as examples; the discussion also applies to @code{?DO} and other
 1588: loops). Perhaps the most insidious example is:
 1589: @example
 1590: AHEAD
 1591: BEGIN
 1592:   x
 1593: [ 1 CS-ROLL ] THEN
 1594:   @{ x @}
 1595:   ...
 1596: UNTIL
 1597: @end example
 1598: 
 1599: This should be legal according to the visibility rule. The use of
 1600: @code{x} can only be reached through the definition; but that appears
 1601: textually below the use.
 1602: 
 1603: From this example it is clear that the visibility rules cannot be fully
 1604: implemented without major headaches. Our implementation treats common
 1605: cases as advertised and the exceptions are treated in a safe way: The
 1606: compiler makes a reasonable guess about the locals visible after a
 1607: @code{BEGIN}; if it is too pessimistic, the
 1608: user will get a spurious error about the local not being defined; if the
 1609: compiler is too optimistic, it will notice this later and issue a
 1610: warning. In the case above the compiler would complain about @code{x}
 1611: being undefined at its use. You can see from the obscure examples in
 1612: this section that it takes quite unusual control structures to get the
 1613: compiler into trouble, and even then it will often do fine.
 1614: 
 1615: If the @code{BEGIN} is reachable from above, the most optimistic guess
 1616: is that all locals visible before the @code{BEGIN} will also be
 1617: visible after the @code{BEGIN}. This guess is valid for all loops that
 1618: are entered only through the @code{BEGIN}, in particular, for normal
 1619: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
 1620: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
 1621: compiler. When the branch to the @code{BEGIN} is finally generated by
 1622: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
 1623: warns the user if it was too optimisitic:
 1624: @example
 1625: IF
 1626:   @{ x @}
 1627: BEGIN
 1628:   \ x ? 
 1629: [ 1 cs-roll ] THEN
 1630:   ...
 1631: UNTIL
 1632: @end example
 1633: 
 1634: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
 1635: optimistically assumes that it lives until the @code{THEN}. It notices
 1636: this difference when it compiles the @code{UNTIL} and issues a
 1637: warning. The user can avoid the warning, and make sure that @code{x}
 1638: is not used in the wrong area by using explicit scoping:
 1639: @example
 1640: IF
 1641:   SCOPE
 1642:   @{ x @}
 1643:   ENDSCOPE
 1644: BEGIN
 1645: [ 1 cs-roll ] THEN
 1646:   ...
 1647: UNTIL
 1648: @end example
 1649: 
 1650: Since the guess is optimistic, there will be no spurious error messages
 1651: about undefined locals.
 1652: 
 1653: If the @code{BEGIN} is not reachable from above (e.g., after
 1654: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
 1655: optimistic guess, as the locals visible after the @code{BEGIN} may be
 1656: defined later. Therefore, the compiler assumes that no locals are
 1657: visible after the @code{BEGIN}. However, the user can use
 1658: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
 1659: visible at the BEGIN as at the point where the top control-flow stack
 1660: item was created.
 1661: 
 1662: doc-assume-live
 1663: 
 1664: E.g.,
 1665: @example
 1666: @{ x @}
 1667: AHEAD
 1668: ASSUME-LIVE
 1669: BEGIN
 1670:   x
 1671: [ 1 CS-ROLL ] THEN
 1672:   ...
 1673: UNTIL
 1674: @end example
 1675: 
 1676: Other cases where the locals are defined before the @code{BEGIN} can be
 1677: handled by inserting an appropriate @code{CS-ROLL} before the
 1678: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
 1679: behind the @code{ASSUME-LIVE}).
 1680: 
 1681: Cases where locals are defined after the @code{BEGIN} (but should be
 1682: visible immediately after the @code{BEGIN}) can only be handled by
 1683: rearranging the loop. E.g., the ``most insidious'' example above can be
 1684: arranged into:
 1685: @example
 1686: BEGIN
 1687:   @{ x @}
 1688:   ... 0=
 1689: WHILE
 1690:   x
 1691: REPEAT
 1692: @end example
 1693: 
 1694: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
 1695: @subsubsection How long do locals live?
 1696: 
 1697: The right answer for the lifetime question would be: A local lives at
 1698: least as long as it can be accessed. For a value-flavoured local this
 1699: means: until the end of its visibility. However, a variable-flavoured
 1700: local could be accessed through its address far beyond its visibility
 1701: scope. Ultimately, this would mean that such locals would have to be
 1702: garbage collected. Since this entails un-Forth-like implementation
 1703: complexities, I adopted the same cowardly solution as some other
 1704: languages (e.g., C): The local lives only as long as it is visible;
 1705: afterwards its address is invalid (and programs that access it
 1706: afterwards are erroneous).
 1707: 
 1708: @node Programming Style, Implementation, How long do locals live?, Gforth locals
 1709: @subsubsection Programming Style
 1710: 
 1711: The freedom to define locals anywhere has the potential to change
 1712: programming styles dramatically. In particular, the need to use the
 1713: return stack for intermediate storage vanishes. Moreover, all stack
 1714: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
 1715: determined arguments) can be eliminated: If the stack items are in the
 1716: wrong order, just write a locals definition for all of them; then
 1717: write the items in the order you want.
 1718: 
 1719: This seems a little far-fetched and eliminating stack manipulations is
 1720: unlikely to become a conscious programming objective. Still, the number
 1721: of stack manipulations will be reduced dramatically if local variables
 1722: are used liberally (e.g., compare @code{max} in @ref{Gforth locals} with
 1723: a traditional implementation of @code{max}).
 1724: 
 1725: This shows one potential benefit of locals: making Forth programs more
 1726: readable. Of course, this benefit will only be realized if the
 1727: programmers continue to honour the principle of factoring instead of
 1728: using the added latitude to make the words longer.
 1729: 
 1730: Using @code{TO} can and should be avoided.  Without @code{TO},
 1731: every value-flavoured local has only a single assignment and many
 1732: advantages of functional languages apply to Forth. I.e., programs are
 1733: easier to analyse, to optimize and to read: It is clear from the
 1734: definition what the local stands for, it does not turn into something
 1735: different later.
 1736: 
 1737: E.g., a definition using @code{TO} might look like this:
 1738: @example
 1739: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 1740:  u1 u2 min 0
 1741:  ?do
 1742:    addr1 c@@ addr2 c@@ -
 1743:    ?dup-if
 1744:      unloop exit
 1745:    then
 1746:    addr1 char+ TO addr1
 1747:    addr2 char+ TO addr2
 1748:  loop
 1749:  u1 u2 - ;
 1750: @end example
 1751: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
 1752: every loop iteration. @code{strcmp} is a typical example of the
 1753: readability problems of using @code{TO}. When you start reading
 1754: @code{strcmp}, you think that @code{addr1} refers to the start of the
 1755: string. Only near the end of the loop you realize that it is something
 1756: else.
 1757: 
 1758: This can be avoided by defining two locals at the start of the loop that
 1759: are initialized with the right value for the current iteration.
 1760: @example
 1761: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 1762:  addr1 addr2
 1763:  u1 u2 min 0 
 1764:  ?do @{ s1 s2 @}
 1765:    s1 c@@ s2 c@@ -
 1766:    ?dup-if
 1767:      unloop exit
 1768:    then
 1769:    s1 char+ s2 char+
 1770:  loop
 1771:  2drop
 1772:  u1 u2 - ;
 1773: @end example
 1774: Here it is clear from the start that @code{s1} has a different value
 1775: in every loop iteration.
 1776: 
 1777: @node Implementation,  , Programming Style, Gforth locals
 1778: @subsubsection Implementation
 1779: 
 1780: Gforth uses an extra locals stack. The most compelling reason for
 1781: this is that the return stack is not float-aligned; using an extra stack
 1782: also eliminates the problems and restrictions of using the return stack
 1783: as locals stack. Like the other stacks, the locals stack grows toward
 1784: lower addresses. A few primitives allow an efficient implementation:
 1785: 
 1786: doc-@local#
 1787: doc-f@local#
 1788: doc-laddr#
 1789: doc-lp+!#
 1790: doc-lp!
 1791: doc->l
 1792: doc-f>l
 1793: 
 1794: In addition to these primitives, some specializations of these
 1795: primitives for commonly occurring inline arguments are provided for
 1796: efficiency reasons, e.g., @code{@@local0} as specialization of
 1797: @code{@@local#} for the inline argument 0. The following compiling words
 1798: compile the right specialized version, or the general version, as
 1799: appropriate:
 1800: 
 1801: doc-compile-@local
 1802: doc-compile-f@local
 1803: doc-compile-lp+!
 1804: 
 1805: Combinations of conditional branches and @code{lp+!#} like
 1806: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
 1807: is taken) are provided for efficiency and correctness in loops.
 1808: 
 1809: A special area in the dictionary space is reserved for keeping the
 1810: local variable names. @code{@{} switches the dictionary pointer to this
 1811: area and @code{@}} switches it back and generates the locals
 1812: initializing code. @code{W:} etc.@ are normal defining words. This
 1813: special area is cleared at the start of every colon definition.
 1814: 
 1815: A special feature of Gforth's dictionary is used to implement the
 1816: definition of locals without type specifiers: every wordlist (aka
 1817: vocabulary) has its own methods for searching
 1818: etc. (@pxref{Wordlists}). For the present purpose we defined a wordlist
 1819: with a special search method: When it is searched for a word, it
 1820: actually creates that word using @code{W:}. @code{@{} changes the search
 1821: order to first search the wordlist containing @code{@}}, @code{W:} etc.,
 1822: and then the wordlist for defining locals without type specifiers.
 1823: 
 1824: The lifetime rules support a stack discipline within a colon
 1825: definition: The lifetime of a local is either nested with other locals
 1826: lifetimes or it does not overlap them.
 1827: 
 1828: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
 1829: pointer manipulation is generated. Between control structure words
 1830: locals definitions can push locals onto the locals stack. @code{AGAIN}
 1831: is the simplest of the other three control flow words. It has to
 1832: restore the locals stack depth of the corresponding @code{BEGIN}
 1833: before branching. The code looks like this:
 1834: @format
 1835: @code{lp+!#} current-locals-size @minus{} dest-locals-size
 1836: @code{branch} <begin>
 1837: @end format
 1838: 
 1839: @code{UNTIL} is a little more complicated: If it branches back, it
 1840: must adjust the stack just like @code{AGAIN}. But if it falls through,
 1841: the locals stack must not be changed. The compiler generates the
 1842: following code:
 1843: @format
 1844: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
 1845: @end format
 1846: The locals stack pointer is only adjusted if the branch is taken.
 1847: 
 1848: @code{THEN} can produce somewhat inefficient code:
 1849: @format
 1850: @code{lp+!#} current-locals-size @minus{} orig-locals-size
 1851: <orig target>:
 1852: @code{lp+!#} orig-locals-size @minus{} new-locals-size
 1853: @end format
 1854: The second @code{lp+!#} adjusts the locals stack pointer from the
 1855: level at the @var{orig} point to the level after the @code{THEN}. The
 1856: first @code{lp+!#} adjusts the locals stack pointer from the current
 1857: level to the level at the orig point, so the complete effect is an
 1858: adjustment from the current level to the right level after the
 1859: @code{THEN}.
 1860: 
 1861: In a conventional Forth implementation a dest control-flow stack entry
 1862: is just the target address and an orig entry is just the address to be
 1863: patched. Our locals implementation adds a wordlist to every orig or dest
 1864: item. It is the list of locals visible (or assumed visible) at the point
 1865: described by the entry. Our implementation also adds a tag to identify
 1866: the kind of entry, in particular to differentiate between live and dead
 1867: (reachable and unreachable) orig entries.
 1868: 
 1869: A few unusual operations have to be performed on locals wordlists:
 1870: 
 1871: doc-common-list
 1872: doc-sub-list?
 1873: doc-list-size
 1874: 
 1875: Several features of our locals wordlist implementation make these
 1876: operations easy to implement: The locals wordlists are organised as
 1877: linked lists; the tails of these lists are shared, if the lists
 1878: contain some of the same locals; and the address of a name is greater
 1879: than the address of the names behind it in the list.
 1880: 
 1881: Another important implementation detail is the variable
 1882: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
 1883: determine if they can be reached directly or only through the branch
 1884: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
 1885: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
 1886: definition, by @code{BEGIN} and usually by @code{THEN}.
 1887: 
 1888: Counted loops are similar to other loops in most respects, but
 1889: @code{LEAVE} requires special attention: It performs basically the same
 1890: service as @code{AHEAD}, but it does not create a control-flow stack
 1891: entry. Therefore the information has to be stored elsewhere;
 1892: traditionally, the information was stored in the target fields of the
 1893: branches created by the @code{LEAVE}s, by organizing these fields into a
 1894: linked list. Unfortunately, this clever trick does not provide enough
 1895: space for storing our extended control flow information. Therefore, we
 1896: introduce another stack, the leave stack. It contains the control-flow
 1897: stack entries for all unresolved @code{LEAVE}s.
 1898: 
 1899: Local names are kept until the end of the colon definition, even if
 1900: they are no longer visible in any control-flow path. In a few cases
 1901: this may lead to increased space needs for the locals name area, but
 1902: usually less than reclaiming this space would cost in code size.
 1903: 
 1904: 
 1905: @node ANS Forth locals,  , Gforth locals, Locals
 1906: @subsection ANS Forth locals
 1907: 
 1908: The ANS Forth locals wordset does not define a syntax for locals, but
 1909: words that make it possible to define various syntaxes. One of the
 1910: possible syntaxes is a subset of the syntax we used in the Gforth locals
 1911: wordset, i.e.:
 1912: 
 1913: @example
 1914: @{ local1 local2 ... -- comment @}
 1915: @end example
 1916: or
 1917: @example
 1918: @{ local1 local2 ... @}
 1919: @end example
 1920: 
 1921: The order of the locals corresponds to the order in a stack comment. The
 1922: restrictions are:
 1923: 
 1924: @itemize @bullet
 1925: @item
 1926: Locals can only be cell-sized values (no type specifiers are allowed).
 1927: @item
 1928: Locals can be defined only outside control structures.
 1929: @item
 1930: Locals can interfere with explicit usage of the return stack. For the
 1931: exact (and long) rules, see the standard. If you don't use return stack
 1932: accessing words in a definition using locals, you will be all right. The
 1933: purpose of this rule is to make locals implementation on the return
 1934: stack easier.
 1935: @item
 1936: The whole definition must be in one line.
 1937: @end itemize
 1938: 
 1939: Locals defined in this way behave like @code{VALUE}s (@xref{Simple
 1940: Defining Words}). I.e., they are initialized from the stack. Using their
 1941: name produces their value. Their value can be changed using @code{TO}.
 1942: 
 1943: Since this syntax is supported by Gforth directly, you need not do
 1944: anything to use it. If you want to port a program using this syntax to
 1945: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
 1946: syntax on the other system.
 1947: 
 1948: Note that a syntax shown in the standard, section A.13 looks
 1949: similar, but is quite different in having the order of locals
 1950: reversed. Beware!
 1951: 
 1952: The ANS Forth locals wordset itself consists of the following word
 1953: 
 1954: doc-(local)
 1955: 
 1956: The ANS Forth locals extension wordset defines a syntax, but it is so
 1957: awful that we strongly recommend not to use it. We have implemented this
 1958: syntax to make porting to Gforth easy, but do not document it here. The
 1959: problem with this syntax is that the locals are defined in an order
 1960: reversed with respect to the standard stack comment notation, making
 1961: programs harder to read, and easier to misread and miswrite. The only
 1962: merit of this syntax is that it is easy to implement using the ANS Forth
 1963: locals wordset.
 1964: 
 1965: @node Defining Words, Wordlists, Locals, Words
 1966: @section Defining Words
 1967: 
 1968: @menu
 1969: * Simple Defining Words::       
 1970: * Colon Definitions::           
 1971: * User-defined Defining Words::  
 1972: * Supplying names::             
 1973: * Interpretation and Compilation Semantics::  
 1974: @end menu
 1975: 
 1976: @node Simple Defining Words, Colon Definitions, Defining Words, Defining Words
 1977: @subsection Simple Defining Words
 1978: 
 1979: doc-constant
 1980: doc-2constant
 1981: doc-fconstant
 1982: doc-variable
 1983: doc-2variable
 1984: doc-fvariable
 1985: doc-create
 1986: doc-user
 1987: doc-value
 1988: doc-to
 1989: doc-defer
 1990: doc-is
 1991: 
 1992: @node Colon Definitions, User-defined Defining Words, Simple Defining Words, Defining Words
 1993: @subsection Colon Definitions
 1994: 
 1995: @example
 1996: : name ( ... -- ... )
 1997:     word1 word2 word3 ;
 1998: @end example
 1999: 
 2000: creates a word called @code{name}, that, upon execution, executes
 2001: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
 2002: 
 2003: The explanation above is somewhat superficial. @xref{Interpretation and
 2004: Compilation Semantics} for an in-depth discussion of some of the issues
 2005: involved.
 2006: 
 2007: doc-:
 2008: doc-;
 2009: 
 2010: @node User-defined Defining Words, Supplying names, Colon Definitions, Defining Words
 2011: @subsection User-defined Defining Words
 2012: 
 2013: You can create new defining words simply by wrapping defining-time code
 2014: around existing defining words and putting the sequence in a colon
 2015: definition.
 2016: 
 2017: If you want the words defined with your defining words to behave
 2018: differently from words defined with standard defining words, you can
 2019: write your defining word like this:
 2020: 
 2021: @example
 2022: : def-word ( "name" -- )
 2023:     Create @var{code1}
 2024: DOES> ( ... -- ... )
 2025:     @var{code2} ;
 2026: 
 2027: def-word name
 2028: @end example
 2029: 
 2030: Technically, this fragment defines a defining word @code{def-word}, and
 2031: a word @code{name}; when you execute @code{name}, the address of the
 2032: body of @code{name} is put on the data stack and @var{code2} is executed
 2033: (the address of the body of @code{name} is the address @code{HERE}
 2034: returns immediately after the @code{CREATE}).
 2035: 
 2036: In other words, if you make the following definitions:
 2037: 
 2038: @example
 2039: : def-word1 ( "name" -- )
 2040:     Create @var{code1} ;
 2041: 
 2042: : action1 ( ... -- ... )
 2043:     @var{code2} ;
 2044: 
 2045: def-word name1
 2046: @end example
 2047: 
 2048: Using @code{name1 action1} is equivalent to using @code{name}.
 2049: 
 2050: E.g., you can implement @code{Constant} in this way:
 2051: 
 2052: @example
 2053: : constant ( w "name" -- )
 2054:     create ,
 2055: DOES> ( -- w )
 2056:     @@ ;
 2057: @end example
 2058: 
 2059: When you create a constant with @code{5 constant five}, first a new word
 2060: @code{five} is created, then the value 5 is laid down in the body of
 2061: @code{five} with @code{,}. When @code{five} is invoked, the address of
 2062: the body is put on the stack, and @code{@@} retrieves the value 5.
 2063: 
 2064: In the example above the stack comment after the @code{DOES>} specifies
 2065: the stack effect of the defined words, not the stack effect of the
 2066: following code (the following code expects the address of the body on
 2067: the top of stack, which is not reflected in the stack comment). This is
 2068: the convention that I use and recommend (it clashes a bit with using
 2069: locals declarations for stack effect specification, though).
 2070: 
 2071: @subsubsection Applications of @code{CREATE..DOES>}
 2072: 
 2073: You may wonder how to use this feature. Here are some usage patterns:
 2074: 
 2075: When you see a sequence of code occurring several times, and you can
 2076: identify a meaning, you will factor it out as a colon definition. When
 2077: you see similar colon definitions, you can factor them using
 2078: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
 2079: that look very similar:
 2080: @example
 2081: : ori, ( reg-taget reg-source n -- )
 2082:     0 asm-reg-reg-imm ;
 2083: : andi, ( reg-taget reg-source n -- )
 2084:     1 asm-reg-reg-imm ;
 2085: @end example
 2086: 
 2087: This could be factored with:
 2088: @example
 2089: : reg-reg-imm ( op-code -- )
 2090:     create ,
 2091: DOES> ( reg-taget reg-source n -- )
 2092:     @@ asm-reg-reg-imm ;
 2093: 
 2094: 0 reg-reg-imm ori,
 2095: 1 reg-reg-imm andi,
 2096: @end example
 2097: 
 2098: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
 2099: supply a part of the parameters for a word (known as @dfn{currying} in
 2100: the functional language community). E.g., @code{+} needs two
 2101: parameters. Creating versions of @code{+} with one parameter fixed can
 2102: be done like this:
 2103: @example
 2104: : curry+ ( n1 -- )
 2105:     create ,
 2106: DOES> ( n2 -- n1+n2 )
 2107:     @@ + ;
 2108: 
 2109:  3 curry+ 3+
 2110: -2 curry+ 2-
 2111: @end example
 2112: 
 2113: @subsubsection The gory details of @code{CREATE..DOES>}
 2114: 
 2115: doc-does>
 2116: 
 2117: This means that you need not use @code{CREATE} and @code{DOES>} in the
 2118: same definition; E.g., you can put the @code{DOES>}-part in a separate
 2119: definition. This allows us to, e.g., select among different DOES>-parts:
 2120: @example
 2121: : does1 
 2122: DOES> ( ... -- ... )
 2123:     ... ;
 2124: 
 2125: : does2
 2126: DOES> ( ... -- ... )
 2127:     ... ;
 2128: 
 2129: : def-word ( ... -- ... )
 2130:     create ...
 2131:     IF
 2132:        does1
 2133:     ELSE
 2134:        does2
 2135:     ENDIF ;
 2136: @end example
 2137: 
 2138: In a standard program you can apply a @code{DOES>}-part only if the last
 2139: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
 2140: will override the behaviour of the last word defined in any case. In a
 2141: standard program, you can use @code{DOES>} only in a colon
 2142: definition. In Gforth, you can also use it in interpretation state, in a
 2143: kind of one-shot mode:
 2144: @example
 2145: CREATE name ( ... -- ... )
 2146:   @var{initialization}
 2147: DOES>
 2148:   @var{code} ;
 2149: @end example
 2150: This is equivalwent to the standard
 2151: @example
 2152: :noname
 2153: DOES>
 2154:     @var{code} ;
 2155: CREATE name EXECUTE ( ... -- ... )
 2156:     @var{initialization}
 2157: @end example
 2158: 
 2159: You can get the address of the body of a word with
 2160: 
 2161: doc->body
 2162: 
 2163: @node Supplying names, Interpretation and Compilation Semantics, User-defined Defining Words, Defining Words
 2164: @subsection Supplying names for the defined words
 2165: 
 2166: By default, defining words take the names for the defined words from the
 2167: input stream. Sometimes you want to supply the name from a string. You
 2168: can do this with
 2169: 
 2170: doc-nextname
 2171: 
 2172: E.g.,
 2173: 
 2174: @example
 2175: s" foo" nextname create
 2176: @end example
 2177: is equivalent to
 2178: @example
 2179: create foo
 2180: @end example
 2181: 
 2182: Sometimes you want to define a word without a name. You can do this with
 2183: 
 2184: doc-noname
 2185: 
 2186: To make any use of the newly defined word, you need its execution
 2187: token. You can get it with
 2188: 
 2189: doc-lastxt
 2190: 
 2191: E.g., you can initialize a deferred word with an anonymous colon
 2192: definition:
 2193: @example
 2194: Defer deferred
 2195: noname : ( ... -- ... )
 2196:   ... ;
 2197: lastxt IS deferred
 2198: @end example
 2199: 
 2200: @code{lastxt} also works when the last word was not defined as
 2201: @code{noname}. 
 2202: 
 2203: The standard has also recognized the need for anonymous words and
 2204: provides
 2205: 
 2206: doc-:noname
 2207: 
 2208: This leaves the execution token for the word on the stack after the
 2209: closing @code{;}. You can rewrite the last example with @code{:noname}:
 2210: @example
 2211: Defer deferred
 2212: :noname ( ... -- ... )
 2213:   ... ;
 2214: IS deferred
 2215: @end example
 2216: 
 2217: @node Interpretation and Compilation Semantics,  , Supplying names, Defining Words
 2218: @subsection Interpretation and Compilation Semantics
 2219: 
 2220: The @dfn{interpretation semantics} of a word are what the text
 2221: interpreter does when it encounters the word in interpret state. It also
 2222: appears in some other contexts, e.g., the execution token returned by
 2223: @code{' @var{word}} identifies the interpretation semantics of
 2224: @var{word} (in other words, @code{' @var{word} execute} is equivalent to
 2225: interpret-state text interpretation of @code{@var{word}}).
 2226: 
 2227: The @dfn{compilation semantics} of a word are what the text interpreter
 2228: does when it encounters the word in compile state. It also appears in
 2229: other contexts, e.g, @code{POSTPONE @var{word}} compiles@footnote{In
 2230: standard terminology, ``appends to the current definition''.} the
 2231: compilation semantics of @var{word}.
 2232: 
 2233: The standard also talks about @dfn{execution semantics}. They are used
 2234: only for defining the interpretation and compilation semantics of many
 2235: words. By default, the interpretation semantics of a word are to
 2236: @code{execute} its execution semantics, and the compilation semantics of
 2237: a word are to @code{compile,} its execution semantics.@footnote{In
 2238: standard terminology: The default interpretation semantics are its
 2239: execution semantics; the default compilation semantics are to append its
 2240: execution semantics to the execution semantics of the current
 2241: definition.}
 2242: 
 2243: You can change the compilation semantics into @code{execute}ing the
 2244: execution semantics with
 2245: 
 2246: doc-immediate
 2247: 
 2248: You can remove the interpretation semantics of a word with
 2249: 
 2250: doc-compile-only
 2251: doc-restrict
 2252: 
 2253: Note that ticking (@code{'}) compile-only words gives an error
 2254: (``Interpreting a compile-only word'').
 2255: 
 2256: Gforth also allows you to define words with arbitrary combinations of
 2257: interpretation and compilation semantics.
 2258: 
 2259: doc-interpret/compile:
 2260: 
 2261: This feature was introduced for implementing @code{TO} and @code{S"}. I
 2262: recommend that you do not define such words, as cute as they may be:
 2263: they make it hard to get at both parts of the word in some contexts.
 2264: E.g., assume you want to get an execution token for the compilation
 2265: part. Instead, define two words, one that embodies the interpretation
 2266: part, and one that embodies the compilation part.
 2267: 
 2268: There is, however, a potentially useful application of this feature:
 2269: Providing differing implementations for the default semantics. While
 2270: this introduces redundancy and is therefore usually a bad idea, a
 2271: performance improvement may be worth the trouble. E.g., consider the
 2272: word @code{foobar}:
 2273: 
 2274: @example
 2275: : foobar
 2276:     foo bar ;
 2277: @end example
 2278: 
 2279: Let us assume that @code{foobar} is called so frequently that the
 2280: calling overhead would take a significant amount of the run-time. We can
 2281: optimize it with @code{interpret/compile:}:
 2282: 
 2283: @example
 2284: :noname
 2285:    foo bar ;
 2286: :noname
 2287:    POSTPONE foo POSTPONE bar ;
 2288: interpret/compile: foobar
 2289: @end example
 2290: 
 2291: This definition has the same interpretation semantics and essentially
 2292: the same compilation semantics as the simple definition of
 2293: @code{foobar}, but the implementation of the compilation semantics is
 2294: more efficient with respect to run-time.
 2295: 
 2296: Some people try to use state-smart words to emulate the feature provided
 2297: by @code{interpret/compile:} (words are state-smart if they check
 2298: @code{STATE} during execution). E.g., they would try to code
 2299: @code{foobar} like this:
 2300: 
 2301: @example
 2302: : foobar
 2303:   STATE @@
 2304:   IF ( compilation state )
 2305:     POSTPONE foo POSTPONE bar
 2306:   ELSE
 2307:     foo bar
 2308:   ENDIF ; immediate
 2309: @end example
 2310: 
 2311: While this works if @code{foobar} is processed only by the text
 2312: interpreter, it does not work in other contexts (like @code{'} or
 2313: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
 2314: for a state-smart word, not for the interpretation semantics of the
 2315: original @code{foobar}; when you execute this execution token (directly
 2316: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
 2317: state, the result will not be what you expected (i.e., it will not
 2318: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
 2319: write them!
 2320: 
 2321: It is also possible to write defining words that define words with
 2322: arbitrary combinations of interpretation and compilation semantics (or,
 2323: preferably, arbitrary combinations of implementations of the default
 2324: semantics). In general, this looks like:
 2325: 
 2326: @example
 2327: : def-word
 2328:     create-interpret/compile
 2329:     @var{code1}
 2330: interpretation>
 2331:     @var{code2}
 2332: <interpretation
 2333: compilation>
 2334:     @var{code3}
 2335: <compilation ;
 2336: @end example
 2337: 
 2338: For a @var{word} defined with @code{def-word}, the interpretation
 2339: semantics are to push the address of the body of @var{word} and perform
 2340: @var{code2}, and the compilation semantics are to push the address of
 2341: the body of @var{word} and perform @var{code3}. E.g., @code{constant}
 2342: can also be defined like this:
 2343: 
 2344: @example
 2345: : constant ( n "name" -- )
 2346:     create-interpret/compile
 2347:     ,
 2348: interpretation> ( -- n )
 2349:     @@
 2350: <interpretation
 2351: compilation> ( compilation. -- ; run-time. -- n )
 2352:     @@ postpone literal
 2353: <compilation ;
 2354: @end example
 2355: 
 2356: doc-create-interpret/compile
 2357: doc-interpretation>
 2358: doc-<interpretation
 2359: doc-compilation>
 2360: doc-<compilation
 2361: 
 2362: Note that words defined with @code{interpret/compile:} and
 2363: @code{create-interpret/compile} have an extended header structure that
 2364: differs from other words; however, unless you try to access them with
 2365: plain address arithmetic, you should not notice this. Words for
 2366: accessing the header structure usually know how to deal with this; e.g.,
 2367: @code{' word >body} also gives you the body of a word created with
 2368: @code{create-interpret/compile}.
 2369: 
 2370: @node Wordlists, Files, Defining Words, Words
 2371: @section Wordlists
 2372: 
 2373: @node Files, Blocks, Wordlists, Words
 2374: @section Files
 2375: 
 2376: @node Blocks, Other I/O, Files, Words
 2377: @section Blocks
 2378: 
 2379: @node Other I/O, Programming Tools, Blocks, Words
 2380: @section Other I/O
 2381: 
 2382: @node Programming Tools, Assembler and Code words, Other I/O, Words
 2383: @section Programming Tools
 2384: 
 2385: @menu
 2386: * Debugging::                   Simple and quick.
 2387: * Assertions::                  Making your programs self-checking.
 2388: @end menu
 2389: 
 2390: @node Debugging, Assertions, Programming Tools, Programming Tools
 2391: @subsection Debugging
 2392: 
 2393: The simple debugging aids provided in @file{debugging.fs}
 2394: are meant to support a different style of debugging than the
 2395: tracing/stepping debuggers used in languages with long turn-around
 2396: times.
 2397: 
 2398: A much better (faster) way in fast-compilig languages is to add
 2399: printing code at well-selected places, let the program run, look at
 2400: the output, see where things went wrong, add more printing code, etc.,
 2401: until the bug is found.
 2402: 
 2403: The word @code{~~} is easy to insert. It just prints debugging
 2404: information (by default the source location and the stack contents). It
 2405: is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
 2406: query-replace them with nothing). The deferred words
 2407: @code{printdebugdata} and @code{printdebugline} control the output of
 2408: @code{~~}. The default source location output format works well with
 2409: Emacs' compilation mode, so you can step through the program at the
 2410: source level using @kbd{C-x `} (the advantage over a stepping debugger
 2411: is that you can step in any direction and you know where the crash has
 2412: happened or where the strange data has occurred).
 2413: 
 2414: Note that the default actions clobber the contents of the pictured
 2415: numeric output string, so you should not use @code{~~}, e.g., between
 2416: @code{<#} and @code{#>}.
 2417: 
 2418: doc-~~
 2419: doc-printdebugdata
 2420: doc-printdebugline
 2421: 
 2422: @node Assertions,  , Debugging, Programming Tools
 2423: @subsection Assertions
 2424: 
 2425: It is a good idea to make your programs self-checking, in particular, if
 2426: you use an assumption (e.g., that a certain field of a data structure is
 2427: never zero) that may become wrong during maintenance. Gforth supports
 2428: assertions for this purpose. They are used like this:
 2429: 
 2430: @example
 2431: assert( @var{flag} )
 2432: @end example
 2433: 
 2434: The code between @code{assert(} and @code{)} should compute a flag, that
 2435: should be true if everything is alright and false otherwise. It should
 2436: not change anything else on the stack. The overall stack effect of the
 2437: assertion is @code{( -- )}. E.g.
 2438: 
 2439: @example
 2440: assert( 1 1 + 2 = ) \ what we learn in school
 2441: assert( dup 0<> ) \ assert that the top of stack is not zero
 2442: assert( false ) \ this code should not be reached
 2443: @end example
 2444: 
 2445: The need for assertions is different at different times. During
 2446: debugging, we want more checking, in production we sometimes care more
 2447: for speed. Therefore, assertions can be turned off, i.e., the assertion
 2448: becomes a comment. Depending on the importance of an assertion and the
 2449: time it takes to check it, you may want to turn off some assertions and
 2450: keep others turned on. Gforth provides several levels of assertions for
 2451: this purpose:
 2452: 
 2453: doc-assert0(
 2454: doc-assert1(
 2455: doc-assert2(
 2456: doc-assert3(
 2457: doc-assert(
 2458: doc-)
 2459: 
 2460: @code{Assert(} is the same as @code{assert1(}. The variable
 2461: @code{assert-level} specifies the highest assertions that are turned
 2462: on. I.e., at the default @code{assert-level} of one, @code{assert0(} and
 2463: @code{assert1(} assertions perform checking, while @code{assert2(} and
 2464: @code{assert3(} assertions are treated as comments.
 2465: 
 2466: Note that the @code{assert-level} is evaluated at compile-time, not at
 2467: run-time. I.e., you cannot turn assertions on or off at run-time, you
 2468: have to set the @code{assert-level} appropriately before compiling a
 2469: piece of code. You can compile several pieces of code at several
 2470: @code{assert-level}s (e.g., a trusted library at level 1 and newly
 2471: written code at level 3).
 2472: 
 2473: doc-assert-level
 2474: 
 2475: If an assertion fails, a message compatible with Emacs' compilation mode
 2476: is produced and the execution is aborted (currently with @code{ABORT"}.
 2477: If there is interest, we will introduce a special throw code. But if you
 2478: intend to @code{catch} a specific condition, using @code{throw} is
 2479: probably more appropriate than an assertion).
 2480: 
 2481: @node Assembler and Code words, Threading Words, Programming Tools, Words
 2482: @section Assembler and Code words
 2483: 
 2484: Gforth provides some words for defining primitives (words written in
 2485: machine code), and for defining the the machine-code equivalent of
 2486: @code{DOES>}-based defining words. However, the machine-independent
 2487: nature of Gforth poses a few problems: First of all. Gforth runs on
 2488: several architectures, so it can provide no standard assembler. What's
 2489: worse is that the register allocation not only depends on the processor,
 2490: but also on the @code{gcc} version and options used.
 2491: 
 2492: The words that Gforth offers encapsulate some system dependences (e.g., the
 2493: header structure), so a system-independent assembler may be used in
 2494: Gforth. If you do not have an assembler, you can compile machine code
 2495: directly with @code{,} and @code{c,}.
 2496: 
 2497: doc-assembler
 2498: doc-code
 2499: doc-end-code
 2500: doc-;code
 2501: doc-flush-icache
 2502: 
 2503: If @code{flush-icache} does not work correctly, @code{code} words
 2504: etc. will not work (reliably), either.
 2505: 
 2506: These words are rarely used. Therefore they reside in @code{code.fs},
 2507: which is usually not loaded (except @code{flush-icache}, which is always
 2508: present). You can load them with @code{require code.fs}.
 2509: 
 2510: In the assembly code you will want to refer to the inner interpreter's
 2511: registers (e.g., the data stack pointer) and you may want to use other
 2512: registers for temporary storage. Unfortunately, the register allocation
 2513: is installation-dependent.
 2514: 
 2515: The easiest solution is to use explicit register declarations
 2516: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
 2517: GNU C Manual}) for all of the inner interpreter's registers: You have to
 2518: compile Gforth with @code{-DFORCE_REG} (configure option
 2519: @code{--enable-force-reg}) and the appropriate declarations must be
 2520: present in the @code{machine.h} file (see @code{mips.h} for an example;
 2521: you can find a full list of all declarable register symbols with
 2522: @code{grep register engine.c}). If you give explicit registers to all
 2523: variables that are declared at the beginning of @code{engine()}, you
 2524: should be able to use the other caller-saved registers for temporary
 2525: storage. Alternatively, you can use the @code{gcc} option
 2526: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
 2527: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
 2528: (however, this restriction on register allocation may slow Gforth
 2529: significantly).
 2530: 
 2531: If this solution is not viable (e.g., because @code{gcc} does not allow
 2532: you to explicitly declare all the registers you need), you have to find
 2533: out by looking at the code where the inner interpreter's registers
 2534: reside and which registers can be used for temporary storage. You can
 2535: get an assembly listing of the engine's code with @code{make engine.s}.
 2536: 
 2537: In any case, it is good practice to abstract your assembly code from the
 2538: actual register allocation. E.g., if the data stack pointer resides in
 2539: register @code{$17}, create an alias for this register called @code{sp},
 2540: and use that in your assembly code.
 2541: 
 2542: Another option for implementing normal and defining words efficiently
 2543: is: adding the wanted functionality to the source of Gforth. For normal
 2544: words you just have to edit @file{primitives} (@pxref{Automatic
 2545: Generation}), defining words (equivalent to @code{;CODE} words, for fast
 2546: defined words) may require changes in @file{engine.c}, @file{kernal.fs},
 2547: @file{prims2x.fs}, and possibly @file{cross.fs}.
 2548: 
 2549: 
 2550: @node Threading Words,  , Assembler and Code words, Words
 2551: @section Threading Words
 2552: 
 2553: These words provide access to code addresses and other threading stuff
 2554: in Gforth (and, possibly, other interpretive Forths). It more or less
 2555: abstracts away the differences between direct and indirect threading
 2556: (and, for direct threading, the machine dependences). However, at
 2557: present this wordset is still inclomplete. It is also pretty low-level;
 2558: some day it will hopefully be made unnecessary by an internals words set
 2559: that abstracts implementation details away completely.
 2560: 
 2561: doc->code-address
 2562: doc->does-code
 2563: doc-code-address!
 2564: doc-does-code!
 2565: doc-does-handler!
 2566: doc-/does-handler
 2567: 
 2568: The code addresses produced by various defining words are produced by
 2569: the following words:
 2570: 
 2571: doc-docol:
 2572: doc-docon:
 2573: doc-dovar:
 2574: doc-douser:
 2575: doc-dodefer:
 2576: doc-dofield:
 2577: 
 2578: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
 2579: with @code{>DOES-CODE}. If the word was defined in that way, the value
 2580: returned is different from 0 and identifies the @code{DOES>} used by the
 2581: defining word.
 2582: 
 2583: @node ANS conformance, Model, Words, Top
 2584: @chapter ANS conformance
 2585: 
 2586: To the best of our knowledge, Gforth is an
 2587: 
 2588: ANS Forth System
 2589: @itemize @bullet
 2590: @item providing the Core Extensions word set
 2591: @item providing the Block word set
 2592: @item providing the Block Extensions word set
 2593: @item providing the Double-Number word set
 2594: @item providing the Double-Number Extensions word set
 2595: @item providing the Exception word set
 2596: @item providing the Exception Extensions word set
 2597: @item providing the Facility word set
 2598: @item providing @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
 2599: @item providing the File Access word set
 2600: @item providing the File Access Extensions word set
 2601: @item providing the Floating-Point word set
 2602: @item providing the Floating-Point Extensions word set
 2603: @item providing the Locals word set
 2604: @item providing the Locals Extensions word set
 2605: @item providing the Memory-Allocation word set
 2606: @item providing the Memory-Allocation Extensions word set (that one's easy)
 2607: @item providing the Programming-Tools word set
 2608: @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
 2609: @item providing the Search-Order word set
 2610: @item providing the Search-Order Extensions word set
 2611: @item providing the String word set
 2612: @item providing the String Extensions word set (another easy one)
 2613: @end itemize
 2614: 
 2615: In addition, ANS Forth systems are required to document certain
 2616: implementation choices. This chapter tries to meet these
 2617: requirements. In many cases it gives a way to ask the system for the
 2618: information instead of providing the information directly, in
 2619: particular, if the information depends on the processor, the operating
 2620: system or the installation options chosen, or if they are likely to
 2621: change during the maintenance of Gforth.
 2622: 
 2623: @comment The framework for the rest has been taken from pfe.
 2624: 
 2625: @menu
 2626: * The Core Words::              
 2627: * The optional Block word set::  
 2628: * The optional Double Number word set::  
 2629: * The optional Exception word set::  
 2630: * The optional Facility word set::  
 2631: * The optional File-Access word set::  
 2632: * The optional Floating-Point word set::  
 2633: * The optional Locals word set::  
 2634: * The optional Memory-Allocation word set::  
 2635: * The optional Programming-Tools word set::  
 2636: * The optional Search-Order word set::  
 2637: @end menu
 2638: 
 2639: 
 2640: @c =====================================================================
 2641: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
 2642: @comment  node-name,  next,  previous,  up
 2643: @section The Core Words
 2644: @c =====================================================================
 2645: 
 2646: @menu
 2647: * core-idef::                   Implementation Defined Options                   
 2648: * core-ambcond::                Ambiguous Conditions                
 2649: * core-other::                  Other System Documentation                  
 2650: @end menu
 2651: 
 2652: @c ---------------------------------------------------------------------
 2653: @node core-idef, core-ambcond, The Core Words, The Core Words
 2654: @subsection Implementation Defined Options
 2655: @c ---------------------------------------------------------------------
 2656: 
 2657: @table @i
 2658: 
 2659: @item (Cell) aligned addresses:
 2660: processor-dependent. Gforth's alignment words perform natural alignment
 2661: (e.g., an address aligned for a datum of size 8 is divisible by
 2662: 8). Unaligned accesses usually result in a @code{-23 THROW}.
 2663: 
 2664: @item @code{EMIT} and non-graphic characters:
 2665: The character is output using the C library function (actually, macro)
 2666: @code{putc}.
 2667: 
 2668: @item character editing of @code{ACCEPT} and @code{EXPECT}:
 2669: This is modeled on the GNU readline library (@pxref{Readline
 2670: Interaction, , Command Line Editing, readline, The GNU Readline
 2671: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
 2672: producing a full word completion every time you type it (instead of
 2673: producing the common prefix of all completions).
 2674: 
 2675: @item character set:
 2676: The character set of your computer and display device. Gforth is
 2677: 8-bit-clean (but some other component in your system may make trouble).
 2678: 
 2679: @item Character-aligned address requirements:
 2680: installation-dependent. Currently a character is represented by a C
 2681: @code{unsigned char}; in the future we might switch to @code{wchar_t}
 2682: (Comments on that requested).
 2683: 
 2684: @item character-set extensions and matching of names:
 2685: Any character except the ASCII NUL charcter can be used in a
 2686: name. Matching is case-insensitive (except in @code{TABLE}s. The
 2687: matching is performed using the C function @code{strncasecmp}, whose
 2688: function is probably influenced by the locale. E.g., the @code{C} locale
 2689: does not know about accents and umlauts, so they are matched
 2690: case-sensitively in that locale. For portability reasons it is best to
 2691: write programs such that they work in the @code{C} locale. Then one can
 2692: use libraries written by a Polish programmer (who might use words
 2693: containing ISO Latin-2 encoded characters) and by a French programmer
 2694: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
 2695: funny results for some of the words (which ones, depends on the font you
 2696: are using)). Also, the locale you prefer may not be available in other
 2697: operating systems. Hopefully, Unicode will solve these problems one day.
 2698: 
 2699: @item conditions under which control characters match a space delimiter:
 2700: If @code{WORD} is called with the space character as a delimiter, all
 2701: white-space characters (as identified by the C macro @code{isspace()})
 2702: are delimiters. @code{PARSE}, on the other hand, treats space like other
 2703: delimiters. @code{PARSE-WORD} treats space like @code{WORD}, but behaves
 2704: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
 2705: interpreter (aka text interpreter) by default, treats all white-space
 2706: characters as delimiters.
 2707: 
 2708: @item format of the control flow stack:
 2709: The data stack is used as control flow stack. The size of a control flow
 2710: stack item in cells is given by the constant @code{cs-item-size}. At the
 2711: time of this writing, an item consists of a (pointer to a) locals list
 2712: (third), an address in the code (second), and a tag for identifying the
 2713: item (TOS). The following tags are used: @code{defstart},
 2714: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
 2715: @code{scopestart}.
 2716: 
 2717: @item conversion of digits > 35
 2718: The characters @code{[\]^_'} are the digits with the decimal value
 2719: 36@minus{}41. There is no way to input many of the larger digits.
 2720: 
 2721: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
 2722: The cursor is moved to the end of the entered string. If the input is
 2723: terminated using the @kbd{Return} key, a space is typed.
 2724: 
 2725: @item exception abort sequence of @code{ABORT"}:
 2726: The error string is stored into the variable @code{"error} and a
 2727: @code{-2 throw} is performed.
 2728: 
 2729: @item input line terminator:
 2730: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
 2731: lines. One of these characters is typically produced when you type the
 2732: @kbd{Enter} or @kbd{Return} key.
 2733: 
 2734: @item maximum size of a counted string:
 2735: @code{s" /counted-string" environment? drop .}. Currently 255 characters
 2736: on all ports, but this may change.
 2737: 
 2738: @item maximum size of a parsed string:
 2739: Given by the constant @code{/line}. Currently 255 characters.
 2740: 
 2741: @item maximum size of a definition name, in characters:
 2742: 31
 2743: 
 2744: @item maximum string length for @code{ENVIRONMENT?}, in characters:
 2745: 31
 2746: 
 2747: @item method of selecting the user input device:
 2748: The user input device is the standard input. There is currently no way to
 2749: change it from within Gforth. However, the input can typically be
 2750: redirected in the command line that starts Gforth.
 2751: 
 2752: @item method of selecting the user output device:
 2753: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
 2754: @code{outfile-id} (@code{stdout} by default). Gforth uses buffered
 2755: output, so output on a terminal does not become visible before the next
 2756: newline or buffer overflow. Output on non-terminals is invisible until
 2757: the buffer overflows.
 2758: 
 2759: @item methods of dictionary compilation:
 2760: What are we expected to document here?
 2761: 
 2762: @item number of bits in one address unit:
 2763: @code{s" address-units-bits" environment? drop .}. 8 in all current
 2764: ports.
 2765: 
 2766: @item number representation and arithmetic:
 2767: Processor-dependent. Binary two's complement on all current ports.
 2768: 
 2769: @item ranges for integer types:
 2770: Installation-dependent. Make environmental queries for @code{MAX-N},
 2771: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
 2772: unsigned (and positive) types is 0. The lower bound for signed types on
 2773: two's complement and one's complement machines machines can be computed
 2774: by adding 1 to the upper bound.
 2775: 
 2776: @item read-only data space regions:
 2777: The whole Forth data space is writable.
 2778: 
 2779: @item size of buffer at @code{WORD}:
 2780: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
 2781: shared with the pictured numeric output string. If overwriting
 2782: @code{PAD} is acceptable, it is as large as the remaining dictionary
 2783: space, although only as much can be sensibly used as fits in a counted
 2784: string.
 2785: 
 2786: @item size of one cell in address units:
 2787: @code{1 cells .}.
 2788: 
 2789: @item size of one character in address units:
 2790: @code{1 chars .}. 1 on all current ports.
 2791: 
 2792: @item size of the keyboard terminal buffer:
 2793: Varies. You can determine the size at a specific time using @code{lp@@
 2794: tib - .}. It is shared with the locals stack and TIBs of files that
 2795: include the current file. You can change the amount of space for TIBs
 2796: and locals stack at Gforth startup with the command line option
 2797: @code{-l}.
 2798: 
 2799: @item size of the pictured numeric output buffer:
 2800: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
 2801: shared with @code{WORD}.
 2802: 
 2803: @item size of the scratch area returned by @code{PAD}:
 2804: The remainder of dictionary space. You can even use the unused part of
 2805: the data stack space. The current size can be computed with @code{sp@@
 2806: pad - .}.
 2807: 
 2808: @item system case-sensitivity characteristics:
 2809: Dictionary searches are case insensitive (except in
 2810: @code{TABLE}s). However, as explained above under @i{character-set
 2811: extensions}, the matching for non-ASCII characters is determined by the
 2812: locale you are using. In the default @code{C} locale all non-ASCII
 2813: characters are matched case-sensitively.
 2814: 
 2815: @item system prompt:
 2816: @code{ ok} in interpret state, @code{ compiled} in compile state.
 2817: 
 2818: @item division rounding:
 2819: installation dependent. @code{s" floored" environment? drop .}. We leave
 2820: the choice to @code{gcc} (what to use for @code{/}) and to you (whether to use
 2821: @code{fm/mod}, @code{sm/rem} or simply @code{/}).
 2822: 
 2823: @item values of @code{STATE} when true:
 2824: -1.
 2825: 
 2826: @item values returned after arithmetic overflow:
 2827: On two's complement machines, arithmetic is performed modulo
 2828: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
 2829: arithmetic (with appropriate mapping for signed types). Division by zero
 2830: typically results in a @code{-55 throw} (Floating-point unidentified
 2831: fault), although a @code{-10 throw} (divide by zero) would be more
 2832: appropriate.
 2833: 
 2834: @item whether the current definition can be found after @t{DOES>}:
 2835: No.
 2836: 
 2837: @end table
 2838: 
 2839: @c ---------------------------------------------------------------------
 2840: @node core-ambcond, core-other, core-idef, The Core Words
 2841: @subsection Ambiguous conditions
 2842: @c ---------------------------------------------------------------------
 2843: 
 2844: @table @i
 2845: 
 2846: @item a name is neither a word nor a number:
 2847: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
 2848: preserves the data and FP stack, so you don't lose more work than
 2849: necessary.
 2850: 
 2851: @item a definition name exceeds the maximum length allowed:
 2852: @code{-19 throw} (Word name too long)
 2853: 
 2854: @item addressing a region not inside the various data spaces of the forth system:
 2855: The stacks, code space and name space are accessible. Machine code space is
 2856: typically readable. Accessing other addresses gives results dependent on
 2857: the operating system. On decent systems: @code{-9 throw} (Invalid memory
 2858: address).
 2859: 
 2860: @item argument type incompatible with parameter:
 2861: This is usually not caught. Some words perform checks, e.g., the control
 2862: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
 2863: mismatch).
 2864: 
 2865: @item attempting to obtain the execution token of a word with undefined execution semantics:
 2866: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
 2867: get an execution token for @code{compile-only-error} (which performs a
 2868: @code{-14 throw} when executed).
 2869: 
 2870: @item dividing by zero:
 2871: typically results in a @code{-55 throw} (floating point unidentified
 2872: fault), although a @code{-10 throw} (divide by zero) would be more
 2873: appropriate.
 2874: 
 2875: @item insufficient data stack or return stack space:
 2876: Not checked. This typically results in mysterious illegal memory
 2877: accesses, producing @code{-9 throw} (Invalid memory address) or
 2878: @code{-23 throw} (Address alignment exception).
 2879: 
 2880: @item insufficient space for loop control parameters:
 2881: like other return stack overflows.
 2882: 
 2883: @item insufficient space in the dictionary:
 2884: Not checked. Similar results as stack overflows. However, typically the
 2885: error appears at a different place when one inserts or removes code.
 2886: 
 2887: @item interpreting a word with undefined interpretation semantics:
 2888: For some words, we defined interpretation semantics. For the others:
 2889: @code{-14 throw} (Interpreting a compile-only word).
 2890: 
 2891: @item modifying the contents of the input buffer or a string literal:
 2892: These are located in writable memory and can be modified.
 2893: 
 2894: @item overflow of the pictured numeric output string:
 2895: Not checked.
 2896: 
 2897: @item parsed string overflow:
 2898: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
 2899: 
 2900: @item producing a result out of range:
 2901: On two's complement machines, arithmetic is performed modulo
 2902: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
 2903: arithmetic (with appropriate mapping for signed types). Division by zero
 2904: typically results in a @code{-55 throw} (floatingpoint unidentified
 2905: fault), although a @code{-10 throw} (divide by zero) would be more
 2906: appropriate. @code{convert} and @code{>number} currently overflow
 2907: silently.
 2908: 
 2909: @item reading from an empty data or return stack:
 2910: The data stack is checked by the outer (aka text) interpreter after
 2911: every word executed. If it has underflowed, a @code{-4 throw} (Stack
 2912: underflow) is performed. Apart from that, the stacks are not checked and
 2913: underflows can result in similar behaviour as overflows (of adjacent
 2914: stacks).
 2915: 
 2916: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
 2917: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
 2918: use zero-length string as a name). Words like @code{'} probably will not
 2919: find what they search. Note that it is possible to create zero-length
 2920: names with @code{nextname} (should it not?).
 2921: 
 2922: @item @code{>IN} greater than input buffer:
 2923: The next invocation of a parsing word returns a string wih length 0.
 2924: 
 2925: @item @code{RECURSE} appears after @code{DOES>}:
 2926: Compiles a recursive call to the defining word, not to the defined word.
 2927: 
 2928: @item argument input source different than current input source for @code{RESTORE-INPUT}:
 2929: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
 2930: the end of the file was reached), its source-id may be
 2931: reused. Therefore, restoring an input source specification referencing a
 2932: closed file may lead to unpredictable results instead of a @code{-12
 2933: THROW}.
 2934: 
 2935: In the future, Gforth may be able to restore input source specifications
 2936: from other than the current input soruce.
 2937: 
 2938: @item data space containing definitions gets de-allocated:
 2939: Deallocation with @code{allot} is not checked. This typically resuls in
 2940: memory access faults or execution of illegal instructions.
 2941: 
 2942: @item data space read/write with incorrect alignment:
 2943: Processor-dependent. Typically results in a @code{-23 throw} (Address
 2944: alignment exception). Under Linux on a 486 or later processor with
 2945: alignment turned on, incorrect alignment results in a @code{-9 throw}
 2946: (Invalid memory address). There are reportedly some processors with
 2947: alignment restrictions that do not report them.
 2948: 
 2949: @item data space pointer not properly aligned, @code{,}, @code{C,}:
 2950: Like other alignment errors.
 2951: 
 2952: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
 2953: Not checked. May cause an illegal memory access.
 2954: 
 2955: @item loop control parameters not available:
 2956: Not checked. The counted loop words simply assume that the top of return
 2957: stack items are loop control parameters and behave accordingly.
 2958: 
 2959: @item most recent definition does not have a name (@code{IMMEDIATE}):
 2960: @code{abort" last word was headerless"}.
 2961: 
 2962: @item name not defined by @code{VALUE} used by @code{TO}:
 2963: @code{-32 throw} (Invalid name argument) (unless name was defined by
 2964: @code{CONSTANT}; then it just changes the constant).
 2965: 
 2966: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
 2967: @code{-13 throw} (Undefined word)
 2968: 
 2969: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
 2970: Gforth behaves as if they were of the same type. I.e., you can predict
 2971: the behaviour by interpreting all parameters as, e.g., signed.
 2972: 
 2973: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
 2974: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
 2975: compilation semantics of @code{TO}.
 2976: 
 2977: @item String longer than a counted string returned by @code{WORD}:
 2978: Not checked. The string will be ok, but the count will, of course,
 2979: contain only the least significant bits of the length.
 2980: 
 2981: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
 2982: Processor-dependent. Typical behaviours are returning 0 and using only
 2983: the low bits of the shift count.
 2984: 
 2985: @item word not defined via @code{CREATE}:
 2986: @code{>BODY} produces the PFA of the word no matter how it was defined.
 2987: 
 2988: @code{DOES>} changes the execution semantics of the last defined word no
 2989: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
 2990: @code{CREATE , DOES>}.
 2991: 
 2992: @item words improperly used outside @code{<#} and @code{#>}:
 2993: Not checked. As usual, you can expect memory faults.
 2994: 
 2995: @end table
 2996: 
 2997: 
 2998: @c ---------------------------------------------------------------------
 2999: @node core-other,  , core-ambcond, The Core Words
 3000: @subsection Other system documentation
 3001: @c ---------------------------------------------------------------------
 3002: 
 3003: @table @i
 3004: 
 3005: @item nonstandard words using @code{PAD}:
 3006: None.
 3007: 
 3008: @item operator's terminal facilities available:
 3009: After processing the command line, Gforth goes into interactive mode,
 3010: and you can give commands to Gforth interactively. The actual facilities
 3011: available depend on how you invoke Gforth.
 3012: 
 3013: @item program data space available:
 3014: @code{sp@@ here - .} gives the space remaining for dictionary and data
 3015: stack together.
 3016: 
 3017: @item return stack space available:
 3018: By default 16 KBytes. The default can be overridden with the @code{-r}
 3019: switch (@pxref{Invocation}) when Gforth starts up.
 3020: 
 3021: @item stack space available:
 3022: @code{sp@@ here - .} gives the space remaining for dictionary and data
 3023: stack together.
 3024: 
 3025: @item system dictionary space required, in address units:
 3026: Type @code{here forthstart - .} after startup. At the time of this
 3027: writing, this gives 70108 (bytes) on a 32-bit system.
 3028: @end table
 3029: 
 3030: 
 3031: @c =====================================================================
 3032: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
 3033: @section The optional Block word set
 3034: @c =====================================================================
 3035: 
 3036: @menu
 3037: * block-idef::                  Implementation Defined Options                  
 3038: * block-ambcond::               Ambiguous Conditions               
 3039: * block-other::                 Other System Documentation                 
 3040: @end menu
 3041: 
 3042: 
 3043: @c ---------------------------------------------------------------------
 3044: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
 3045: @subsection Implementation Defined Options
 3046: @c ---------------------------------------------------------------------
 3047: 
 3048: @table @i
 3049: 
 3050: @item the format for display by @code{LIST}:
 3051: First the screen number is displayed, then 16 lines of 64 characters,
 3052: each line preceded by the line number.
 3053: 
 3054: @item the length of a line affected by @code{\}:
 3055: 64 characters.
 3056: @end table
 3057: 
 3058: 
 3059: @c ---------------------------------------------------------------------
 3060: @node block-ambcond, block-other, block-idef, The optional Block word set
 3061: @subsection Ambiguous conditions
 3062: @c ---------------------------------------------------------------------
 3063: 
 3064: @table @i
 3065: 
 3066: @item correct block read was not possible:
 3067: Typically results in a @code{throw} of some OS-derived value (between
 3068: -512 and -2048). If the blocks file was just not long enough, blanks are
 3069: supplied for the missing portion.
 3070: 
 3071: @item I/O exception in block transfer:
 3072: Typically results in a @code{throw} of some OS-derived value (between
 3073: -512 and -2048).
 3074: 
 3075: @item invalid block number:
 3076: @code{-35 throw} (Invalid block number)
 3077: 
 3078: @item a program directly alters the contents of @code{BLK}:
 3079: The input stream is switched to that other block, at the same
 3080: position. If the storing to @code{BLK} happens when interpreting
 3081: non-block input, the system will get quite confused when the block ends.
 3082: 
 3083: @item no current block buffer for @code{UPDATE}:
 3084: @code{UPDATE} has no effect.
 3085: 
 3086: @end table
 3087: 
 3088: 
 3089: @c ---------------------------------------------------------------------
 3090: @node block-other,  , block-ambcond, The optional Block word set
 3091: @subsection Other system documentation
 3092: @c ---------------------------------------------------------------------
 3093: 
 3094: @table @i
 3095: 
 3096: @item any restrictions a multiprogramming system places on the use of buffer addresses:
 3097: No restrictions (yet).
 3098: 
 3099: @item the number of blocks available for source and data:
 3100: depends on your disk space.
 3101: 
 3102: @end table
 3103: 
 3104: 
 3105: @c =====================================================================
 3106: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
 3107: @section The optional Double Number word set
 3108: @c =====================================================================
 3109: 
 3110: @menu
 3111: * double-ambcond::              Ambiguous Conditions              
 3112: @end menu
 3113: 
 3114: 
 3115: @c ---------------------------------------------------------------------
 3116: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
 3117: @subsection Ambiguous conditions
 3118: @c ---------------------------------------------------------------------
 3119: 
 3120: @table @i
 3121: 
 3122: @item @var{d} outside of range of @var{n} in @code{D>S}:
 3123: The least significant cell of @var{d} is produced.
 3124: 
 3125: @end table
 3126: 
 3127: 
 3128: @c =====================================================================
 3129: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
 3130: @section The optional Exception word set
 3131: @c =====================================================================
 3132: 
 3133: @menu
 3134: * exception-idef::              Implementation Defined Options              
 3135: @end menu
 3136: 
 3137: 
 3138: @c ---------------------------------------------------------------------
 3139: @node exception-idef,  , The optional Exception word set, The optional Exception word set
 3140: @subsection Implementation Defined Options
 3141: @c ---------------------------------------------------------------------
 3142: 
 3143: @table @i
 3144: @item @code{THROW}-codes used in the system:
 3145: The codes -256@minus{}-511 are used for reporting signals (see
 3146: @file{errore.fs}). The codes -512@minus{}-2047 are used for OS errors
 3147: (for file and memory allocation operations). The mapping from OS error
 3148: numbers to throw code is -512@minus{}@var{errno}. One side effect of
 3149: this mapping is that undefined OS errors produce a message with a
 3150: strange number; e.g., @code{-1000 THROW} results in @code{Unknown error
 3151: 488} on my system.
 3152: @end table
 3153: 
 3154: @c =====================================================================
 3155: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
 3156: @section The optional Facility word set
 3157: @c =====================================================================
 3158: 
 3159: @menu
 3160: * facility-idef::               Implementation Defined Options               
 3161: * facility-ambcond::            Ambiguous Conditions            
 3162: @end menu
 3163: 
 3164: 
 3165: @c ---------------------------------------------------------------------
 3166: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
 3167: @subsection Implementation Defined Options
 3168: @c ---------------------------------------------------------------------
 3169: 
 3170: @table @i
 3171: 
 3172: @item encoding of keyboard events (@code{EKEY}):
 3173: Not yet implemeted.
 3174: 
 3175: @item duration of a system clock tick
 3176: System dependent. With respect to @code{MS}, the time is specified in
 3177: microseconds. How well the OS and the hardware implement this, is
 3178: another question.
 3179: 
 3180: @item repeatability to be expected from the execution of @code{MS}:
 3181: System dependent. On Unix, a lot depends on load. If the system is
 3182: lightly loaded, and the delay is short enough that Gforth does not get
 3183: swapped out, the performance should be acceptable. Under MS-DOS and
 3184: other single-tasking systems, it should be good.
 3185: 
 3186: @end table
 3187: 
 3188: 
 3189: @c ---------------------------------------------------------------------
 3190: @node facility-ambcond,  , facility-idef, The optional Facility word set
 3191: @subsection Ambiguous conditions
 3192: @c ---------------------------------------------------------------------
 3193: 
 3194: @table @i
 3195: 
 3196: @item @code{AT-XY} can't be performed on user output device:
 3197: Largely terminal dependant. No range checks are done on the arguments.
 3198: No errors are reported. You may see some garbage appearing, you may see
 3199: simply nothing happen.
 3200: 
 3201: @end table
 3202: 
 3203: 
 3204: @c =====================================================================
 3205: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
 3206: @section The optional File-Access word set
 3207: @c =====================================================================
 3208: 
 3209: @menu
 3210: * file-idef::                   Implementation Defined Options                   
 3211: * file-ambcond::                Ambiguous Conditions                
 3212: @end menu
 3213: 
 3214: 
 3215: @c ---------------------------------------------------------------------
 3216: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
 3217: @subsection Implementation Defined Options
 3218: @c ---------------------------------------------------------------------
 3219: 
 3220: @table @i
 3221: 
 3222: @item File access methods used:
 3223: @code{R/O}, @code{R/W} and @code{BIN} work as you would
 3224: expect. @code{W/O} translates into the C file opening mode @code{w} (or
 3225: @code{wb}): The file is cleared, if it exists, and created, if it does
 3226: not (both with @code{open-file} and @code{create-file}).  Under Unix
 3227: @code{create-file} creates a file with 666 permissions modified by your
 3228: umask.
 3229: 
 3230: @item file exceptions:
 3231: The file words do not raise exceptions (except, perhaps, memory access
 3232: faults when you pass illegal addresses or file-ids).
 3233: 
 3234: @item file line terminator:
 3235: System-dependent. Gforth uses C's newline character as line
 3236: terminator. What the actual character code(s) of this are is
 3237: system-dependent.
 3238: 
 3239: @item file name format
 3240: System dependent. Gforth just uses the file name format of your OS.
 3241: 
 3242: @item information returned by @code{FILE-STATUS}:
 3243: @code{FILE-STATUS} returns the most powerful file access mode allowed
 3244: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
 3245: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
 3246: along with the retured mode.
 3247: 
 3248: @item input file state after an exception when including source:
 3249: All files that are left via the exception are closed.
 3250: 
 3251: @item @var{ior} values and meaning:
 3252: The @var{ior}s returned by the file and memory allocation words are
 3253: intended as throw codes. They typically are in the range
 3254: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
 3255: @var{ior}s is -512@minus{}@var{errno}.
 3256: 
 3257: @item maximum depth of file input nesting:
 3258: limited by the amount of return stack, locals/TIB stack, and the number
 3259: of open files available. This should not give you troubles.
 3260: 
 3261: @item maximum size of input line:
 3262: @code{/line}. Currently 255.
 3263: 
 3264: @item methods of mapping block ranges to files:
 3265: Currently, the block words automatically access the file
 3266: @file{blocks.fb} in the currend working directory. More sophisticated
 3267: methods could be implemented if there is demand (and a volunteer).
 3268: 
 3269: @item number of string buffers provided by @code{S"}:
 3270: 1
 3271: 
 3272: @item size of string buffer used by @code{S"}:
 3273: @code{/line}. currently 255.
 3274: 
 3275: @end table
 3276: 
 3277: @c ---------------------------------------------------------------------
 3278: @node file-ambcond,  , file-idef, The optional File-Access word set
 3279: @subsection Ambiguous conditions
 3280: @c ---------------------------------------------------------------------
 3281: 
 3282: @table @i
 3283: 
 3284: @item attempting to position a file outside it's boundaries:
 3285: @code{REPOSITION-FILE} is performed as usual: Afterwards,
 3286: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
 3287: 
 3288: @item attempting to read from file positions not yet written:
 3289: End-of-file, i.e., zero characters are read and no error is reported.
 3290: 
 3291: @item @var{file-id} is invalid (@code{INCLUDE-FILE}):
 3292: An appropriate exception may be thrown, but a memory fault or other
 3293: problem is more probable.
 3294: 
 3295: @item I/O exception reading or closing @var{file-id} (@code{include-file}, @code{included}):
 3296: The @var{ior} produced by the operation, that discovered the problem, is
 3297: thrown.
 3298: 
 3299: @item named file cannot be opened (@code{included}):
 3300: The @var{ior} produced by @code{open-file} is thrown.
 3301: 
 3302: @item requesting an unmapped block number:
 3303: There are no unmapped legal block numbers. On some operating systems,
 3304: writing a block with a large number may overflow the file system and
 3305: have an error message as consequence.
 3306: 
 3307: @item using @code{source-id} when @code{blk} is non-zero:
 3308: @code{source-id} performs its function. Typically it will give the id of
 3309: the source which loaded the block. (Better ideas?)
 3310: 
 3311: @end table
 3312: 
 3313: 
 3314: @c =====================================================================
 3315: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
 3316: @section The optional Floating-Point word set
 3317: @c =====================================================================
 3318: 
 3319: @menu
 3320: * floating-idef::               Implementation Defined Options
 3321: * floating-ambcond::            Ambiguous Conditions            
 3322: @end menu
 3323: 
 3324: 
 3325: @c ---------------------------------------------------------------------
 3326: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
 3327: @subsection Implementation Defined Options
 3328: @c ---------------------------------------------------------------------
 3329: 
 3330: @table @i
 3331: 
 3332: @item format and range of floating point numbers:
 3333: System-dependent; the @code{double} type of C.
 3334: 
 3335: @item results of @code{REPRESENT} when @var{float} is out of range:
 3336: System dependent; @code{REPRESENT} is implemented using the C library
 3337: function @code{ecvt()} and inherits its behaviour in this respect.
 3338: 
 3339: @item rounding or truncation of floating-point numbers:
 3340: System dependent; the rounding behaviour is inherited from the hosting C
 3341: compiler. IEEE-FP-based (i.e., most) systems by default round to
 3342: nearest, and break ties by rounding to even (i.e., such that the last
 3343: bit of the mantissa is 0).
 3344: 
 3345: @item size of floating-point stack:
 3346: @code{s" FLOATING-STACK" environment? drop .}. Can be changed at startup
 3347: with the command-line option @code{-f}.
 3348: 
 3349: @item width of floating-point stack:
 3350: @code{1 floats}.
 3351: 
 3352: @end table
 3353: 
 3354: 
 3355: @c ---------------------------------------------------------------------
 3356: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
 3357: @subsection Ambiguous conditions
 3358: @c ---------------------------------------------------------------------
 3359: 
 3360: @table @i
 3361: 
 3362: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
 3363: System-dependent. Typically results in an alignment fault like other
 3364: alignment violations.
 3365: 
 3366: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
 3367: System-dependent. Typically results in an alignment fault like other
 3368: alignment violations.
 3369: 
 3370: @item Floating-point result out of range:
 3371: System-dependent. Can result in a @code{-55 THROW} (Floating-point
 3372: unidentified fault), or can produce a special value representing, e.g.,
 3373: Infinity.
 3374: 
 3375: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
 3376: System-dependent. Typically results in an alignment fault like other
 3377: alignment violations.
 3378: 
 3379: @item BASE is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
 3380: The floating-point number is converted into decimal nonetheless.
 3381: 
 3382: @item Both arguments are equal to zero (@code{FATAN2}):
 3383: System-dependent. @code{FATAN2} is implemented using the C library
 3384: function @code{atan2()}.
 3385: 
 3386: @item Using ftan on an argument @var{r1} where cos(@var{r1}) is zero:
 3387: System-dependent. Anyway, typically the cos of @var{r1} will not be zero
 3388: because of small errors and the tan will be a very large (or very small)
 3389: but finite number.
 3390: 
 3391: @item @var{d} cannot be presented precisely as a float in @code{D>F}:
 3392: The result is rounded to the nearest float.
 3393: 
 3394: @item dividing by zero:
 3395: @code{-55 throw} (Floating-point unidentified fault)
 3396: 
 3397: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
 3398: System dependent. On IEEE-FP based systems the number is converted into
 3399: an infinity.
 3400: 
 3401: @item @var{float}<1 (@code{facosh}):
 3402: @code{-55 throw} (Floating-point unidentified fault)
 3403: 
 3404: @item @var{float}=<-1 (@code{flnp1}):
 3405: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
 3406: negative infinity is typically produced for @var{float}=-1.
 3407: 
 3408: @item @var{float}=<0 (@code{fln}, @code{flog}):
 3409: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
 3410: negative infinity is typically produced for @var{float}=0.
 3411: 
 3412: @item @var{float}<0 (@code{fasinh}, @code{fsqrt}):
 3413: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
 3414: produces values for these inputs on my Linux box (Bug in the C library?)
 3415: 
 3416: @item |@var{float}|>1 (@code{facos}, @code{fasin}, @code{fatanh}):
 3417: @code{-55 throw} (Floating-point unidentified fault).
 3418: 
 3419: @item integer part of float cannot be represented by @var{d} in @code{f>d}:
 3420: @code{-55 throw} (Floating-point unidentified fault).
 3421: 
 3422: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
 3423: This does not happen.
 3424: @end table
 3425: 
 3426: 
 3427: 
 3428: @c =====================================================================
 3429: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
 3430: @section The optional Locals word set
 3431: @c =====================================================================
 3432: 
 3433: @menu
 3434: * locals-idef::                 Implementation Defined Options                 
 3435: * locals-ambcond::              Ambiguous Conditions              
 3436: @end menu
 3437: 
 3438: 
 3439: @c ---------------------------------------------------------------------
 3440: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
 3441: @subsection Implementation Defined Options
 3442: @c ---------------------------------------------------------------------
 3443: 
 3444: @table @i
 3445: 
 3446: @item maximum number of locals in a definition:
 3447: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
 3448: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
 3449: characters. The number of locals in a definition is bounded by the size
 3450: of locals-buffer, which contains the names of the locals.
 3451: 
 3452: @end table
 3453: 
 3454: 
 3455: @c ---------------------------------------------------------------------
 3456: @node locals-ambcond,  , locals-idef, The optional Locals word set
 3457: @subsection Ambiguous conditions
 3458: @c ---------------------------------------------------------------------
 3459: 
 3460: @table @i
 3461: 
 3462: @item executing a named local in interpretation state:
 3463: @code{-14 throw} (Interpreting a compile-only word).
 3464: 
 3465: @item @var{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
 3466: @code{-32 throw} (Invalid name argument)
 3467: 
 3468: @end table
 3469: 
 3470: 
 3471: @c =====================================================================
 3472: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
 3473: @section The optional Memory-Allocation word set
 3474: @c =====================================================================
 3475: 
 3476: @menu
 3477: * memory-idef::                 Implementation Defined Options                 
 3478: @end menu
 3479: 
 3480: 
 3481: @c ---------------------------------------------------------------------
 3482: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
 3483: @subsection Implementation Defined Options
 3484: @c ---------------------------------------------------------------------
 3485: 
 3486: @table @i
 3487: 
 3488: @item values and meaning of @var{ior}:
 3489: The @var{ior}s returned by the file and memory allocation words are
 3490: intended as throw codes. They typically are in the range
 3491: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
 3492: @var{ior}s is -512@minus{}@var{errno}.
 3493: 
 3494: @end table
 3495: 
 3496: @c =====================================================================
 3497: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
 3498: @section The optional Programming-Tools word set
 3499: @c =====================================================================
 3500: 
 3501: @menu
 3502: * programming-idef::            Implementation Defined Options            
 3503: * programming-ambcond::         Ambiguous Conditions         
 3504: @end menu
 3505: 
 3506: 
 3507: @c ---------------------------------------------------------------------
 3508: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
 3509: @subsection Implementation Defined Options
 3510: @c ---------------------------------------------------------------------
 3511: 
 3512: @table @i
 3513: 
 3514: @item ending sequence for input following @code{;code} and @code{code}:
 3515: Not implemented (yet).
 3516: 
 3517: @item manner of processing input following @code{;code} and @code{code}:
 3518: Not implemented (yet).
 3519: 
 3520: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
 3521: Not implemented (yet). If they were implemented, they would use the
 3522: search order wordset.
 3523: 
 3524: @item source and format of display by @code{SEE}:
 3525: The source for @code{see} is the intermediate code used by the inner
 3526: interpreter.  The current @code{see} tries to output Forth source code
 3527: as well as possible.
 3528: 
 3529: @end table
 3530: 
 3531: @c ---------------------------------------------------------------------
 3532: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
 3533: @subsection Ambiguous conditions
 3534: @c ---------------------------------------------------------------------
 3535: 
 3536: @table @i
 3537: 
 3538: @item deleting the compilation wordlist (@code{FORGET}):
 3539: Not implemented (yet).
 3540: 
 3541: @item fewer than @var{u}+1 items on the control flow stack (@code{CS-PICK}, @code{CS-ROLL}):
 3542: This typically results in an @code{abort"} with a descriptive error
 3543: message (may change into a @code{-22 throw} (Control structure mismatch)
 3544: in the future). You may also get a memory access error. If you are
 3545: unlucky, this ambiguous condition is not caught.
 3546: 
 3547: @item @var{name} can't be found (@code{forget}):
 3548: Not implemented (yet).
 3549: 
 3550: @item @var{name} not defined via @code{CREATE}:
 3551: @code{;code} is not implemented (yet). If it were, it would behave like
 3552: @code{DOES>} in this respect, i.e., change the execution semantics of
 3553: the last defined word no matter how it was defined.
 3554: 
 3555: @item @code{POSTPONE} applied to @code{[IF]}:
 3556: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
 3557: equivalent to @code{[IF]}.
 3558: 
 3559: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
 3560: Continue in the same state of conditional compilation in the next outer
 3561: input source. Currently there is no warning to the user about this.
 3562: 
 3563: @item removing a needed definition (@code{FORGET}):
 3564: Not implemented (yet).
 3565: 
 3566: @end table
 3567: 
 3568: 
 3569: @c =====================================================================
 3570: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
 3571: @section The optional Search-Order word set
 3572: @c =====================================================================
 3573: 
 3574: @menu
 3575: * search-idef::                 Implementation Defined Options                 
 3576: * search-ambcond::              Ambiguous Conditions              
 3577: @end menu
 3578: 
 3579: 
 3580: @c ---------------------------------------------------------------------
 3581: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
 3582: @subsection Implementation Defined Options
 3583: @c ---------------------------------------------------------------------
 3584: 
 3585: @table @i
 3586: 
 3587: @item maximum number of word lists in search order:
 3588: @code{s" wordlists" environment? drop .}. Currently 16.
 3589: 
 3590: @item minimum search order:
 3591: @code{root root}.
 3592: 
 3593: @end table
 3594: 
 3595: @c ---------------------------------------------------------------------
 3596: @node search-ambcond,  , search-idef, The optional Search-Order word set
 3597: @subsection Ambiguous conditions
 3598: @c ---------------------------------------------------------------------
 3599: 
 3600: @table @i
 3601: 
 3602: @item changing the compilation wordlist (during compilation):
 3603: The word is entered into the wordlist that was the compilation wordlist
 3604: at the start of the definition. Any changes to the name field (e.g.,
 3605: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
 3606: are applied to the latest defined word (as reported by @code{last} or
 3607: @code{lastxt}), if possible, irrespective of the compilation wordlist.
 3608: 
 3609: @item search order empty (@code{previous}):
 3610: @code{abort" Vocstack empty"}.
 3611: 
 3612: @item too many word lists in search order (@code{also}):
 3613: @code{abort" Vocstack full"}.
 3614: 
 3615: @end table
 3616: 
 3617: @node Model, Integrating Gforth, ANS conformance, Top
 3618: @chapter Model
 3619: 
 3620: This chapter has yet to be written. It will contain information, on
 3621: which internal structures you can rely.
 3622: 
 3623: @node Integrating Gforth, Emacs and Gforth, Model, Top
 3624: @chapter Integrating Gforth into C programs
 3625: 
 3626: This is not yet implemented.
 3627: 
 3628: Several people like to use Forth as scripting language for applications
 3629: that are otherwise written in C, C++, or some other language.
 3630: 
 3631: The Forth system ATLAST provides facilities for embedding it into
 3632: applications; unfortunately it has several disadvantages: most
 3633: importantly, it is not based on ANS Forth, and it is apparently dead
 3634: (i.e., not developed further and not supported). The facilities
 3635: provided by Gforth in this area are inspired by ATLASTs facilities, so
 3636: making the switch should not be hard.
 3637: 
 3638: We also tried to design the interface such that it can easily be
 3639: implemented by other Forth systems, so that we may one day arrive at a
 3640: standardized interface. Such a standard interface would allow you to
 3641: replace the Forth system without having to rewrite C code.
 3642: 
 3643: You embed the Gforth interpreter by linking with the library
 3644: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
 3645: global symbols in this library that belong to the interface, have the
 3646: prefix @code{forth_}. (Global symbols that are used internally have the
 3647: prefix @code{gforth_}).
 3648: 
 3649: You can include the declarations of Forth types and the functions and
 3650: variables of the interface with @code{#include <forth.h>}.
 3651: 
 3652: Types.
 3653: 
 3654: Variables.
 3655: 
 3656: Data and FP Stack pointer. Area sizes.
 3657: 
 3658: functions.
 3659: 
 3660: forth_init(imagefile)
 3661: forth_evaluate(string) exceptions?
 3662: forth_goto(address) (or forth_execute(xt)?)
 3663: forth_continue() (a corountining mechanism)
 3664: 
 3665: Adding primitives.
 3666: 
 3667: No checking.
 3668: 
 3669: Signals?
 3670: 
 3671: Accessing the Stacks
 3672: 
 3673: @node Emacs and Gforth, Internals, Integrating Gforth, Top
 3674: @chapter Emacs and Gforth
 3675: 
 3676: Gforth comes with @file{gforth.el}, an improved version of
 3677: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
 3678: improvements are a better (but still not perfect) handling of
 3679: indentation. I have also added comment paragraph filling (@kbd{M-q}),
 3680: commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) regions and
 3681: removing debugging tracers (@kbd{C-x ~}, @pxref{Debugging}). I left the
 3682: stuff I do not use alone, even though some of it only makes sense for
 3683: TILE. To get a description of these features, enter Forth mode and type
 3684: @kbd{C-h m}.
 3685: 
 3686: In addition, Gforth supports Emacs quite well: The source code locations
 3687: given in error messages, debugging output (from @code{~~}) and failed
 3688: assertion messages are in the right format for Emacs' compilation mode
 3689: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
 3690: Manual}) so the source location corresponding to an error or other
 3691: message is only a few keystrokes away (@kbd{C-x `} for the next error,
 3692: @kbd{C-c C-c} for the error under the cursor).
 3693: 
 3694: Also, if you @code{include} @file{etags.fs}, a new @file{TAGS} file
 3695: (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) will be produced that
 3696: contains the definitions of all words defined afterwards. You can then
 3697: find the source for a word using @kbd{M-.}. Note that emacs can use
 3698: several tags files at the same time (e.g., one for the Gforth sources
 3699: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
 3700: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
 3701: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
 3702: @file{/usr/local/share/gforth/0.2.0/TAGS}).
 3703: 
 3704: To get all these benefits, add the following lines to your @file{.emacs}
 3705: file:
 3706: 
 3707: @example
 3708: (autoload 'forth-mode "gforth.el")
 3709: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
 3710: @end example
 3711: 
 3712: @node Internals, Bugs, Emacs and Gforth, Top
 3713: @chapter Internals
 3714: 
 3715: Reading this section is not necessary for programming with Gforth. It
 3716: should be helpful for finding your way in the Gforth sources.
 3717: 
 3718: The ideas in this section have also been published in the papers
 3719: @cite{ANS fig/GNU/??? Forth} (in German) by Bernd Paysan, presented at
 3720: the Forth-Tagung '93 and @cite{A Portable Forth Engine} by M. Anton
 3721: Ertl, presented at EuroForth '93; the latter is available at
 3722: @*@file{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z}.
 3723: 
 3724: @menu
 3725: * Portability::                 
 3726: * Threading::                   
 3727: * Primitives::                  
 3728: * System Architecture::         
 3729: * Performance::                 
 3730: @end menu
 3731: 
 3732: @node Portability, Threading, Internals, Internals
 3733: @section Portability
 3734: 
 3735: One of the main goals of the effort is availability across a wide range
 3736: of personal machines. fig-Forth, and, to a lesser extent, F83, achieved
 3737: this goal by manually coding the engine in assembly language for several
 3738: then-popular processors. This approach is very labor-intensive and the
 3739: results are short-lived due to progress in computer architecture.
 3740: 
 3741: Others have avoided this problem by coding in C, e.g., Mitch Bradley
 3742: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
 3743: particularly popular for UNIX-based Forths due to the large variety of
 3744: architectures of UNIX machines. Unfortunately an implementation in C
 3745: does not mix well with the goals of efficiency and with using
 3746: traditional techniques: Indirect or direct threading cannot be expressed
 3747: in C, and switch threading, the fastest technique available in C, is
 3748: significantly slower. Another problem with C is that it's very
 3749: cumbersome to express double integer arithmetic.
 3750: 
 3751: Fortunately, there is a portable language that does not have these
 3752: limitations: GNU C, the version of C processed by the GNU C compiler
 3753: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
 3754: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
 3755: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
 3756: threading possible, its @code{long long} type (@pxref{Long Long, ,
 3757: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
 3758: double numbers@footnote{Unfortunately, long longs are not implemented
 3759: properly on all machines (e.g., on alpha-osf1, long longs are only 64
 3760: bits, the same size as longs (and pointers), but they should be twice as
 3761: long according to @ref{Long Long, , Double-Word Integers, gcc.info, GNU
 3762: C Manual}). So, we had to implement doubles in C after all. Still, on
 3763: most machines we can use long longs and achieve better performance than
 3764: with the emulation package.}. GNU C is available for free on all
 3765: important (and many unimportant) UNIX machines, VMS, 80386s running
 3766: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
 3767: on all these machines.
 3768: 
 3769: Writing in a portable language has the reputation of producing code that
 3770: is slower than assembly. For our Forth engine we repeatedly looked at
 3771: the code produced by the compiler and eliminated most compiler-induced
 3772: inefficiencies by appropriate changes in the source-code.
 3773: 
 3774: However, register allocation cannot be portably influenced by the
 3775: programmer, leading to some inefficiencies on register-starved
 3776: machines. We use explicit register declarations (@pxref{Explicit Reg
 3777: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
 3778: improve the speed on some machines. They are turned on by using the
 3779: @code{gcc} switch @code{-DFORCE_REG}. Unfortunately, this feature not
 3780: only depends on the machine, but also on the compiler version: On some
 3781: machines some compiler versions produce incorrect code when certain
 3782: explicit register declarations are used. So by default
 3783: @code{-DFORCE_REG} is not used.
 3784: 
 3785: @node Threading, Primitives, Portability, Internals
 3786: @section Threading
 3787: 
 3788: GNU C's labels as values extension (available since @code{gcc-2.0},
 3789: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
 3790: makes it possible to take the address of @var{label} by writing
 3791: @code{&&@var{label}}.  This address can then be used in a statement like
 3792: @code{goto *@var{address}}. I.e., @code{goto *&&x} is the same as
 3793: @code{goto x}.
 3794: 
 3795: With this feature an indirect threaded NEXT looks like:
 3796: @example
 3797: cfa = *ip++;
 3798: ca = *cfa;
 3799: goto *ca;
 3800: @end example
 3801: For those unfamiliar with the names: @code{ip} is the Forth instruction
 3802: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
 3803: execution token and points to the code field of the next word to be
 3804: executed; The @code{ca} (code address) fetched from there points to some
 3805: executable code, e.g., a primitive or the colon definition handler
 3806: @code{docol}.
 3807: 
 3808: Direct threading is even simpler:
 3809: @example
 3810: ca = *ip++;
 3811: goto *ca;
 3812: @end example
 3813: 
 3814: Of course we have packaged the whole thing neatly in macros called
 3815: @code{NEXT} and @code{NEXT1} (the part of NEXT after fetching the cfa).
 3816: 
 3817: @menu
 3818: * Scheduling::                  
 3819: * Direct or Indirect Threaded?::  
 3820: * DOES>::                       
 3821: @end menu
 3822: 
 3823: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
 3824: @subsection Scheduling
 3825: 
 3826: There is a little complication: Pipelined and superscalar processors,
 3827: i.e., RISC and some modern CISC machines can process independent
 3828: instructions while waiting for the results of an instruction. The
 3829: compiler usually reorders (schedules) the instructions in a way that
 3830: achieves good usage of these delay slots. However, on our first tries
 3831: the compiler did not do well on scheduling primitives. E.g., for
 3832: @code{+} implemented as
 3833: @example
 3834: n=sp[0]+sp[1];
 3835: sp++;
 3836: sp[0]=n;
 3837: NEXT;
 3838: @end example
 3839: the NEXT comes strictly after the other code, i.e., there is nearly no
 3840: scheduling. After a little thought the problem becomes clear: The
 3841: compiler cannot know that sp and ip point to different addresses (and
 3842: the version of @code{gcc} we used would not know it even if it was
 3843: possible), so it could not move the load of the cfa above the store to
 3844: the TOS. Indeed the pointers could be the same, if code on or very near
 3845: the top of stack were executed. In the interest of speed we chose to
 3846: forbid this probably unused ``feature'' and helped the compiler in
 3847: scheduling: NEXT is divided into the loading part (@code{NEXT_P1}) and
 3848: the goto part (@code{NEXT_P2}). @code{+} now looks like:
 3849: @example
 3850: n=sp[0]+sp[1];
 3851: sp++;
 3852: NEXT_P1;
 3853: sp[0]=n;
 3854: NEXT_P2;
 3855: @end example
 3856: This can be scheduled optimally by the compiler.
 3857: 
 3858: This division can be turned off with the switch @code{-DCISC_NEXT}. This
 3859: switch is on by default on machines that do not profit from scheduling
 3860: (e.g., the 80386), in order to preserve registers.
 3861: 
 3862: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
 3863: @subsection Direct or Indirect Threaded?
 3864: 
 3865: Both! After packaging the nasty details in macro definitions we
 3866: realized that we could switch between direct and indirect threading by
 3867: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
 3868: defining a few machine-specific macros for the direct-threading case.
 3869: On the Forth level we also offer access words that hide the
 3870: differences between the threading methods (@pxref{Threading Words}).
 3871: 
 3872: Indirect threading is implemented completely
 3873: machine-independently. Direct threading needs routines for creating
 3874: jumps to the executable code (e.g. to docol or dodoes). These routines
 3875: are inherently machine-dependent, but they do not amount to many source
 3876: lines. I.e., even porting direct threading to a new machine is a small
 3877: effort.
 3878: 
 3879: @node DOES>,  , Direct or Indirect Threaded?, Threading
 3880: @subsection DOES>
 3881: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
 3882: the chunk of code executed by every word defined by a
 3883: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
 3884: the Forth code to be executed, i.e. the code after the @code{DOES>} (the
 3885: DOES-code)? There are two solutions:
 3886: 
 3887: In fig-Forth the code field points directly to the dodoes and the
 3888: DOES-code address is stored in the cell after the code address
 3889: (i.e. at cfa cell+). It may seem that this solution is illegal in the
 3890: Forth-79 and all later standards, because in fig-Forth this address
 3891: lies in the body (which is illegal in these standards). However, by
 3892: making the code field larger for all words this solution becomes legal
 3893: again. We use this approach for the indirect threaded version. Leaving
 3894: a cell unused in most words is a bit wasteful, but on the machines we
 3895: are targetting this is hardly a problem. The other reason for having a
 3896: code field size of two cells is to avoid having different image files
 3897: for direct and indirect threaded systems (@pxref{System Architecture}).
 3898: 
 3899: The other approach is that the code field points or jumps to the cell
 3900: after @code{DOES}. In this variant there is a jump to @code{dodoes} at
 3901: this address. @code{dodoes} can then get the DOES-code address by
 3902: computing the code address, i.e., the address of the jump to dodoes,
 3903: and add the length of that jump field. A variant of this is to have a
 3904: call to @code{dodoes} after the @code{DOES>}; then the return address
 3905: (which can be found in the return register on RISCs) is the DOES-code
 3906: address. Since the two cells available in the code field are usually
 3907: used up by the jump to the code address in direct threading, we use
 3908: this approach for direct threading. We did not want to add another
 3909: cell to the code field.
 3910: 
 3911: @node Primitives, System Architecture, Threading, Internals
 3912: @section Primitives
 3913: 
 3914: @menu
 3915: * Automatic Generation::        
 3916: * TOS Optimization::            
 3917: * Produced code::               
 3918: @end menu
 3919: 
 3920: @node Automatic Generation, TOS Optimization, Primitives, Primitives
 3921: @subsection Automatic Generation
 3922: 
 3923: Since the primitives are implemented in a portable language, there is no
 3924: longer any need to minimize the number of primitives. On the contrary,
 3925: having many primitives is an advantage: speed. In order to reduce the
 3926: number of errors in primitives and to make programming them easier, we
 3927: provide a tool, the primitive generator (@file{prims2x.fs}), that
 3928: automatically generates most (and sometimes all) of the C code for a
 3929: primitive from the stack effect notation.  The source for a primitive
 3930: has the following form:
 3931: 
 3932: @format
 3933: @var{Forth-name}	@var{stack-effect}	@var{category}	[@var{pronounc.}]
 3934: [@code{""}@var{glossary entry}@code{""}]
 3935: @var{C code}
 3936: [@code{:}
 3937: @var{Forth code}]
 3938: @end format
 3939: 
 3940: The items in brackets are optional. The category and glossary fields
 3941: are there for generating the documentation, the Forth code is there
 3942: for manual implementations on machines without GNU C. E.g., the source
 3943: for the primitive @code{+} is:
 3944: @example
 3945: +    n1 n2 -- n    core    plus
 3946: n = n1+n2;
 3947: @end example
 3948: 
 3949: This looks like a specification, but in fact @code{n = n1+n2} is C
 3950: code. Our primitive generation tool extracts a lot of information from
 3951: the stack effect notations@footnote{We use a one-stack notation, even
 3952: though we have separate data and floating-point stacks; The separate
 3953: notation can be generated easily from the unified notation.}: The number
 3954: of items popped from and pushed on the stack, their type, and by what
 3955: name they are referred to in the C code. It then generates a C code
 3956: prelude and postlude for each primitive. The final C code for @code{+}
 3957: looks like this:
 3958: 
 3959: @example
 3960: I_plus:	/* + ( n1 n2 -- n ) */  /* label, stack effect */
 3961: /*  */                          /* documentation */
 3962: @{
 3963: DEF_CA                          /* definition of variable ca (indirect threading) */
 3964: Cell n1;                        /* definitions of variables */
 3965: Cell n2;
 3966: Cell n;
 3967: n1 = (Cell) sp[1];              /* input */
 3968: n2 = (Cell) TOS;
 3969: sp += 1;                        /* stack adjustment */
 3970: NAME("+")                       /* debugging output (with -DDEBUG) */
 3971: @{
 3972: n = n1+n2;                      /* C code taken from the source */
 3973: @}
 3974: NEXT_P1;                        /* NEXT part 1 */
 3975: TOS = (Cell)n;                  /* output */
 3976: NEXT_P2;                        /* NEXT part 2 */
 3977: @}
 3978: @end example
 3979: 
 3980: This looks long and inefficient, but the GNU C compiler optimizes quite
 3981: well and produces optimal code for @code{+} on, e.g., the R3000 and the
 3982: HP RISC machines: Defining the @code{n}s does not produce any code, and
 3983: using them as intermediate storage also adds no cost.
 3984: 
 3985: There are also other optimizations, that are not illustrated by this
 3986: example: Assignments between simple variables are usually for free (copy
 3987: propagation). If one of the stack items is not used by the primitive
 3988: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
 3989: (dead code elimination). On the other hand, there are some things that
 3990: the compiler does not do, therefore they are performed by
 3991: @file{prims2x.fs}: The compiler does not optimize code away that stores
 3992: a stack item to the place where it just came from (e.g., @code{over}).
 3993: 
 3994: While programming a primitive is usually easy, there are a few cases
 3995: where the programmer has to take the actions of the generator into
 3996: account, most notably @code{?dup}, but also words that do not (always)
 3997: fall through to NEXT.
 3998: 
 3999: @node TOS Optimization, Produced code, Automatic Generation, Primitives
 4000: @subsection TOS Optimization
 4001: 
 4002: An important optimization for stack machine emulators, e.g., Forth
 4003: engines, is keeping  one or more of the top stack items in
 4004: registers.  If a word has the stack effect @var{in1}...@var{inx} @code{--}
 4005: @var{out1}...@var{outy}, keeping the top @var{n} items in registers
 4006: @itemize @bullet
 4007: @item
 4008: is better than keeping @var{n-1} items, if @var{x>=n} and @var{y>=n},
 4009: due to fewer loads from and stores to the stack.
 4010: @item is slower than keeping @var{n-1} items, if @var{x<>y} and @var{x<n} and
 4011: @var{y<n}, due to additional moves between registers.
 4012: @end itemize
 4013: 
 4014: In particular, keeping one item in a register is never a disadvantage,
 4015: if there are enough registers. Keeping two items in registers is a
 4016: disadvantage for frequent words like @code{?branch}, constants,
 4017: variables, literals and @code{i}. Therefore our generator only produces
 4018: code that keeps zero or one items in registers. The generated C code
 4019: covers both cases; the selection between these alternatives is made at
 4020: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
 4021: code for @code{+} is just a simple variable name in the one-item case,
 4022: otherwise it is a macro that expands into @code{sp[0]}. Note that the
 4023: GNU C compiler tries to keep simple variables like @code{TOS} in
 4024: registers, and it usually succeeds, if there are enough registers.
 4025: 
 4026: The primitive generator performs the TOS optimization for the
 4027: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
 4028: operations the benefit of this optimization is even larger:
 4029: floating-point operations take quite long on most processors, but can be
 4030: performed in parallel with other operations as long as their results are
 4031: not used. If the FP-TOS is kept in a register, this works. If
 4032: it is kept on the stack, i.e., in memory, the store into memory has to
 4033: wait for the result of the floating-point operation, lengthening the
 4034: execution time of the primitive considerably.
 4035: 
 4036: The TOS optimization makes the automatic generation of primitives a
 4037: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
 4038: @code{TOS} is not sufficient. There are some special cases to
 4039: consider:
 4040: @itemize @bullet
 4041: @item In the case of @code{dup ( w -- w w )} the generator must not
 4042: eliminate the store to the original location of the item on the stack,
 4043: if the TOS optimization is turned on.
 4044: @item Primitives with stack effects of the form @code{--}
 4045: @var{out1}...@var{outy} must store the TOS to the stack at the start.
 4046: Likewise, primitives with the stack effect @var{in1}...@var{inx} @code{--}
 4047: must load the TOS from the stack at the end. But for the null stack
 4048: effect @code{--} no stores or loads should be generated.
 4049: @end itemize
 4050: 
 4051: @node Produced code,  , TOS Optimization, Primitives
 4052: @subsection Produced code
 4053: 
 4054: To see what assembly code is produced for the primitives on your machine
 4055: with your compiler and your flag settings, type @code{make engine.s} and
 4056: look at the resulting file @file{engine.s}.
 4057: 
 4058: @node System Architecture, Performance, Primitives, Internals
 4059: @section System Architecture
 4060: 
 4061: Our Forth system consists not only of primitives, but also of
 4062: definitions written in Forth. Since the Forth compiler itself belongs
 4063: to those definitions, it is not possible to start the system with the
 4064: primitives and the Forth source alone. Therefore we provide the Forth
 4065: code as an image file in nearly executable form. At the start of the
 4066: system a C routine loads the image file into memory, sets up the
 4067: memory (stacks etc.) according to information in the image file, and
 4068: starts executing Forth code.
 4069: 
 4070: The image file format is a compromise between the goals of making it
 4071: easy to generate image files and making them portable. The easiest way
 4072: to generate an image file is to just generate a memory dump. However,
 4073: this kind of image file cannot be used on a different machine, or on
 4074: the next version of the engine on the same machine, it even might not
 4075: work with the same engine compiled by a different version of the C
 4076: compiler. We would like to have as few versions of the image file as
 4077: possible, because we do not want to distribute many versions of the
 4078: same image file, and to make it easy for the users to use their image
 4079: files on many machines. We currently need to create a different image
 4080: file for machines with different cell sizes and different byte order
 4081: (little- or big-endian)@footnote{We are considering adding information to the
 4082: image file that enables the loader to change the byte order.}.
 4083: 
 4084: Forth code that is going to end up in a portable image file has to
 4085: comply to some restrictions: addresses have to be stored in memory with
 4086: special words (@code{A!}, @code{A,}, etc.) in order to make the code
 4087: relocatable. Cells, floats, etc., have to be stored at the natural
 4088: alignment boundaries@footnote{E.g., store floats (8 bytes) at an address
 4089: dividable by~8. This happens automatically in our system when you use
 4090: the ANS Forth alignment words.}, in order to avoid alignment faults on
 4091: machines with stricter alignment. The image file is produced by a
 4092: metacompiler (@file{cross.fs}).
 4093: 
 4094: So, unlike the image file of Mitch Bradleys @code{cforth}, our image
 4095: file is not directly executable, but has to undergo some manipulations
 4096: during loading. Address relocation is performed at image load-time, not
 4097: at run-time. The loader also has to replace tokens standing for
 4098: primitive calls with the appropriate code-field addresses (or code
 4099: addresses in the case of direct threading).
 4100: 
 4101: @node  Performance,  , System Architecture, Internals
 4102: @section Performance
 4103: 
 4104: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
 4105: impossible to write a significantly faster engine.
 4106: 
 4107: On register-starved machines like the 386 architecture processors
 4108: improvements are possible, because @code{gcc} does not utilize the
 4109: registers as well as a human, even with explicit register declarations;
 4110: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
 4111: and hand-tuned it for the 486; this system is 1.19 times faster on the
 4112: Sieve benchmark on a 486DX2/66 than Gforth compiled with
 4113: @code{gcc-2.6.3} with @code{-DFORCE_REG}.
 4114: 
 4115: However, this potential advantage of assembly language implementations
 4116: is not necessarily realized in complete Forth systems: We compared
 4117: Gforth (direct threaded, compiled with @code{gcc-2.6.3} and
 4118: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
 4119: 1994) and Eforth (with and without peephole (aka pinhole) optimization
 4120: of the threaded code); all these systems were written in assembly
 4121: language. We also compared Gforth with three systems written in C:
 4122: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
 4123: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
 4124: -DUNROLL_NEXT}), ThisForth Beta (compiled with gcc-2.6.3 -O3
 4125: -fomit-frame-pointer; ThisForth employs peephole optimization of the
 4126: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
 4127: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
 4128: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
 4129: 486DX2/66 with similar memory performance under Windows NT. Marcel
 4130: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
 4131: added the peephole optimizer, ran the benchmarks and reported the
 4132: results.
 4133:  
 4134: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
 4135: matrix multiplication come from the Stanford integer benchmarks and have
 4136: been translated into Forth by Martin Fraeman; we used the versions
 4137: included in the TILE Forth package, but with bigger data set sizes; and
 4138: a recursive Fibonacci number computation for benchmarking calling
 4139: performance. The following table shows the time taken for the benchmarks
 4140: scaled by the time taken by Gforth (in other words, it shows the speedup
 4141: factor that Gforth achieved over the other systems).
 4142: 
 4143: @example
 4144: relative      Win32-    NT       eforth       This-
 4145:   time  Gforth Forth Forth eforth  +opt   PFE Forth  TILE
 4146: sieve     1.00  1.39  1.14   1.39  0.85  1.58  3.18  8.58
 4147: bubble    1.00  1.31  1.41   1.48  0.88  1.50        3.88
 4148: matmul    1.00  1.47  1.35   1.46  1.16  1.58        4.09
 4149: fib       1.00  1.52  1.34   1.22  1.13  1.74  2.99  4.30
 4150: @end example
 4151: 
 4152: You may find the good performance of Gforth compared with the systems
 4153: written in assembly language quite surprising. One important reason for
 4154: the disappointing performance of these systems is probably that they are
 4155: not written optimally for the 486 (e.g., they use the @code{lods}
 4156: instruction). In addition, Win32Forth uses a comfortable, but costly
 4157: method for relocating the Forth image: like @code{cforth}, it computes
 4158: the actual addresses at run time, resulting in two address computations
 4159: per NEXT (@pxref{System Architecture}).
 4160: 
 4161: Only Eforth with the peephole optimizer performs comparable to
 4162: Gforth. The speedups achieved with peephole optimization of threaded
 4163: code are quite remarkable. Adding a peephole optimizer to Gforth should
 4164: cause similar speedups.
 4165: 
 4166: The speedup of Gforth over PFE, ThisForth and TILE can be easily
 4167: explained with the self-imposed restriction to standard C, which makes
 4168: efficient threading impossible (however, the measured implementation of
 4169: PFE uses a GNU C extension: @ref{Global Reg Vars, , Defining Global
 4170: Register Variables, gcc.info, GNU C Manual}).  Moreover, current C
 4171: compilers have a hard time optimizing other aspects of the ThisForth
 4172: and the TILE source.
 4173: 
 4174: Note that the performance of Gforth on 386 architecture processors
 4175: varies widely with the version of @code{gcc} used. E.g., @code{gcc-2.5.8}
 4176: failed to allocate any of the virtual machine registers into real
 4177: machine registers by itself and would not work correctly with explicit
 4178: register declarations, giving a 1.3 times slower engine (on a 486DX2/66
 4179: running the Sieve) than the one measured above.
 4180: 
 4181: In @cite{Translating Forth to Efficient C} by M. Anton Ertl and Martin
 4182: Maierhofer (presented at EuroForth '95), an indirect threaded version of
 4183: Gforth is compared with Win32Forth, NT Forth, PFE, and ThisForth; that
 4184: version of Gforth is 2\%@minus{}8\% slower on a 486 than the version
 4185: used here. The paper available at
 4186: @*@file{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz};
 4187: it also contains numbers for some native code systems. You can find
 4188: numbers for Gforth on various machines in @file{Benchres}.
 4189: 
 4190: @node Bugs, Origin, Internals, Top
 4191: @chapter Bugs
 4192: 
 4193: Known bugs are described in the file BUGS in the Gforth distribution.
 4194: 
 4195: If you find a bug, please send a bug report to
 4196: @code{bug-gforth@@gnu.ai.mit.edu}. A bug report should
 4197: describe the Gforth version used (it is announced at the start of an
 4198: interactive Gforth session), the machine and operating system (on Unix
 4199: systems you can use @code{uname -a} to produce this information), the
 4200: installation options (send the @code{config.status} file), and a
 4201: complete list of changes you (or your installer) have made to the Gforth
 4202: sources (if any); it should contain a program (or a sequence of keyboard
 4203: commands) that reproduces the bug and a description of what you think
 4204: constitutes the buggy behaviour.
 4205: 
 4206: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
 4207: to Report Bugs, gcc.info, GNU C Manual}.
 4208: 
 4209: 
 4210: @node Origin, Word Index, Bugs, Top
 4211: @chapter Authors and Ancestors of Gforth
 4212: 
 4213: @section Authors and Contributors
 4214: 
 4215: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
 4216: Ertl. The third major author was Jens Wilke.  Lennart Benschop (who was
 4217: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
 4218: with their continuous feedback. Lennart Benshop contributed
 4219: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
 4220: support for calling C libraries. Helpful comments also came from Paul
 4221: Kleinrubatscher, Christian Pirker, Dirk Zoller and Marcel Hendrix.
 4222: 
 4223: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
 4224: and autoconf, among others), and to the creators of the Internet: Gforth
 4225: was developed across the Internet, and its authors have not met
 4226: physically yet.
 4227: 
 4228: @section Pedigree
 4229: 
 4230: Gforth descends from BigForth (1993) and fig-Forth. Gforth and PFE (by
 4231: Dirk Zoller) will cross-fertilize each other. Of course, a significant
 4232: part of the design of Gforth was prescribed by ANS Forth.
 4233: 
 4234: Bernd Paysan wrote BigForth, a descendent from TurboForth, an unreleased
 4235: 32 bit native code version of VolksForth for the Atari ST, written
 4236: mostly by Dietrich Weineck.
 4237: 
 4238: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
 4239: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
 4240: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
 4241: 
 4242: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
 4243: Forth-83 standard. !! Pedigree? When?
 4244: 
 4245: A team led by Bill Ragsdale implemented fig-Forth on many processors in
 4246: 1979. Robert Selzer and Bill Ragsdale developed the original
 4247: implementation of fig-Forth for the 6502 based on microForth.
 4248: 
 4249: The principal architect of microForth was Dean Sanderson. microForth was
 4250: FORTH, Inc.'s first off-the-shelf product. It was developped in 1976 for
 4251: the 1802, and subsequently implemented on the 8080, the 6800 and the
 4252: Z80.
 4253: 
 4254: All earlier Forth systems were custom-made, usually by Charles Moore,
 4255: who discovered (as he puts it) Forth during the late 60s. The first full
 4256: Forth existed in 1971.
 4257: 
 4258: A part of the information in this section comes from @cite{The Evolution
 4259: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
 4260: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
 4261: Notices 28(3), 1993.  You can find more historical and genealogical
 4262: information about Forth there.
 4263: 
 4264: @node Word Index, Node Index, Origin, Top
 4265: @chapter Word Index
 4266: 
 4267: This index is as incomplete as the manual. Each word is listed with
 4268: stack effect and wordset.
 4269: 
 4270: @printindex fn
 4271: 
 4272: @node Node Index,  , Word Index, Top
 4273: @chapter Node Index
 4274: 
 4275: This index is even less complete than the manual.
 4276: 
 4277: @contents
 4278: @bye
 4279: 

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