File:  [gforth] / gforth / Attic / gforth.ds
Revision 1.46: download - view: text, annotated - select for diffs
Wed Mar 19 18:27:15 1997 UTC (27 years, 1 month ago) by anton
Branches: MAIN
CVS tags: HEAD
fixed some documentation bugs
updated dates on copyright messages
updated NEWS
some fixes in Makefile.in

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

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