File:  [gforth] / gforth / Attic / gforth.ds
Revision 1.47: download - view: text, annotated - select for diffs
Thu Mar 20 14:39:50 1997 UTC (27 years ago) by anton
Branches: MAIN
CVS tags: v0-3-0, HEAD
fixed a few Makefile bugs (make clean)
renamed blocks.fs:flush-file into flush-blocks
fixed bell bug (now flushes the output)
documentation changes

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

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