File:  [gforth] / gforth / Attic / gforth.ds
Revision 1.24: download - view: text, annotated - select for diffs
Wed Nov 15 17:29:07 1995 UTC (28 years, 5 months ago) by anton
Branches: MAIN
CVS tags: HEAD
fixed a bug in the unit conversion in main.c
"make bench" now also works on 64-bit machines
documentation improvements

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

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