File:  [gforth] / gforth / Attic / gforth.ds
Revision 1.16: download - view: text, annotated - select for diffs
Sat Jun 3 14:24:42 1995 UTC (25 years, 10 months ago) by anton
Branches: MAIN
CVS tags: HEAD
replaced Bernds solution for the path searching problem with mine.
Use different register declarations for Intel depending on compiler version
Updated bug list
added GNU-convention make target check

    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
    5: @settitle GNU Forth Manual
    6: @comment @setchapternewpage odd
    7: @comment %**end of header (This is for running Texinfo on a region.)
    9: @ifinfo
   10: This file documents GNU Forth 0.0
   12: Copyright @copyright{} 1994 GNU Forth Development Group
   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.
   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).
   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.
   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
   39: @titlepage
   40: @sp 10
   41: @center @titlefont{GNU Forth Manual}
   42: @sp 2
   43: @center for version 0.0
   44: @sp 2
   45: @center Anton Ertl
   47: @comment  The following two commands start the copyright page.
   48: @page
   49: @vskip 0pt plus 1filll
   50: Copyright @copyright{} 1994 GNU Forth Development Group
   52: @comment !! Published by ... or You can get a copy of this manual ...
   54:      Permission is granted to make and distribute verbatim copies of
   55:      this manual provided the copyright notice and this permission notice
   56:      are preserved on all copies.
   58:      Permission is granted to copy and distribute modified versions of this
   59:      manual under the conditions for verbatim copying, provided also that the
   60:      sections entitled "Distribution" and "General Public License" are
   61:      included exactly as in the original, and provided that the entire
   62:      resulting derived work is distributed under the terms of a permission
   63:      notice identical to this one.
   65:      Permission is granted to copy and distribute translations of this manual
   66:      into another language, under the above conditions for modified versions,
   67:      except that the sections entitled "Distribution" and "General Public
   68:      License" may be included in a translation approved by the author instead
   69:      of in the original English.
   70: @end titlepage
   73: @node Top, License, (dir), (dir)
   74: @ifinfo
   75: GNU Forth is a free implementation of ANS Forth available on many
   76: personal machines. This manual corresponds to version 0.0.
   77: @end ifinfo
   79: @menu
   80: * License::                     
   81: * Goals::                       About the GNU Forth Project
   82: * Other Books::                 Things you might want to read
   83: * Invocation::                  Starting GNU Forth
   84: * Words::                       Forth words available in GNU Forth
   85: * ANS conformance::             Implementation-defined options etc.
   86: * Model::                       The abstract machine of GNU Forth
   87: * Emacs and GForth::            The GForth Mode
   88: * Internals::                   Implementation details
   89: * Bugs::                        How to report them
   90: * Pedigree::                    Ancestors of GNU Forth
   91: * Word Index::                  An item for each Forth word
   92: * Node Index::                  An item for each node
   93: @end menu
   95: @node License, Goals, Top, Top
   96: @unnumbered License
   97: !! Insert GPL here
   99: @iftex
  100: @unnumbered Preface
  101: This manual documents GNU Forth. The reader is expected to know
  102: Forth. This manual is primarily a reference manual. @xref{Other Books}
  103: for introductory material.
  104: @end iftex
  106: @node    Goals, Other Books, License, Top
  107: @comment node-name,     next,           previous, up
  108: @chapter Goals of GNU Forth
  109: @cindex Goals
  110: The goal of the GNU Forth Project is to develop a standard model for
  111: ANSI Forth. This can be split into several subgoals:
  113: @itemize @bullet
  114: @item
  115: GNU Forth should conform to the ANSI Forth standard.
  116: @item
  117: It should be a model, i.e. it should define all the
  118: implementation-dependent things.
  119: @item
  120: It should become standard, i.e. widely accepted and used. This goal
  121: is the most difficult one.
  122: @end itemize
  124: To achieve these goals GNU Forth should be
  125: @itemize @bullet
  126: @item
  127: Similar to previous models (fig-Forth, F83)
  128: @item
  129: Powerful. It should provide for all the things that are considered
  130: necessary today and even some that are not yet considered necessary.
  131: @item
  132: Efficient. It should not get the reputation of being exceptionally
  133: slow.
  134: @item
  135: Free.
  136: @item
  137: Available on many machines/easy to port.
  138: @end itemize
  140: Have we achieved these goals? GNU Forth conforms to the ANS Forth
  141: standard; it may be considered a model, but we have not yet documented
  142: which parts of the model are stable and which parts we are likely to
  143: change; it certainly has not yet become a de facto standard. It has some
  144: similarities and some differences to previous models; It has some
  145: powerful features, but not yet everything that we envisioned; on RISCs
  146: it is as fast as interpreters programmed in assembly, on
  147: register-starved machines it is not so fast, but still faster than any
  148: other C-based interpretive implementation; it is free and available on
  149: many machines.
  151: @node Other Books, Invocation, Goals, Top
  152: @chapter Other books on ANS Forth
  154: As the standard is relatively new, there are not many books out yet. It
  155: is not recommended to learn Forth by using GNU Forth and a book that is
  156: not written for ANS Forth, as you will not know your mistakes from the
  157: deviations of the book.
  159: There is, of course, the standard, the definite reference if you want to
  160: write ANS Forth programs. It will be available in printed form from
  161: Global Engineering Documents !! somtime in spring or summer 1994. If you
  162: are lucky, you can still get dpANS6 (the draft that was approved as
  163: standard) by aftp from
  165: @cite{Forth: The new model} by Jack Woehr (!! Publisher) is an
  166: introductory book based on a draft version of the standard. It does not
  167: cover the whole standard. It also contains interesting background
  168: information (Jack Woehr was in the ANS Forth Technical Committe). It is
  169: not appropriate for complete newbies, but programmers experienced in
  170: other languages should find it ok.
  172: @node Invocation, Words, Other Books, Top
  173: @chapter Invocation
  175: You will usually just say @code{gforth}. In many other cases the default
  176: GNU Forth image will be invoked like this:
  178: @example
  179: gforth [files] [-e forth-code]
  180: @end example
  182: executing the contents of the files and the Forth code in the order they
  183: are given.
  185: In general, the command line looks like this:
  187: @example
  188: gforth [initialization options] [image-specific options]
  189: @end example
  191: The initialization options must come before the rest of the command
  192: line. They are:
  194: @table @code
  195: @item --image-file @var{file}
  196: Loads the Forth image @var{file} instead of the default
  197: @file{}.
  199: @item --path @var{path}
  200: Uses @var{path} for searching the image file and Forth source code
  201: files instead of the default in the environment variable
  202: @code{GFORTHPATH} or the path specified at installation time (typically
  203: @file{/usr/local/lib/gforth:.}). A path is given as a @code{:}-separated
  204: list.
  206: @item --dictionary-size @var{size}
  207: @item -m @var{size}
  208: Allocate @var{size} space for the Forth dictionary space instead of
  209: using the default specified in the image (typically 256K). The
  210: @var{size} specification consists of an integer and a unit (e.g.,
  211: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
  212: size, in this case Cells), @code{k} (kilobytes), and @code{M}
  213: (Megabytes). If no unit is specified, @code{e} is used.
  215: @item --data-stack-size @var{size}
  216: @item -d @var{size}
  217: Allocate @var{size} space for the data stack instead of using the
  218: default specified in the image (typically 16K).
  220: @item --return-stack-size @var{size}
  221: @item -r @var{size}
  222: Allocate @var{size} space for the return stack instead of using the
  223: default specified in the image (typically 16K).
  225: @item --fp-stack-size @var{size}
  226: @item -f @var{size}
  227: Allocate @var{size} space for the floating point stack instead of
  228: using the default specified in the image (typically 16K). In this case
  229: the unit specifier @code{e} refers to floating point numbers.
  231: @item --locals-stack-size @var{size}
  232: @item -l @var{size}
  233: Allocate @var{size} space for the locals stack instead of using the
  234: default specified in the image (typically 16K).
  236: @end table
  238: As explained above, the image-specific command-line arguments for the
  239: default image @file{} consist of a sequence of filenames and
  240: @code{-e @var{forth-code}} options that are interpreted in the seqence
  241: in which they are given. The @code{-e @var{forth-code}} or
  242: @code{--evaluate @var{forth-code}} option evaluates the forth
  243: code. This option takes only one argument; if you want to evaluate more
  244: Forth words, you have to quote them or use several @code{-e}s. To exit
  245: after processing the command line (instead of entering interactive mode)
  246: append @code{-e bye} to the command line.
  248: Not yet implemented:
  249: On startup the system first executes the system initialization file
  250: (unless the option @code{--no-init-file} is given; note that the system
  251: resulting from using this option may not be ANS Forth conformant). Then
  252: the user initialization file @file{.gforth.fs} is executed, unless the
  253: option @code{--no-rc} is given; this file is first searched in @file{.},
  254: then in @file{~}, then in the normal path (see above).
  256: @node Words, ANS conformance, Invocation, Top
  257: @chapter Forth Words
  259: @menu
  260: * Notation::                    
  261: * Arithmetic::                  
  262: * Stack Manipulation::          
  263: * Memory access::               
  264: * Control Structures::          
  265: * Locals::                      
  266: * Defining Words::              
  267: * Wordlists::                   
  268: * Files::                       
  269: * Blocks::                      
  270: * Other I/O::                   
  271: * Programming Tools::           
  272: * Threading Words::             
  273: @end menu
  275: @node Notation, Arithmetic, Words, Words
  276: @section Notation
  278: The Forth words are described in this section in the glossary notation
  279: that has become a de-facto standard for Forth texts, i.e.
  281: @format
  282: @var{word}     @var{Stack effect}   @var{wordset}   @var{pronunciation}
  283: @end format
  284: @var{Description}
  286: @table @var
  287: @item word
  288: The name of the word. BTW, GNU Forth is case insensitive, so you can
  289: type the words in in lower case (However, @pxref{core-idef}).
  291: @item Stack effect
  292: The stack effect is written in the notation @code{@var{before} --
  293: @var{after}}, where @var{before} and @var{after} describe the top of
  294: stack entries before and after the execution of the word. The rest of
  295: the stack is not touched by the word. The top of stack is rightmost,
  296: i.e., a stack sequence is written as it is typed in. Note that GNU Forth
  297: uses a separate floating point stack, but a unified stack
  298: notation. Also, return stack effects are not shown in @var{stack
  299: effect}, but in @var{Description}. The name of a stack item describes
  300: the type and/or the function of the item. See below for a discussion of
  301: the types.
  303: @item pronunciation
  304: How the word is pronounced
  306: @item wordset
  307: The ANS Forth standard is divided into several wordsets. A standard
  308: system need not support all of them. So, the fewer wordsets your program
  309: uses the more portable it will be in theory. However, we suspect that
  310: most ANS Forth systems on personal machines will feature all
  311: wordsets. Words that are not defined in the ANS standard have
  312: @code{gforth} as wordset.
  314: @item Description
  315: A description of the behaviour of the word.
  316: @end table
  318: The type of a stack item is specified by the character(s) the name
  319: starts with:
  321: @table @code
  322: @item f
  323: Bool, i.e. @code{false} or @code{true}.
  324: @item c
  325: Char
  326: @item w
  327: Cell, can contain an integer or an address
  328: @item n
  329: signed integer
  330: @item u
  331: unsigned integer
  332: @item d
  333: double sized signed integer
  334: @item ud
  335: double sized unsigned integer
  336: @item r
  337: Float
  338: @item a_
  339: Cell-aligned address
  340: @item c_
  341: Char-aligned address (note that a Char is two bytes in Windows NT)
  342: @item f_
  343: Float-aligned address
  344: @item df_
  345: Address aligned for IEEE double precision float
  346: @item sf_
  347: Address aligned for IEEE single precision float
  348: @item xt
  349: Execution token, same size as Cell
  350: @item wid
  351: Wordlist ID, same size as Cell
  352: @item f83name
  353: Pointer to a name structure
  354: @end table
  356: @node Arithmetic, Stack Manipulation, Notation, Words
  357: @section Arithmetic
  358: Forth arithmetic is not checked, i.e., you will not hear about integer
  359: overflow on addition or multiplication, you may hear about division by
  360: zero if you are lucky. The operator is written after the operands, but
  361: the operands are still in the original order. I.e., the infix @code{2-1}
  362: corresponds to @code{2 1 -}. Forth offers a variety of division
  363: operators. If you perform division with potentially negative operands,
  364: you do not want to use @code{/} or @code{/mod} with its undefined
  365: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
  366: former, @pxref{Mixed precision}).
  368: @menu
  369: * Single precision::            
  370: * Bitwise operations::          
  371: * Mixed precision::             operations with single and double-cell integers
  372: * Double precision::            Double-cell integer arithmetic
  373: * Floating Point::              
  374: @end menu
  376: @node Single precision, Bitwise operations, Arithmetic, Arithmetic
  377: @subsection Single precision
  378: doc-+
  379: doc--
  380: doc-*
  381: doc-/
  382: doc-mod
  383: doc-/mod
  384: doc-negate
  385: doc-abs
  386: doc-min
  387: doc-max
  389: @node Bitwise operations, Mixed precision, Single precision, Arithmetic
  390: @subsection Bitwise operations
  391: doc-and
  392: doc-or
  393: doc-xor
  394: doc-invert
  395: doc-2*
  396: doc-2/
  398: @node Mixed precision, Double precision, Bitwise operations, Arithmetic
  399: @subsection Mixed precision
  400: doc-m+
  401: doc-*/
  402: doc-*/mod
  403: doc-m*
  404: doc-um*
  405: doc-m*/
  406: doc-um/mod
  407: doc-fm/mod
  408: doc-sm/rem
  410: @node Double precision, Floating Point, Mixed precision, Arithmetic
  411: @subsection Double precision
  413: The outer (aka text) interpreter converts numbers containing a dot into
  414: a double precision number. Note that only numbers with the dot as last
  415: character are standard-conforming.
  417: doc-d+
  418: doc-d-
  419: doc-dnegate
  420: doc-dabs
  421: doc-dmin
  422: doc-dmax
  424: @node Floating Point,  , Double precision, Arithmetic
  425: @subsection Floating Point
  427: The format of floating point numbers recognized by the outer (aka text)
  428: interpreter is: a signed decimal number, possibly containing a decimal
  429: point (@code{.}), followed by @code{E} or @code{e}, optionally followed
  430: by a signed integer (the exponent). E.g., @code{1e} ist the same as
  431: @code{+1.0e+1}. Note that a number without @code{e}
  432: is not interpreted as floating-point number, but as double (if the
  433: number contains a @code{.}) or single precision integer. Also,
  434: conversions between string and floating point numbers always use base
  435: 10, irrespective of the value of @code{BASE}. If @code{BASE} contains a
  436: value greater then 14, the @code{E} may be interpreted as digit and the
  437: number will be interpreted as integer, unless it has a signed exponent
  438: (both @code{+} and @code{-} are allowed as signs).
  440: Angles in floating point operations are given in radians (a full circle
  441: has 2 pi radians). Note, that gforth has a separate floating point
  442: stack, but we use the unified notation.
  444: Floating point numbers have a number of unpleasant surprises for the
  445: unwary (e.g., floating point addition is not associative) and even a few
  446: for the wary. You should not use them unless you know what you are doing
  447: or you don't care that the results you get are totally bogus. If you
  448: want to learn about the problems of floating point numbers (and how to
  449: avoid them), you might start with @cite{David Goldberg, What Every
  450: Computer Scientist Should Know About Floating-Point Arithmetic, ACM
  451: Computing Surveys 23(1):5@minus{}48, March 1991}.
  453: doc-f+
  454: doc-f-
  455: doc-f*
  456: doc-f/
  457: doc-fnegate
  458: doc-fabs
  459: doc-fmax
  460: doc-fmin
  461: doc-floor
  462: doc-fround
  463: doc-f**
  464: doc-fsqrt
  465: doc-fexp
  466: doc-fexpm1
  467: doc-fln
  468: doc-flnp1
  469: doc-flog
  470: doc-falog
  471: doc-fsin
  472: doc-fcos
  473: doc-fsincos
  474: doc-ftan
  475: doc-fasin
  476: doc-facos
  477: doc-fatan
  478: doc-fatan2
  479: doc-fsinh
  480: doc-fcosh
  481: doc-ftanh
  482: doc-fasinh
  483: doc-facosh
  484: doc-fatanh
  486: @node Stack Manipulation, Memory access, Arithmetic, Words
  487: @section Stack Manipulation
  489: gforth has a data stack (aka parameter stack) for characters, cells,
  490: addresses, and double cells, a floating point stack for floating point
  491: numbers, a return stack for storing the return addresses of colon
  492: definitions and other data, and a locals stack for storing local
  493: variables. Note that while every sane Forth has a separate floating
  494: point stack, this is not strictly required; an ANS Forth system could
  495: theoretically keep floating point numbers on the data stack. As an
  496: additional difficulty, you don't know how many cells a floating point
  497: number takes. It is reportedly possible to write words in a way that
  498: they work also for a unified stack model, but we do not recommend trying
  499: it. Instead, just say that your program has an environmental dependency
  500: on a separate FP stack.
  502: Also, a Forth system is allowed to keep the local variables on the
  503: return stack. This is reasonable, as local variables usually eliminate
  504: the need to use the return stack explicitly. So, if you want to produce
  505: a standard complying program and if you are using local variables in a
  506: word, forget about return stack manipulations in that word (see the
  507: standard document for the exact rules).
  509: @menu
  510: * Data stack::                  
  511: * Floating point stack::        
  512: * Return stack::                
  513: * Locals stack::                
  514: * Stack pointer manipulation::  
  515: @end menu
  517: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
  518: @subsection Data stack
  519: doc-drop
  520: doc-nip
  521: doc-dup
  522: doc-over
  523: doc-tuck
  524: doc-swap
  525: doc-rot
  526: doc--rot
  527: doc-?dup
  528: doc-pick
  529: doc-roll
  530: doc-2drop
  531: doc-2nip
  532: doc-2dup
  533: doc-2over
  534: doc-2tuck
  535: doc-2swap
  536: doc-2rot
  538: @node Floating point stack, Return stack, Data stack, Stack Manipulation
  539: @subsection Floating point stack
  540: doc-fdrop
  541: doc-fnip
  542: doc-fdup
  543: doc-fover
  544: doc-ftuck
  545: doc-fswap
  546: doc-frot
  548: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
  549: @subsection Return stack
  550: doc->r
  551: doc-r>
  552: doc-r@
  553: doc-rdrop
  554: doc-2>r
  555: doc-2r>
  556: doc-2r@
  557: doc-2rdrop
  559: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
  560: @subsection Locals stack
  562: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
  563: @subsection Stack pointer manipulation
  564: doc-sp@
  565: doc-sp!
  566: doc-fp@
  567: doc-fp!
  568: doc-rp@
  569: doc-rp!
  570: doc-lp@
  571: doc-lp!
  573: @node Memory access, Control Structures, Stack Manipulation, Words
  574: @section Memory access
  576: @menu
  577: * Stack-Memory transfers::      
  578: * Address arithmetic::          
  579: * Memory block access::         
  580: @end menu
  582: @node Stack-Memory transfers, Address arithmetic, Memory access, Memory access
  583: @subsection Stack-Memory transfers
  585: doc-@
  586: doc-!
  587: doc-+!
  588: doc-c@
  589: doc-c!
  590: doc-2@
  591: doc-2!
  592: doc-f@
  593: doc-f!
  594: doc-sf@
  595: doc-sf!
  596: doc-df@
  597: doc-df!
  599: @node Address arithmetic, Memory block access, Stack-Memory transfers, Memory access
  600: @subsection Address arithmetic
  602: ANS Forth does not specify the sizes of the data types. Instead, it
  603: offers a number of words for computing sizes and doing address
  604: arithmetic. Basically, address arithmetic is performed in terms of
  605: address units (aus); on most systems the address unit is one byte. Note
  606: that a character may have more than one au, so @code{chars} is no noop
  607: (on systems where it is a noop, it compiles to nothing).
  609: ANS Forth also defines words for aligning addresses for specific
  610: addresses. Many computers require that accesses to specific data types
  611: must only occur at specific addresses; e.g., that cells may only be
  612: accessed at addresses divisible by 4. Even if a machine allows unaligned
  613: accesses, it can usually perform aligned accesses faster. 
  615: For the performance-concious: alignment operations are usually only
  616: necessary during the definition of a data structure, not during the
  617: (more frequent) accesses to it.
  619: ANS Forth defines no words for character-aligning addresses. This is not
  620: an oversight, but reflects the fact that addresses that are not
  621: char-aligned have no use in the standard and therefore will not be
  622: created.
  624: The standard guarantees that addresses returned by @code{CREATE}d words
  625: are cell-aligned; in addition, gforth guarantees that these addresses
  626: are aligned for all purposes.
  628: Note that the standard defines a word @code{char}, which has nothing to
  629: do with address arithmetic.
  631: doc-chars
  632: doc-char+
  633: doc-cells
  634: doc-cell+
  635: doc-align
  636: doc-aligned
  637: doc-floats
  638: doc-float+
  639: doc-falign
  640: doc-faligned
  641: doc-sfloats
  642: doc-sfloat+
  643: doc-sfalign
  644: doc-sfaligned
  645: doc-dfloats
  646: doc-dfloat+
  647: doc-dfalign
  648: doc-dfaligned
  649: doc-maxalign
  650: doc-maxaligned
  651: doc-cfalign
  652: doc-cfaligned
  653: doc-address-unit-bits
  655: @node Memory block access,  , Address arithmetic, Memory access
  656: @subsection Memory block access
  658: doc-move
  659: doc-erase
  661: While the previous words work on address units, the rest works on
  662: characters.
  664: doc-cmove
  665: doc-cmove>
  666: doc-fill
  667: doc-blank
  669: @node Control Structures, Locals, Memory access, Words
  670: @section Control Structures
  672: Control structures in Forth cannot be used in interpret state, only in
  673: compile state, i.e., in a colon definition. We do not like this
  674: limitation, but have not seen a satisfying way around it yet, although
  675: many schemes have been proposed.
  677: @menu
  678: * Selection::                   
  679: * Simple Loops::                
  680: * Counted Loops::               
  681: * Arbitrary control structures::  
  682: * Calls and returns::           
  683: * Exception Handling::          
  684: @end menu
  686: @node Selection, Simple Loops, Control Structures, Control Structures
  687: @subsection Selection
  689: @example
  690: @var{flag}
  691: IF
  692:   @var{code}
  693: ENDIF
  694: @end example
  695: or
  696: @example
  697: @var{flag}
  698: IF
  699:   @var{code1}
  700: ELSE
  701:   @var{code2}
  702: ENDIF
  703: @end example
  705: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
  706: standard, and @code{ENDIF} is not, although it is quite popular. We
  707: recommend using @code{ENDIF}, because it is less confusing for people
  708: who also know other languages (and is not prone to reinforcing negative
  709: prejudices against Forth in these people). Adding @code{ENDIF} to a
  710: system that only supplies @code{THEN} is simple:
  711: @example
  712: : endif   POSTPONE then ; immediate
  713: @end example
  715: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
  716: (adv.)}  has the following meanings:
  717: @quotation
  718: ... 2b: following next after in order ... 3d: as a necessary consequence
  719: (if you were there, then you saw them).
  720: @end quotation
  721: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
  722: and many other programming languages has the meaning 3d.]
  724: We also provide the words @code{?dup-if} and @code{?dup-0=-if}, so you
  725: can avoid using @code{?dup}.
  727: @example
  728: @var{n}
  729: CASE
  730:   @var{n1} OF @var{code1} ENDOF
  731:   @var{n2} OF @var{code2} ENDOF
  732:   @dots{}
  733: ENDCASE
  734: @end example
  736: Executes the first @var{codei}, where the @var{ni} is equal to
  737: @var{n}. A default case can be added by simply writing the code after
  738: the last @code{ENDOF}. It may use @var{n}, which is on top of the stack,
  739: but must not consume it.
  741: @node Simple Loops, Counted Loops, Selection, Control Structures
  742: @subsection Simple Loops
  744: @example
  745: BEGIN
  746:   @var{code1}
  747:   @var{flag}
  748: WHILE
  749:   @var{code2}
  750: REPEAT
  751: @end example
  753: @var{code1} is executed and @var{flag} is computed. If it is true,
  754: @var{code2} is executed and the loop is restarted; If @var{flag} is false, execution continues after the @code{REPEAT}.
  756: @example
  757: BEGIN
  758:   @var{code}
  759:   @var{flag}
  760: UNTIL
  761: @end example
  763: @var{code} is executed. The loop is restarted if @code{flag} is false.
  765: @example
  766: BEGIN
  767:   @var{code}
  768: AGAIN
  769: @end example
  771: This is an endless loop.
  773: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
  774: @subsection Counted Loops
  776: The basic counted loop is:
  777: @example
  778: @var{limit} @var{start}
  779: ?DO
  780:   @var{body}
  781: LOOP
  782: @end example
  784: This performs one iteration for every integer, starting from @var{start}
  785: and up to, but excluding @var{limit}. The counter, aka index, can be
  786: accessed with @code{i}. E.g., the loop
  787: @example
  788: 10 0 ?DO
  789:   i .
  790: LOOP
  791: @end example
  792: prints
  793: @example
  794: 0 1 2 3 4 5 6 7 8 9
  795: @end example
  796: The index of the innermost loop can be accessed with @code{i}, the index
  797: of the next loop with @code{j}, and the index of the third loop with
  798: @code{k}.
  800: The loop control data are kept on the return stack, so there are some
  801: restrictions on mixing return stack accesses and counted loop
  802: words. E.g., if you put values on the return stack outside the loop, you
  803: cannot read them inside the loop. If you put values on the return stack
  804: within a loop, you have to remove them before the end of the loop and
  805: before accessing the index of the loop.
  807: There are several variations on the counted loop:
  809: @code{LEAVE} leaves the innermost counted loop immediately.
  811: @code{LOOP} can be replaced with @code{@var{n} +LOOP}; this updates the
  812: index by @var{n} instead of by 1. The loop is terminated when the border
  813: between @var{limit-1} and @var{limit} is crossed. E.g.:
  815: @code{4 0 ?DO  i .  2 +LOOP}   prints @code{0 2}
  817: @code{4 1 ?DO  i .  2 +LOOP}   prints @code{1 3}
  819: The behaviour of @code{@var{n} +LOOP} is peculiar when @var{n} is negative:
  821: @code{-1 0 ?DO  i .  -1 +LOOP}  prints @code{0 -1}
  823: @code{ 0 0 ?DO  i .  -1 +LOOP}  prints nothing
  825: Therefore we recommend avoiding using @code{@var{n} +LOOP} with negative
  826: @var{n}. One alternative is @code{@var{n} S+LOOP}, where the negative
  827: case behaves symmetrical to the positive case:
  829: @code{-2 0 ?DO  i .  -1 S+LOOP}  prints @code{0 -1}
  831: @code{-1 0 ?DO  i .  -1 S+LOOP}  prints @code{0}
  833: @code{ 0 0 ?DO  i .  -1 S+LOOP}  prints nothing
  835: The loop is terminated when the border between @var{limit@minus{}sgn(n)} and
  836: @var{limit} is crossed. However, @code{S+LOOP} is not part of the ANS
  837: Forth standard.
  839: @code{?DO} can be replaced by @code{DO}. @code{DO} enters the loop even
  840: when the start and the limit value are equal. We do not recommend using
  841: @code{DO}. It will just give you maintenance troubles.
  843: @code{UNLOOP} is used to prepare for an abnormal loop exit, e.g., via
  844: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
  845: return stack so @code{EXIT} can get to its return address.
  847: Another counted loop is
  848: @example
  849: @var{n}
  850: FOR
  851:   @var{body}
  852: NEXT
  853: @end example
  854: This is the preferred loop of native code compiler writers who are too
  855: lazy to optimize @code{?DO} loops properly. In GNU Forth, this loop
  856: iterates @var{n+1} times; @code{i} produces values starting with @var{n}
  857: and ending with 0. Other Forth systems may behave differently, even if
  858: they support @code{FOR} loops.
  860: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
  861: @subsection Arbitrary control structures
  863: ANS Forth permits and supports using control structures in a non-nested
  864: way. Information about incomplete control structures is stored on the
  865: control-flow stack. This stack may be implemented on the Forth data
  866: stack, and this is what we have done in gforth.
  868: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
  869: entry represents a backward branch target. A few words are the basis for
  870: building any control structure possible (except control structures that
  871: need storage, like calls, coroutines, and backtracking).
  873: doc-if
  874: doc-ahead
  875: doc-then
  876: doc-begin
  877: doc-until
  878: doc-again
  879: doc-cs-pick
  880: doc-cs-roll
  882: On many systems control-flow stack items take one word, in gforth they
  883: currently take three (this may change in the future). Therefore it is a
  884: really good idea to manipulate the control flow stack with
  885: @code{cs-pick} and @code{cs-roll}, not with data stack manipulation
  886: words.
  888: Some standard control structure words are built from these words:
  890: doc-else
  891: doc-while
  892: doc-repeat
  894: Counted loop words constitute a separate group of words:
  896: doc-?do
  897: doc-do
  898: doc-for
  899: doc-loop
  900: doc-s+loop
  901: doc-+loop
  902: doc-next
  903: doc-leave
  904: doc-?leave
  905: doc-unloop
  906: doc-done
  908: The standard does not allow using @code{cs-pick} and @code{cs-roll} on
  909: @i{do-sys}. Our system allows it, but it's your job to ensure that for
  910: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
  911: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
  912: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
  913: resolved (by using one of the loop-ending words or @code{DONE}).
  915: Another group of control structure words are
  917: doc-case
  918: doc-endcase
  919: doc-of
  920: doc-endof
  922: @i{case-sys} and @i{of-sys} cannot be processed using @code{cs-pick} and
  923: @code{cs-roll}.
  925: @subsubsection Programming Style
  927: In order to ensure readability we recommend that you do not create
  928: arbitrary control structures directly, but define new control structure
  929: words for the control structure you want and use these words in your
  930: program.
  932: E.g., instead of writing
  934: @example
  935: begin
  936:   ...
  937: if [ 1 cs-roll ]
  938:   ...
  939: again then
  940: @end example
  942: we recommend defining control structure words, e.g.,
  944: @example
  945: : while ( dest -- orig dest )
  946:  POSTPONE if
  947:  1 cs-roll ; immediate
  949: : repeat ( orig dest -- )
  950:  POSTPONE again
  951:  POSTPONE then ; immediate
  952: @end example
  954: and then using these to create the control structure:
  956: @example
  957: begin
  958:   ...
  959: while
  960:   ...
  961: repeat
  962: @end example
  964: That's much easier to read, isn't it? Of course, @code{BEGIN} and
  965: @code{WHILE} are predefined, so in this example it would not be
  966: necessary to define them.
  968: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
  969: @subsection Calls and returns
  971: A definition can be called simply be writing the name of the
  972: definition. When the end of the definition is reached, it returns. An earlier return can be forced using
  974: doc-exit
  976: Don't forget to clean up the return stack and @code{UNLOOP} any
  977: outstanding @code{?DO}...@code{LOOP}s before @code{EXIT}ing. The
  978: primitive compiled by @code{EXIT} is
  980: doc-;s
  982: @node Exception Handling,  , Calls and returns, Control Structures
  983: @subsection Exception Handling
  985: doc-catch
  986: doc-throw
  988: @node Locals, Defining Words, Control Structures, Words
  989: @section Locals
  991: Local variables can make Forth programming more enjoyable and Forth
  992: programs easier to read. Unfortunately, the locals of ANS Forth are
  993: laden with restrictions. Therefore, we provide not only the ANS Forth
  994: locals wordset, but also our own, more powerful locals wordset (we
  995: implemented the ANS Forth locals wordset through our locals wordset).
  997: @menu
  998: * gforth locals::               
  999: * ANS Forth locals::            
 1000: @end menu
 1002: @node gforth locals, ANS Forth locals, Locals, Locals
 1003: @subsection gforth locals
 1005: Locals can be defined with
 1007: @example
 1008: @{ local1 local2 ... -- comment @}
 1009: @end example
 1010: or
 1011: @example
 1012: @{ local1 local2 ... @}
 1013: @end example
 1015: E.g.,
 1016: @example
 1017: : max @{ n1 n2 -- n3 @}
 1018:  n1 n2 > if
 1019:    n1
 1020:  else
 1021:    n2
 1022:  endif ;
 1023: @end example
 1025: The similarity of locals definitions with stack comments is intended. A
 1026: locals definition often replaces the stack comment of a word. The order
 1027: of the locals corresponds to the order in a stack comment and everything
 1028: after the @code{--} is really a comment.
 1030: This similarity has one disadvantage: It is too easy to confuse locals
 1031: declarations with stack comments, causing bugs and making them hard to
 1032: find. However, this problem can be avoided by appropriate coding
 1033: conventions: Do not use both notations in the same program. If you do,
 1034: they should be distinguished using additional means, e.g. by position.
 1036: The name of the local may be preceded by a type specifier, e.g.,
 1037: @code{F:} for a floating point value:
 1039: @example
 1040: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
 1041: \ complex multiplication
 1042:  Ar Br f* Ai Bi f* f-
 1043:  Ar Bi f* Ai Br f* f+ ;
 1044: @end example
 1046: GNU Forth currently supports cells (@code{W:}, @code{W^}), doubles
 1047: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
 1048: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
 1049: with @code{W:}, @code{D:} etc.) produces its value and can be changed
 1050: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
 1051: produces its address (which becomes invalid when the variable's scope is
 1052: left). E.g., the standard word @code{emit} can be defined in therms of
 1053: @code{type} like this:
 1055: @example
 1056: : emit @{ C^ char* -- @}
 1057:     char* 1 type ;
 1058: @end example
 1060: A local without type specifier is a @code{W:} local. Both flavours of
 1061: locals are initialized with values from the data or FP stack.
 1063: Currently there is no way to define locals with user-defined data
 1064: structures, but we are working on it.
 1066: GNU Forth allows defining locals everywhere in a colon definition. This
 1067: poses the following questions:
 1069: @menu
 1070: * Where are locals visible by name?::  
 1071: * How long do locals live?::    
 1072: * Programming Style::           
 1073: * Implementation::              
 1074: @end menu
 1076: @node Where are locals visible by name?, How long do locals live?, gforth locals, gforth locals
 1077: @subsubsection Where are locals visible by name?
 1079: Basically, the answer is that locals are visible where you would expect
 1080: it in block-structured languages, and sometimes a little longer. If you
 1081: want to restrict the scope of a local, enclose its definition in
 1082: @code{SCOPE}...@code{ENDSCOPE}.
 1084: doc-scope
 1085: doc-endscope
 1087: These words behave like control structure words, so you can use them
 1088: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
 1089: arbitrary ways.
 1091: If you want a more exact answer to the visibility question, here's the
 1092: basic principle: A local is visible in all places that can only be
 1093: reached through the definition of the local@footnote{In compiler
 1094: construction terminology, all places dominated by the definition of the
 1095: local.}. In other words, it is not visible in places that can be reached
 1096: without going through the definition of the local. E.g., locals defined
 1097: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
 1098: defined in @code{BEGIN}...@code{UNTIL} are visible after the
 1099: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
 1101: The reasoning behind this solution is: We want to have the locals
 1102: visible as long as it is meaningful. The user can always make the
 1103: visibility shorter by using explicit scoping. In a place that can
 1104: only be reached through the definition of a local, the meaning of a
 1105: local name is clear. In other places it is not: How is the local
 1106: initialized at the control flow path that does not contain the
 1107: definition? Which local is meant, if the same name is defined twice in
 1108: two independent control flow paths?
 1110: This should be enough detail for nearly all users, so you can skip the
 1111: rest of this section. If you relly must know all the gory details and
 1112: options, read on.
 1114: In order to implement this rule, the compiler has to know which places
 1115: are unreachable. It knows this automatically after @code{AHEAD},
 1116: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
 1117: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
 1118: compiler that the control flow never reaches that place. If
 1119: @code{UNREACHABLE} is not used where it could, the only consequence is
 1120: that the visibility of some locals is more limited than the rule above
 1121: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
 1122: lie to the compiler), buggy code will be produced.
 1124: Another problem with this rule is that at @code{BEGIN}, the compiler
 1125: does not know which locals will be visible on the incoming
 1126: back-edge. All problems discussed in the following are due to this
 1127: ignorance of the compiler (we discuss the problems using @code{BEGIN}
 1128: loops as examples; the discussion also applies to @code{?DO} and other
 1129: loops). Perhaps the most insidious example is:
 1130: @example
 1131: AHEAD
 1132: BEGIN
 1133:   x
 1134: [ 1 CS-ROLL ] THEN
 1135:   @{ x @}
 1136:   ...
 1137: UNTIL
 1138: @end example
 1140: This should be legal according to the visibility rule. The use of
 1141: @code{x} can only be reached through the definition; but that appears
 1142: textually below the use.
 1144: From this example it is clear that the visibility rules cannot be fully
 1145: implemented without major headaches. Our implementation treats common
 1146: cases as advertised and the exceptions are treated in a safe way: The
 1147: compiler makes a reasonable guess about the locals visible after a
 1148: @code{BEGIN}; if it is too pessimistic, the
 1149: user will get a spurious error about the local not being defined; if the
 1150: compiler is too optimistic, it will notice this later and issue a
 1151: warning. In the case above the compiler would complain about @code{x}
 1152: being undefined at its use. You can see from the obscure examples in
 1153: this section that it takes quite unusual control structures to get the
 1154: compiler into trouble, and even then it will often do fine.
 1156: If the @code{BEGIN} is reachable from above, the most optimistic guess
 1157: is that all locals visible before the @code{BEGIN} will also be
 1158: visible after the @code{BEGIN}. This guess is valid for all loops that
 1159: are entered only through the @code{BEGIN}, in particular, for normal
 1160: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
 1161: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
 1162: compiler. When the branch to the @code{BEGIN} is finally generated by
 1163: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
 1164: warns the user if it was too optimisitic:
 1165: @example
 1166: IF
 1167:   @{ x @}
 1168: BEGIN
 1169:   \ x ? 
 1170: [ 1 cs-roll ] THEN
 1171:   ...
 1172: UNTIL
 1173: @end example
 1175: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
 1176: optimistically assumes that it lives until the @code{THEN}. It notices
 1177: this difference when it compiles the @code{UNTIL} and issues a
 1178: warning. The user can avoid the warning, and make sure that @code{x}
 1179: is not used in the wrong area by using explicit scoping:
 1180: @example
 1181: IF
 1182:   SCOPE
 1183:   @{ x @}
 1184:   ENDSCOPE
 1185: BEGIN
 1186: [ 1 cs-roll ] THEN
 1187:   ...
 1188: UNTIL
 1189: @end example
 1191: Since the guess is optimistic, there will be no spurious error messages
 1192: about undefined locals.
 1194: If the @code{BEGIN} is not reachable from above (e.g., after
 1195: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
 1196: optimistic guess, as the locals visible after the @code{BEGIN} may be
 1197: defined later. Therefore, the compiler assumes that no locals are
 1198: visible after the @code{BEGIN}. However, the useer can use
 1199: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
 1200: visible at the BEGIN as at the point where the item was created.
 1202: doc-assume-live
 1204: E.g.,
 1205: @example
 1206: @{ x @}
 1207: AHEAD
 1209: BEGIN
 1210:   x
 1211: [ 1 CS-ROLL ] THEN
 1212:   ...
 1213: UNTIL
 1214: @end example
 1216: Other cases where the locals are defined before the @code{BEGIN} can be
 1217: handled by inserting an appropriate @code{CS-ROLL} before the
 1218: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
 1219: behind the @code{ASSUME-LIVE}).
 1221: Cases where locals are defined after the @code{BEGIN} (but should be
 1222: visible immediately after the @code{BEGIN}) can only be handled by
 1223: rearranging the loop. E.g., the ``most insidious'' example above can be
 1224: arranged into:
 1225: @example
 1226: BEGIN
 1227:   @{ x @}
 1228:   ... 0=
 1229: WHILE
 1230:   x
 1231: REPEAT
 1232: @end example
 1234: @node How long do locals live?, Programming Style, Where are locals visible by name?, gforth locals
 1235: @subsubsection How long do locals live?
 1237: The right answer for the lifetime question would be: A local lives at
 1238: least as long as it can be accessed. For a value-flavoured local this
 1239: means: until the end of its visibility. However, a variable-flavoured
 1240: local could be accessed through its address far beyond its visibility
 1241: scope. Ultimately, this would mean that such locals would have to be
 1242: garbage collected. Since this entails un-Forth-like implementation
 1243: complexities, I adopted the same cowardly solution as some other
 1244: languages (e.g., C): The local lives only as long as it is visible;
 1245: afterwards its address is invalid (and programs that access it
 1246: afterwards are erroneous).
 1248: @node Programming Style, Implementation, How long do locals live?, gforth locals
 1249: @subsubsection Programming Style
 1251: The freedom to define locals anywhere has the potential to change
 1252: programming styles dramatically. In particular, the need to use the
 1253: return stack for intermediate storage vanishes. Moreover, all stack
 1254: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
 1255: determined arguments) can be eliminated: If the stack items are in the
 1256: wrong order, just write a locals definition for all of them; then
 1257: write the items in the order you want.
 1259: This seems a little far-fetched and eliminating stack manipulations is
 1260: unlikely to become a conscious programming objective. Still, the number
 1261: of stack manipulations will be reduced dramatically if local variables
 1262: are used liberally (e.g., compare @code{max} in @ref{gforth locals} with
 1263: a traditional implementation of @code{max}).
 1265: This shows one potential benefit of locals: making Forth programs more
 1266: readable. Of course, this benefit will only be realized if the
 1267: programmers continue to honour the principle of factoring instead of
 1268: using the added latitude to make the words longer.
 1270: Using @code{TO} can and should be avoided.  Without @code{TO},
 1271: every value-flavoured local has only a single assignment and many
 1272: advantages of functional languages apply to Forth. I.e., programs are
 1273: easier to analyse, to optimize and to read: It is clear from the
 1274: definition what the local stands for, it does not turn into something
 1275: different later.
 1277: E.g., a definition using @code{TO} might look like this:
 1278: @example
 1279: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 1280:  u1 u2 min 0
 1281:  ?do
 1282:    addr1 c@ addr2 c@ - ?dup
 1283:    if
 1284:      unloop exit
 1285:    then
 1286:    addr1 char+ TO addr1
 1287:    addr2 char+ TO addr2
 1288:  loop
 1289:  u1 u2 - ;
 1290: @end example
 1291: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
 1292: every loop iteration. @code{strcmp} is a typical example of the
 1293: readability problems of using @code{TO}. When you start reading
 1294: @code{strcmp}, you think that @code{addr1} refers to the start of the
 1295: string. Only near the end of the loop you realize that it is something
 1296: else.
 1298: This can be avoided by defining two locals at the start of the loop that
 1299: are initialized with the right value for the current iteration.
 1300: @example
 1301: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 1302:  addr1 addr2
 1303:  u1 u2 min 0 
 1304:  ?do @{ s1 s2 @}
 1305:    s1 c@ s2 c@ - ?dup 
 1306:    if
 1307:      unloop exit
 1308:    then
 1309:    s1 char+ s2 char+
 1310:  loop
 1311:  2drop
 1312:  u1 u2 - ;
 1313: @end example
 1314: Here it is clear from the start that @code{s1} has a different value
 1315: in every loop iteration.
 1317: @node Implementation,  , Programming Style, gforth locals
 1318: @subsubsection Implementation
 1320: GNU Forth uses an extra locals stack. The most compelling reason for
 1321: this is that the return stack is not float-aligned; using an extra stack
 1322: also eliminates the problems and restrictions of using the return stack
 1323: as locals stack. Like the other stacks, the locals stack grows toward
 1324: lower addresses. A few primitives allow an efficient implementation:
 1326: doc-@local#
 1327: doc-f@local#
 1328: doc-laddr#
 1329: doc-lp+!#
 1330: doc-lp!
 1331: doc->l
 1332: doc-f>l
 1334: In addition to these primitives, some specializations of these
 1335: primitives for commonly occurring inline arguments are provided for
 1336: efficiency reasons, e.g., @code{@@local0} as specialization of
 1337: @code{@@local#} for the inline argument 0. The following compiling words
 1338: compile the right specialized version, or the general version, as
 1339: appropriate:
 1341: doc-compile-@local
 1342: doc-compile-f@local
 1343: doc-compile-lp+!
 1345: Combinations of conditional branches and @code{lp+!#} like
 1346: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
 1347: is taken) are provided for efficiency and correctness in loops.
 1349: A special area in the dictionary space is reserved for keeping the
 1350: local variable names. @code{@{} switches the dictionary pointer to this
 1351: area and @code{@}} switches it back and generates the locals
 1352: initializing code. @code{W:} etc.@ are normal defining words. This
 1353: special area is cleared at the start of every colon definition.
 1355: A special feature of GNU Forths dictionary is used to implement the
 1356: definition of locals without type specifiers: every wordlist (aka
 1357: vocabulary) has its own methods for searching
 1358: etc. (@pxref{Wordlists}). For the present purpose we defined a wordlist
 1359: with a special search method: When it is searched for a word, it
 1360: actually creates that word using @code{W:}. @code{@{} changes the search
 1361: order to first search the wordlist containing @code{@}}, @code{W:} etc.,
 1362: and then the wordlist for defining locals without type specifiers.
 1364: The lifetime rules support a stack discipline within a colon
 1365: definition: The lifetime of a local is either nested with other locals
 1366: lifetimes or it does not overlap them.
 1368: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
 1369: pointer manipulation is generated. Between control structure words
 1370: locals definitions can push locals onto the locals stack. @code{AGAIN}
 1371: is the simplest of the other three control flow words. It has to
 1372: restore the locals stack depth of the corresponding @code{BEGIN}
 1373: before branching. The code looks like this:
 1374: @format
 1375: @code{lp+!#} current-locals-size @minus{} dest-locals-size
 1376: @code{branch} <begin>
 1377: @end format
 1379: @code{UNTIL} is a little more complicated: If it branches back, it
 1380: must adjust the stack just like @code{AGAIN}. But if it falls through,
 1381: the locals stack must not be changed. The compiler generates the
 1382: following code:
 1383: @format
 1384: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
 1385: @end format
 1386: The locals stack pointer is only adjusted if the branch is taken.
 1388: @code{THEN} can produce somewhat inefficient code:
 1389: @format
 1390: @code{lp+!#} current-locals-size @minus{} orig-locals-size
 1391: <orig target>:
 1392: @code{lp+!#} orig-locals-size @minus{} new-locals-size
 1393: @end format
 1394: The second @code{lp+!#} adjusts the locals stack pointer from the
 1395: level at the @var{orig} point to the level after the @code{THEN}. The
 1396: first @code{lp+!#} adjusts the locals stack pointer from the current
 1397: level to the level at the orig point, so the complete effect is an
 1398: adjustment from the current level to the right level after the
 1399: @code{THEN}.
 1401: In a conventional Forth implementation a dest control-flow stack entry
 1402: is just the target address and an orig entry is just the address to be
 1403: patched. Our locals implementation adds a wordlist to every orig or dest
 1404: item. It is the list of locals visible (or assumed visible) at the point
 1405: described by the entry. Our implementation also adds a tag to identify
 1406: the kind of entry, in particular to differentiate between live and dead
 1407: (reachable and unreachable) orig entries.
 1409: A few unusual operations have to be performed on locals wordlists:
 1411: doc-common-list
 1412: doc-sub-list?
 1413: doc-list-size
 1415: Several features of our locals wordlist implementation make these
 1416: operations easy to implement: The locals wordlists are organised as
 1417: linked lists; the tails of these lists are shared, if the lists
 1418: contain some of the same locals; and the address of a name is greater
 1419: than the address of the names behind it in the list.
 1421: Another important implementation detail is the variable
 1422: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
 1423: determine if they can be reached directly or only through the branch
 1424: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
 1425: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
 1426: definition, by @code{BEGIN} and usually by @code{THEN}.
 1428: Counted loops are similar to other loops in most respects, but
 1429: @code{LEAVE} requires special attention: It performs basically the same
 1430: service as @code{AHEAD}, but it does not create a control-flow stack
 1431: entry. Therefore the information has to be stored elsewhere;
 1432: traditionally, the information was stored in the target fields of the
 1433: branches created by the @code{LEAVE}s, by organizing these fields into a
 1434: linked list. Unfortunately, this clever trick does not provide enough
 1435: space for storing our extended control flow information. Therefore, we
 1436: introduce another stack, the leave stack. It contains the control-flow
 1437: stack entries for all unresolved @code{LEAVE}s.
 1439: Local names are kept until the end of the colon definition, even if
 1440: they are no longer visible in any control-flow path. In a few cases
 1441: this may lead to increased space needs for the locals name area, but
 1442: usually less than reclaiming this space would cost in code size.
 1445: @node ANS Forth locals,  , gforth locals, Locals
 1446: @subsection ANS Forth locals
 1448: The ANS Forth locals wordset does not define a syntax for locals, but
 1449: words that make it possible to define various syntaxes. One of the
 1450: possible syntaxes is a subset of the syntax we used in the gforth locals
 1451: wordset, i.e.:
 1453: @example
 1454: @{ local1 local2 ... -- comment @}
 1455: @end example
 1456: or
 1457: @example
 1458: @{ local1 local2 ... @}
 1459: @end example
 1461: The order of the locals corresponds to the order in a stack comment. The
 1462: restrictions are:
 1464: @itemize @bullet
 1465: @item
 1466: Locals can only be cell-sized values (no type specifers are allowed).
 1467: @item
 1468: Locals can be defined only outside control structures.
 1469: @item
 1470: Locals can interfere with explicit usage of the return stack. For the
 1471: exact (and long) rules, see the standard. If you don't use return stack
 1472: accessing words in a definition using locals, you will we all right. The
 1473: purpose of this rule is to make locals implementation on the return
 1474: stack easier.
 1475: @item
 1476: The whole definition must be in one line.
 1477: @end itemize
 1479: Locals defined in this way behave like @code{VALUE}s
 1480: (@xref{Values}). I.e., they are initialized from the stack. Using their
 1481: name produces their value. Their value can be changed using @code{TO}.
 1483: Since this syntax is supported by gforth directly, you need not do
 1484: anything to use it. If you want to port a program using this syntax to
 1485: another ANS Forth system, use @file{anslocal.fs} to implement the syntax
 1486: on the other system.
 1488: Note that a syntax shown in the standard, section A.13 looks
 1489: similar, but is quite different in having the order of locals
 1490: reversed. Beware!
 1492: The ANS Forth locals wordset itself consists of the following word
 1494: doc-(local)
 1496: The ANS Forth locals extension wordset defines a syntax, but it is so
 1497: awful that we strongly recommend not to use it. We have implemented this
 1498: syntax to make porting to gforth easy, but do not document it here. The
 1499: problem with this syntax is that the locals are defined in an order
 1500: reversed with respect to the standard stack comment notation, making
 1501: programs harder to read, and easier to misread and miswrite. The only
 1502: merit of this syntax is that it is easy to implement using the ANS Forth
 1503: locals wordset.
 1505: @node Defining Words, Wordlists, Locals, Words
 1506: @section Defining Words
 1508: @menu
 1509: * Values::                      
 1510: @end menu
 1512: @node Values,  , Defining Words, Defining Words
 1513: @subsection Values
 1515: @node Wordlists, Files, Defining Words, Words
 1516: @section Wordlists
 1518: @node Files, Blocks, Wordlists, Words
 1519: @section Files
 1521: @node Blocks, Other I/O, Files, Words
 1522: @section Blocks
 1524: @node Other I/O, Programming Tools, Blocks, Words
 1525: @section Other I/O
 1527: @node Programming Tools, Threading Words, Other I/O, Words
 1528: @section Programming Tools
 1530: @menu
 1531: * Debugging::                   Simple and quick.
 1532: * Assertions::                  Making your programs self-checking.
 1533: @end menu
 1535: @node Debugging, Assertions, Programming Tools, Programming Tools
 1536: @subsection Debugging
 1538: The simple debugging aids provided in @file{debugging.fs}
 1539: are meant to support a different style of debugging than the
 1540: tracing/stepping debuggers used in languages with long turn-around
 1541: times.
 1543: A much better (faster) way in fast-compilig languages is to add
 1544: printing code at well-selected places, let the program run, look at
 1545: the output, see where things went wrong, add more printing code, etc.,
 1546: until the bug is found.
 1548: The word @code{~~} is easy to insert. It just prints debugging
 1549: information (by default the source location and the stack contents). It
 1550: is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
 1551: query-replace them with nothing). The deferred words
 1552: @code{printdebugdata} and @code{printdebugline} control the output of
 1553: @code{~~}. The default source location output format works well with
 1554: Emacs' compilation mode, so you can step through the program at the
 1555: source level using @kbd{C-x `} (the advantage over a stepping debugger
 1556: is that you can step in any direction and you know where the crash has
 1557: happened or where the strange data has occurred).
 1559: Note that the default actions clobber the contents of the pictured
 1560: numeric output string, so you should not use @code{~~}, e.g., between
 1561: @code{<#} and @code{#>}.
 1563: doc-~~
 1564: doc-printdebugdata
 1565: doc-printdebugline
 1567: @node Assertions,  , Debugging, Programming Tools
 1568: @subsection Assertions
 1570: It is a good idea to make your programs self-checking, in particular, if
 1571: you use an assumption (e.g., that a certain field of a data structure is
 1572: never zero) that may become wrong during maintenance. GForth supports
 1573: assertions for this purpose. They are used like this:
 1575: @example
 1576: assert( @var{flag} )
 1577: @end example
 1579: The code between @code{assert(} and @code{)} should compute a flag, that
 1580: should be true if everything is alright and false otherwise. It should
 1581: not change anything else on the stack. The overall stack effect of the
 1582: assertion is @code{( -- )}. E.g.
 1584: @example
 1585: assert( 1 1 + 2 = ) \ what we learn in school
 1586: assert( dup 0<> ) \ assert that the top of stack is not zero
 1587: assert( false ) \ this code should not be reached
 1588: @end example
 1590: The need for assertions is different at different times. During
 1591: debugging, we want more checking, in production we sometimes care more
 1592: for speed. Therefore, assertions can be turned off, i.e., the assertion
 1593: becomes a comment. Depending on the importance of an assertion and the
 1594: time it takes to check it, you may want to turn off some assertions and
 1595: keep others turned on. GForth provides several levels of assertions for
 1596: this purpose:
 1598: doc-assert0(
 1599: doc-assert1(
 1600: doc-assert2(
 1601: doc-assert3(
 1602: doc-assert(
 1603: doc-)
 1605: @code{Assert(} is the same as @code{assert1(}. The variable
 1606: @code{assert-level} specifies the highest assertions that are turned
 1607: on. I.e., at the default @code{assert-level} of one, @code{assert0(} and
 1608: @code{assert1(} assertions perform checking, while @code{assert2(} and
 1609: @code{assert3(} assertions are treated as comments.
 1611: Note that the @code{assert-level} is evaluated at compile-time, not at
 1612: run-time. I.e., you cannot turn assertions on or off at run-time, you
 1613: have to set the @code{assert-level} appropriately before compiling a
 1614: piece of code. You can compile several pieces of code at several
 1615: @code{assert-level}s (e.g., a trusted library at level 1 and newly
 1616: written code at level 3).
 1618: doc-assert-level
 1620: If an assertion fails, a message compatible with Emacs' compilation mode
 1621: is produced and the execution is aborted (currently with @code{ABORT"}.
 1622: If there is interest, we will introduce a special throw code. But if you
 1623: intend to @code{catch} a specific condition, using @code{throw} is
 1624: probably more appropriate than an assertion).
 1626: @node Threading Words,  , Programming Tools, Words
 1627: @section Threading Words
 1629: These words provide access to code addresses and other threading stuff
 1630: in gforth (and, possibly, other interpretive Forths). It more or less
 1631: abstracts away the differences between direct and indirect threading
 1632: (and, for direct threading, the machine dependences). However, at
 1633: present this wordset is still inclomplete. It is also pretty low-level;
 1634: some day it will hopefully be made unnecessary by an internals words set
 1635: that abstracts implementation details away completely.
 1637: doc->code-address
 1638: doc->does-code
 1639: doc-code-address!
 1640: doc-does-code!
 1641: doc-does-handler!
 1642: doc-/does-handler
 1646: @node ANS conformance, Model, Words, Top
 1647: @chapter ANS conformance
 1649: To the best of our knowledge, gforth is an
 1651: ANS Forth System
 1652: @itemize
 1653: @item providing the Core Extensions word set
 1654: @item providing the Block word set
 1655: @item providing the Block Extensions word set
 1656: @item providing the Double-Number word set
 1657: @item providing the Double-Number Extensions word set
 1658: @item providing the Exception word set
 1659: @item providing the Exception Extensions word set
 1660: @item providing the Facility word set
 1661: @item providing @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
 1662: @item providing the File Access word set
 1663: @item providing the File Access Extensions word set
 1664: @item providing the Floating-Point word set
 1665: @item providing the Floating-Point Extensions word set
 1666: @item providing the Locals word set
 1667: @item providing the Locals Extensions word set
 1668: @item providing the Memory-Allocation word set
 1669: @item providing the Memory-Allocation Extensions word set (that one's easy)
 1670: @item providing the Programming-Tools word set
 1671: @item providing @code{AHEAD}, @code{BYE}, @code{CS-PICK}, @code{CS-ROLL}, @code{STATE}, @code{[ELSE]}, @code{[IF]}, @code{[THEN]} from the Programming-Tools Extensions word set
 1672: @item providing the Search-Order word set
 1673: @item providing the Search-Order Extensions word set
 1674: @item providing the String word set
 1675: @item providing the String Extensions word set (another easy one)
 1676: @end itemize
 1678: In addition, ANS Forth systems are required to document certain
 1679: implementation choices. This chapter tries to meet these
 1680: requirements. In many cases it gives a way to ask the system for the
 1681: information instead of providing the information directly, in
 1682: particular, if the information depends on the processor, the operating
 1683: system or the installation options chosen, or if they are likely to
 1684: change during the maintenance of gforth.
 1686: @comment The framework for the rest has been taken from pfe.
 1688: @menu
 1689: * The Core Words::              
 1690: * The optional Block word set::  
 1691: * The optional Double Number word set::  
 1692: * The optional Exception word set::  
 1693: * The optional Facility word set::  
 1694: * The optional File-Access word set::  
 1695: * The optional Floating-Point word set::  
 1696: * The optional Locals word set::  
 1697: * The optional Memory-Allocation word set::  
 1698: * The optional Programming-Tools word set::  
 1699: * The optional Search-Order word set::  
 1700: @end menu
 1703: @c =====================================================================
 1704: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
 1705: @comment  node-name,  next,  previous,  up
 1706: @section The Core Words
 1707: @c =====================================================================
 1709: @menu
 1710: * core-idef::                   Implementation Defined Options                   
 1711: * core-ambcond::                Ambiguous Conditions                
 1712: * core-other::                  Other System Documentation                  
 1713: @end menu
 1715: @c ---------------------------------------------------------------------
 1716: @node core-idef, core-ambcond, The Core Words, The Core Words
 1717: @subsection Implementation Defined Options
 1718: @c ---------------------------------------------------------------------
 1720: @table @i
 1722: @item (Cell) aligned addresses:
 1723: processor-dependent. Gforths alignment words perform natural alignment
 1724: (e.g., an address aligned for a datum of size 8 is divisible by
 1725: 8). Unaligned accesses usually result in a @code{-23 THROW}.
 1727: @item @code{EMIT} and non-graphic characters:
 1728: The character is output using the C library function (actually, macro)
 1729: @code{putchar}.
 1731: @item character editing of @code{ACCEPT} and @code{EXPECT}:
 1732: This is modeled on the GNU readline library (@pxref{Readline
 1733: Interaction, , Command Line Editing, readline, The GNU Readline
 1734: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
 1735: producing a full word completion every time you type it (instead of
 1736: producing the common prefix of all completions).
 1738: @item character set:
 1739: The character set of your computer and display device. Gforth is
 1740: 8-bit-clean (but some other component in your system may make trouble).
 1742: @item Character-aligned address requirements:
 1743: installation-dependent. Currently a character is represented by a C
 1744: @code{unsigned char}; in the future we might switch to @code{wchar_t}
 1745: (Comments on that requested).
 1747: @item character-set extensions and matching of names:
 1748: Any character except 0 can be used in a name. Matching is
 1749: case-insensitive. The matching is performed using the C function
 1750: @code{strncasecmp}, whose function is probably influenced by the
 1751: locale. E.g., the @code{C} locale does not know about accents and
 1752: umlauts, so they are matched case-sensitively in that locale. For
 1753: portability reasons it is best to write programs such that they work in
 1754: the @code{C} locale. Then one can use libraries written by a Polish
 1755: programmer (who might use words containing ISO Latin-2 encoded
 1756: characters) and by a French programmer (ISO Latin-1) in the same program
 1757: (of course, @code{WORDS} will produce funny results for some of the
 1758: words (which ones, depends on the font you are using)). Also, the locale
 1759: you prefer may not be available in other operating systems. Hopefully,
 1760: Unicode will solve these problems one day.
 1762: @item conditions under which control characters match a space delimiter:
 1763: If @code{WORD} is called with the space character as a delimiter, all
 1764: white-space characters (as identified by the C macro @code{isspace()})
 1765: are delimiters. @code{PARSE}, on the other hand, treats space like other
 1766: delimiters. @code{PARSE-WORD} treats space like @code{WORD}, but behaves
 1767: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
 1768: interpreter (aka text interpreter) by default, treats all white-space
 1769: characters as delimiters.
 1771: @item format of the control flow stack:
 1772: The data stack is used as control flow stack. The size of a control flow
 1773: stack item in cells is given by the constant @code{cs-item-size}. At the
 1774: time of this writing, an item consists of a (pointer to a) locals list
 1775: (third), an address in the code (second), and a tag for identifying the
 1776: item (TOS). The following tags are used: @code{defstart},
 1777: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
 1778: @code{scopestart}.
 1780: @item conversion of digits > 35
 1781: The characters @code{[\]^_'} are the digits with the decimal value
 1782: 36@minus{}41. There is no way to input many of the larger digits.
 1784: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
 1785: The cursor is moved to the end of the entered string. If the input is
 1786: terminated using the @kbd{Return} key, a space is typed.
 1788: @item exception abort sequence of @code{ABORT"}:
 1789: The error string is stored into the variable @code{"error} and a
 1790: @code{-2 throw} is performed.
 1792: @item input line terminator:
 1793: For interactive input, @kbd{C-m} and @kbd{C-j} terminate lines. One of
 1794: these characters is typically produced when you type the @kbd{Enter} or
 1795: @kbd{Return} key.
 1797: @item maximum size of a counted string:
 1798: @code{s" /counted-string" environment? drop .}. Currently 255 characters
 1799: on all ports, but this may change.
 1801: @item maximum size of a parsed string:
 1802: Given by the constant @code{/line}. Currently 255 characters.
 1804: @item maximum size of a definition name, in characters:
 1805: 31
 1807: @item maximum string length for @code{ENVIRONMENT?}, in characters:
 1808: 31
 1810: @item method of selecting the user input device:
 1811: The user input device is the standard input. There is current no way to
 1812: change it from within gforth. However, the input can typically be
 1813: redirected in the command line that starts gforth.
 1815: @item method of selecting the user output device:
 1816: The user output device is the standard output. It cannot be redirected
 1817: from within gforth, but typically from the command line that starts
 1818: gforth. Gforth uses buffered output, so output on a terminal does not
 1819: become visible before the next newline or buffer overflow. Output on
 1820: non-terminals is invisible until the buffer overflows.
 1822: @item methods of dictionary compilation:
 1823: Waht are we expected to document here?
 1825: @item number of bits in one address unit:
 1826: @code{s" address-units-bits" environment? drop .}. 8 in all current
 1827: ports.
 1829: @item number representation and arithmetic:
 1830: Processor-dependent. Binary two's complement on all current ports.
 1832: @item ranges for integer types:
 1833: Installation-dependent. Make environmental queries for @code{MAX-N},
 1834: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
 1835: unsigned (and positive) types is 0. The lower bound for signed types on
 1836: two's complement and one's complement machines machines can be computed
 1837: by adding 1 to the upper bound.
 1839: @item read-only data space regions:
 1840: The whole Forth data space is writable.
 1842: @item size of buffer at @code{WORD}:
 1843: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
 1844: shared with the pictured numeric output string. If overwriting
 1845: @code{PAD} is acceptable, it is as large as the remaining dictionary
 1846: space, although only as much can be sensibly used as fits in a counted
 1847: string.
 1849: @item size of one cell in address units:
 1850: @code{1 cells .}.
 1852: @item size of one character in address units:
 1853: @code{1 chars .}. 1 on all current ports.
 1855: @item size of the keyboard terminal buffer:
 1856: Varies. You can determine the size at a specific time using @code{lp@
 1857: tib - .}. It is shared with the locals stack and TIBs of files that
 1858: include the current file. You can change the amount of space for TIBs
 1859: and locals stack at gforth startup with the command line option
 1860: @code{-l}.
 1862: @item size of the pictured numeric output buffer:
 1863: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
 1864: shared with @code{WORD}.
 1866: @item size of the scratch area returned by @code{PAD}:
 1867: The remainder of dictionary space. You can even use the unused part of
 1868: the data stack space. The current size can be computed with @code{sp@
 1869: pad - .}.
 1871: @item system case-sensitivity characteristics:
 1872: Dictionary searches are case insensitive. However, as explained above
 1873: under @i{character-set extensions}, the matching for non-ASCII
 1874: characters is determined by the locale you are using. In the default
 1875: @code{C} locale all non-ASCII characters are matched case-sensitively.
 1877: @item system prompt:
 1878: @code{ ok} in interpret state, @code{ compiled} in compile state.
 1880: @item division rounding:
 1881: installation dependent. @code{s" floored" environment? drop .}. We leave
 1882: the choice to gcc (what to use for @code{/}) and to you (whether to use
 1883: @code{fm/mod}, @code{sm/rem} or simply @code{/}).
 1885: @item values of @code{STATE} when true:
 1886: -1.
 1888: @item values returned after arithmetic overflow:
 1889: On two's complement machines, arithmetic is performed modulo
 1890: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
 1891: arithmetic (with appropriate mapping for signed types). Division by zero
 1892: typically results in a @code{-55 throw} (floatingpoint unidentified
 1893: fault), although a @code{-10 throw} (divide by zero) would be more
 1894: appropriate.
 1896: @item whether the current definition can be found after @t{DOES>}:
 1897: No.
 1899: @end table
 1901: @c ---------------------------------------------------------------------
 1902: @node core-ambcond, core-other, core-idef, The Core Words
 1903: @subsection Ambiguous conditions
 1904: @c ---------------------------------------------------------------------
 1906: @table @i
 1908: @item a name is neither a word nor a number:
 1909: @code{-13 throw} (Undefined word)
 1911: @item a definition name exceeds the maximum length allowed:
 1912: @code{-19 throw} (Word name too long)
 1914: @item addressing a region not inside the various data spaces of the forth system:
 1915: The stacks, code space and name space are accessible. Machine code space is
 1916: typically readable. Accessing other addresses gives results dependent on
 1917: the operating system. On decent systems: @code{-9 throw} (Invalid memory
 1918: address).
 1920: @item argument type incompatible with parameter:
 1921: This is usually not caught. Some words perform checks, e.g., the control
 1922: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
 1923: mismatch).
 1925: @item attempting to obtain the execution token of a word with undefined execution semantics:
 1926: You get an execution token representing the compilation semantics
 1927: instead.
 1929: @item dividing by zero:
 1930: typically results in a @code{-55 throw} (floating point unidentified
 1931: fault), although a @code{-10 throw} (divide by zero) would be more
 1932: appropriate.
 1934: @item insufficient data stack or return stack space:
 1935: Not checked. This typically results in mysterious illegal memory
 1936: accesses, producing @code{-9 throw} (Invalid memory address) or
 1937: @code{-23 throw} (Address alignment exception).
 1939: @item insufficient space for loop control parameters:
 1940: like other return stack overflows.
 1942: @item insufficient space in the dictionary:
 1943: Not checked. Similar results as stack overflows. However, typically the
 1944: error appears at a different place when one inserts or removes code.
 1946: @item interpreting a word with undefined interpretation semantics:
 1947: For some words, we defined interpretation semantics. For the others:
 1948: @code{-14 throw} (Interpreting a compile-only word). Note that this is
 1949: checked only by the outer (aka text) interpreter; if the word is
 1950: @code{execute}d in some other way, it will typically perform it's
 1951: compilation semantics even in interpret state. (We could change @code{'}
 1952: and relatives not to give the xt of such words, but we think that would
 1953: be too restrictive).
 1955: @item modifying the contents of the input buffer or a string literal:
 1956: These are located in writable memory and can be modified.
 1958: @item overflow of the pictured numeric output string:
 1959: Not checked.
 1961: @item parsed string overflow:
 1962: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
 1964: @item producing a result out of range:
 1965: On two's complement machines, arithmetic is performed modulo
 1966: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
 1967: arithmetic (with appropriate mapping for signed types). Division by zero
 1968: typically results in a @code{-55 throw} (floatingpoint unidentified
 1969: fault), although a @code{-10 throw} (divide by zero) would be more
 1970: appropriate. @code{convert} and @code{>number} currently overflow
 1971: silently.
 1973: @item reading from an empty data or return stack:
 1974: The data stack is checked by the outer (aka text) interpreter after
 1975: every word executed. If it has underflowed, a @code{-4 throw} (Stack
 1976: underflow) is performed. Apart from that, the stacks are not checked and
 1977: underflows can result in similar behaviour as overflows (of adjacent
 1978: stacks).
 1980: @item unexepected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
 1981: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
 1982: use zero-length string as a name). Words like @code{'} probably will not
 1983: find what they search. Note that it is possible to create zero-length
 1984: names with @code{nextname} (should it not?).
 1986: @item @code{>IN} greater than input buffer:
 1987: The next invocation of a parsing word returns a string wih length 0.
 1989: @item @code{RECURSE} appears after @code{DOES>}:
 1990: Compiles a recursive call to the defining word not to the defined word.
 1992: @item argument input source different than current input source for @code{RESTORE-INPUT}:
 1993: !!???If the argument input source is a valid input source then it gets
 1994: restored. Otherwise causes @code{-12 THROW} which unless caught issues
 1995: the message "argument type mismatch" and aborts.
 1997: @item data space containing definitions gets de-allocated:
 1998: Deallocation with @code{allot} is not checked. This typically resuls in
 1999: memory access faults or execution of illegal instructions.
 2001: @item data space read/write with incorrect alignment:
 2002: Processor-dependent. Typically results in a @code{-23 throw} (Address
 2003: alignment exception). Under Linux on a 486 or later processor with
 2004: alignment turned on, incorrect alignment results in a @code{-9 throw}
 2005: (Invalid memory address). There are reportedly some processors with
 2006: alignment restrictions that do not report them.
 2008: @item data space pointer not properly aligned, @code{,}, @code{C,}:
 2009: Like other alignment errors.
 2011: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
 2012: Not checked. May cause an illegal memory access.
 2014: @item loop control parameters not available:
 2015: Not checked. The counted loop words simply assume that the top of return
 2016: stack items are loop control parameters and behave accordingly.
 2018: @item most recent definition does not have a name (@code{IMMEDIATE}):
 2019: @code{abort" last word was headerless"}.
 2021: @item name not defined by @code{VALUE} used by @code{TO}:
 2022: @code{-32 throw} (Invalid name argument)
 2024: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
 2025: @code{-13 throw} (Undefined word)
 2027: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
 2028: Gforth behaves as if they were of the same type. I.e., you can predict
 2029: the behaviour by interpreting all parameters as, e.g., signed.
 2031: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
 2032: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} is equivalent to
 2033: @code{TO}.
 2035: @item String longer than a counted string returned by @code{WORD}:
 2036: Not checked. The string will be ok, but the count will, of course,
 2037: contain only the least significant bits of the length.
 2039: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
 2040: Processor-dependent. Typical behaviours are returning 0 and using only
 2041: the low bits of the shift count.
 2043: @item word not defined via @code{CREATE}:
 2044: @code{>BODY} produces the PFA of the word no matter how it was defined.
 2046: @code{DOES>} changes the execution semantics of the last defined word no
 2047: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
 2048: @code{CREATE , DOES>}.
 2050: @item words improperly used outside @code{<#} and @code{#>}:
 2051: Not checked. As usual, you can expect memory faults.
 2053: @end table
 2056: @c ---------------------------------------------------------------------
 2057: @node core-other,  , core-ambcond, The Core Words
 2058: @subsection Other system documentation
 2059: @c ---------------------------------------------------------------------
 2061: @table @i
 2063: @item nonstandard words using @code{PAD}:
 2064: None.
 2066: @item operator's terminal facilities available:
 2067: !!??
 2069: @item program data space available:
 2070: @code{sp@ here - .} gives the space remaining for dictionary and data
 2071: stack together.
 2073: @item return stack space available:
 2074: !!??
 2076: @item stack space available:
 2077: @code{sp@ here - .} gives the space remaining for dictionary and data
 2078: stack together.
 2080: @item system dictionary space required, in address units:
 2081: Type @code{here forthstart - .} after startup. At the time of this
 2082: writing, this gives 70108 (bytes) on a 32-bit system.
 2083: @end table
 2086: @c =====================================================================
 2087: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
 2088: @section The optional Block word set
 2089: @c =====================================================================
 2091: @menu
 2092: * block-idef::                  Implementation Defined Options                  
 2093: * block-ambcond::               Ambiguous Conditions               
 2094: * block-other::                 Other System Documentation                 
 2095: @end menu
 2098: @c ---------------------------------------------------------------------
 2099: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
 2100: @subsection Implementation Defined Options
 2101: @c ---------------------------------------------------------------------
 2103: @table @i
 2105: @item the format for display by @code{LIST}:
 2106: First the screen number is displayed, then 16 lines of 64 characters,
 2107: each line preceded by the line number.
 2109: @item the length of a line affected by @code{\}:
 2110: 64 characters.
 2111: @end table
 2114: @c ---------------------------------------------------------------------
 2115: @node block-ambcond, block-other, block-idef, The optional Block word set
 2116: @subsection Ambiguous conditions
 2117: @c ---------------------------------------------------------------------
 2119: @table @i
 2121: @item correct block read was not possible:
 2122: Typically results in a @code{throw} of some OS-derived value (between
 2123: -512 and -2048). If the blocks file was just not long enough, blanks are
 2124: supplied for the missing portion.
 2126: @item I/O exception in block transfer:
 2127: Typically results in a @code{throw} of some OS-derived value (between
 2128: -512 and -2048).
 2130: @item invalid block number:
 2131: @code{-35 throw} (Invalid block number)
 2133: @item a program directly alters the contents of @code{BLK}:
 2134: The input stream is switched to that other block, at the same
 2135: position. If the storing to @code{BLK} happens when interpreting
 2136: non-block input, the system will get quite confused when the block ends.
 2138: @item no current block buffer for @code{UPDATE}:
 2139: @code{UPDATE} has no effect.
 2141: @end table
 2144: @c ---------------------------------------------------------------------
 2145: @node block-other,  , block-ambcond, The optional Block word set
 2146: @subsection Other system documentation
 2147: @c ---------------------------------------------------------------------
 2149: @table @i
 2151: @item any restrictions a multiprogramming system places on the use of buffer addresses:
 2152: No restrictions (yet).
 2154: @item the number of blocks available for source and data:
 2155: depends on your disk space.
 2157: @end table
 2160: @c =====================================================================
 2161: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
 2162: @section The optional Double Number word set
 2163: @c =====================================================================
 2165: @menu
 2166: * double-ambcond::              Ambiguous Conditions              
 2167: @end menu
 2170: @c ---------------------------------------------------------------------
 2171: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
 2172: @subsection Ambiguous conditions
 2173: @c ---------------------------------------------------------------------
 2175: @table @i
 2177: @item @var{d} outside of range of @var{n} in @code{D>S}:
 2178: The least significant cell of @var{d} is produced.
 2180: @end table
 2183: @c =====================================================================
 2184: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
 2185: @section The optional Exception word set
 2186: @c =====================================================================
 2188: @menu
 2189: * exception-idef::              Implementation Defined Options              
 2190: @end menu
 2193: @c ---------------------------------------------------------------------
 2194: @node exception-idef,  , The optional Exception word set, The optional Exception word set
 2195: @subsection Implementation Defined Options
 2196: @c ---------------------------------------------------------------------
 2198: @table @i
 2199: @item @code{THROW}-codes used in the system:
 2200: The codes -256@minus{}-511 are used for reporting signals (see
 2201: @file{errore.fs}). The codes -512@minus{}-2047 are used for OS errors
 2202: (for file and memory allocation operations). The mapping from OS error
 2203: numbers to throw code is -512@minus{}@var{errno}. One side effect of
 2204: this mapping is that undefined OS errors produce a message with a
 2205: strange number; e.g., @code{-1000 THROW} results in @code{Unknown error
 2206: 488} on my system.
 2207: @end table
 2209: @c =====================================================================
 2210: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
 2211: @section The optional Facility word set
 2212: @c =====================================================================
 2214: @menu
 2215: * facility-idef::               Implementation Defined Options               
 2216: * facility-ambcond::            Ambiguous Conditions            
 2217: @end menu
 2220: @c ---------------------------------------------------------------------
 2221: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
 2222: @subsection Implementation Defined Options
 2223: @c ---------------------------------------------------------------------
 2225: @table @i
 2227: @item encoding of keyboard events (@code{EKEY}):
 2228: Not yet implemeted.
 2230: @item duration of a system clock tick
 2231: System dependent. With respect to @code{MS}, the time is specified in
 2232: microseconds. How well the OS and the hardware implement this, is
 2233: another question.
 2235: @item repeatability to be expected from the execution of @code{MS}:
 2236: System dependent. On Unix, a lot depends on load. If the system is
 2237: lightly loaded, and the delay is short enough that gforth does not get
 2238: swapped out, the performance should be acceptable. Under MS-DOS and
 2239: other single-tasking systems, it should be good.
 2241: @end table
 2244: @c ---------------------------------------------------------------------
 2245: @node facility-ambcond,  , facility-idef, The optional Facility word set
 2246: @subsection Ambiguous conditions
 2247: @c ---------------------------------------------------------------------
 2249: @table @i
 2251: @item @code{AT-XY} can't be performed on user output device:
 2252: Largely terminal dependant. No range checks are done on the arguments.
 2253: No errors are reported. You may see some garbage appearing, you may see
 2254: simply nothing happen.
 2256: @end table
 2259: @c =====================================================================
 2260: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
 2261: @section The optional File-Access word set
 2262: @c =====================================================================
 2264: @menu
 2265: * file-idef::                   Implementation Defined Options                   
 2266: * file-ambcond::                Ambiguous Conditions                
 2267: @end menu
 2270: @c ---------------------------------------------------------------------
 2271: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
 2272: @subsection Implementation Defined Options
 2273: @c ---------------------------------------------------------------------
 2275: @table @i
 2277: @item File access methods used:
 2278: @code{R/O}, @code{R/W} and @code{BIN} work as you would
 2279: expect. @code{W/O} translates into the C file opening mode @code{w} (or
 2280: @code{wb}): The file is cleared, if it exists, and created, if it does
 2281: not (both with @code{open-file} and @code{create-file}).  Under Unix
 2282: @code{create-file} creates a file with 666 permissions modified by your
 2283: umask.
 2285: @item file exceptions:
 2286: The file words do not raise exceptions (except, perhaps, memory access
 2287: faults when you pass illegal addresses or file-ids).
 2289: @item file line terminator:
 2290: System-dependent. Gforth uses C's newline character as line
 2291: terminator. What the actual character code(s) of this are is
 2292: system-dependent.
 2294: @item file name format
 2295: System dependent. Gforth just uses the file name format of your OS.
 2297: @item information returned by @code{FILE-STATUS}:
 2298: @code{FILE-STATUS} returns the most powerful file access mode allowed
 2299: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
 2300: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
 2301: along with the retured mode.
 2303: @item input file state after an exception when including source:
 2304: All files that are left via the exception are closed.
 2306: @item @var{ior} values and meaning:
 2307: The @var{ior}s returned by the file and memory allocation words are
 2308: intended as throw codes. They typically are in the range
 2309: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
 2310: @var{ior}s is -512@minus{}@var{errno}.
 2312: @item maximum depth of file input nesting:
 2313: limited by the amount of return stack, locals/TIB stack, and the number
 2314: of open files available. This should not give you troubles.
 2316: @item maximum size of input line:
 2317: @code{/line}. Currently 255.
 2319: @item methods of mapping block ranges to files:
 2320: Currently, the block words automatically access the file
 2321: @file{blocks.fb} in the currend working directory. More sophisticated
 2322: methods could be implemented if there is demand (and a volunteer).
 2324: @item number of string buffers provided by @code{S"}:
 2325: 1
 2327: @item size of string buffer used by @code{S"}:
 2328: @code{/line}. currently 255.
 2330: @end table
 2332: @c ---------------------------------------------------------------------
 2333: @node file-ambcond,  , file-idef, The optional File-Access word set
 2334: @subsection Ambiguous conditions
 2335: @c ---------------------------------------------------------------------
 2337: @table @i
 2339: @item attempting to position a file outside it's boundaries:
 2340: @code{REPOSITION-FILE} is performed as usual: Afterwards,
 2341: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
 2343: @item attempting to read from file positions not yet written:
 2344: End-of-file, i.e., zero characters are read and no error is reported.
 2346: @item @var{file-id} is invalid (@code{INCLUDE-FILE}):
 2347: An appropriate exception may be thrown, but a memory fault or other
 2348: problem is more probable.
 2350: @item I/O exception reading or closing @var{file-id} (@code{include-file}, @code{included}):
 2351: The @var{ior} produced by the operation, that discovered the problem, is
 2352: thrown.
 2354: @item named file cannot be opened (@code{included}):
 2355: The @var{ior} produced by @code{open-file} is thrown.
 2357: @item requesting an unmapped block number:
 2358: There are no unmapped legal block numbers. On some operating systems,
 2359: writing a block with a large number may overflow the file system and
 2360: have an error message as consequence.
 2362: @item using @code{source-id} when @code{blk} is non-zero:
 2363: @code{source-id} performs its function. Typically it will give the id of
 2364: the source which loaded the block. (Better ideas?)
 2366: @end table
 2369: @c =====================================================================
 2370: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
 2371: @section The optional Floating-Point word set
 2372: @c =====================================================================
 2374: @menu
 2375: * floating-idef::               Implementation Defined Options
 2376: * floating-ambcond::            Ambiguous Conditions            
 2377: @end menu
 2380: @c ---------------------------------------------------------------------
 2381: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
 2382: @subsection Implementation Defined Options
 2383: @c ---------------------------------------------------------------------
 2385: @table @i
 2387: @item format and range of floating point numbers:
 2388: System-dependent; the @code{double} type of C.
 2390: @item results of @code{REPRESENT} when @var{float} is out of range:
 2391: System dependent; @code{REPRESENT} is implemented using the C library
 2392: function @code{ecvt()} and inherits its behaviour in this respect.
 2394: @item rounding or truncation of floating-point numbers:
 2395: What's the question?!!
 2397: @item size of floating-point stack:
 2398: @code{s" FLOATING-STACK" environment? drop .}. Can be changed at startup
 2399: with the command-line option @code{-f}.
 2401: @item width of floating-point stack:
 2402: @code{1 floats}.
 2404: @end table
 2407: @c ---------------------------------------------------------------------
 2408: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
 2409: @subsection Ambiguous conditions
 2410: @c ---------------------------------------------------------------------
 2412: @table @i
 2414: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
 2415: System-dependent. Typically results in an alignment fault like other
 2416: alignment violations.
 2418: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
 2419: System-dependent. Typically results in an alignment fault like other
 2420: alignment violations.
 2422: @item Floating-point result out of range:
 2423: System-dependent. Can result in a @code{-55 THROW} (Floating-point
 2424: unidentified fault), or can produce a special value representing, e.g.,
 2425: Infinity.
 2427: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
 2428: System-dependent. Typically results in an alignment fault like other
 2429: alignment violations.
 2431: @item BASE is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
 2432: The floating-point number is converted into decimal nonetheless.
 2434: @item Both arguments are equal to zero (@code{FATAN2}):
 2435: System-dependent. @code{FATAN2} is implemented using the C library
 2436: function @code{atan2()}.
 2438: @item Using ftan on an argument @var{r1} where cos(@var{r1}) is zero:
 2439: System-dependent. Anyway, typically the cos of @var{r1} will not be zero
 2440: because of small errors and the tan will be a very large (or very small)
 2441: but finite number.
 2443: @item @var{d} cannot be presented precisely as a float in @code{D>F}:
 2444: The result is rounded to the nearest float.
 2446: @item dividing by zero:
 2447: @code{-55 throw} (Floating-point unidentified fault)
 2449: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
 2450: System dependent. On IEEE-FP based systems the number is converted into
 2451: an infinity.
 2453: @item @var{float}<1 (@code{facosh}):
 2454: @code{-55 throw} (Floating-point unidentified fault)
 2456: @item @var{float}=<-1 (@code{flnp1}):
 2457: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
 2458: negative infinity is typically produced for @var{float}=-1.
 2460: @item @var{float}=<0 (@code{fln}, @code{flog}):
 2461: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
 2462: negative infinity is typically produced for @var{float}=0.
 2464: @item @var{float}<0 (@code{fasinh}, @code{fsqrt}):
 2465: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
 2466: produces values for these inputs on my Linux box (Bug in the C library?)
 2468: @item |@var{float}|>1 (@code{facos}, @code{fasin}, @code{fatanh}):
 2469: @code{-55 throw} (Floating-point unidentified fault).
 2471: @item integer part of float cannot be represented by @var{d} in @code{f>d}:
 2472: @code{-55 throw} (Floating-point unidentified fault).
 2474: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
 2475: This does not happen.
 2476: @end table
 2480: @c =====================================================================
 2481: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
 2482: @section The optional Locals word set
 2483: @c =====================================================================
 2485: @menu
 2486: * locals-idef::                 Implementation Defined Options                 
 2487: * locals-ambcond::              Ambiguous Conditions              
 2488: @end menu
 2491: @c ---------------------------------------------------------------------
 2492: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
 2493: @subsection Implementation Defined Options
 2494: @c ---------------------------------------------------------------------
 2496: @table @i
 2498: @item maximum number of locals in a definition:
 2499: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
 2500: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
 2501: characters. The number of locals in a definition is bounded by the size
 2502: of locals-buffer, which contains the names of the locals.
 2504: @end table
 2507: @c ---------------------------------------------------------------------
 2508: @node locals-ambcond,  , locals-idef, The optional Locals word set
 2509: @subsection Ambiguous conditions
 2510: @c ---------------------------------------------------------------------
 2512: @table @i
 2514: @item executing a named local in interpretation state:
 2515: @code{-14 throw} (Interpreting a compile-only word).
 2517: @item @var{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
 2518: @code{-32 throw} (Invalid name argument)
 2520: @end table
 2523: @c =====================================================================
 2524: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
 2525: @section The optional Memory-Allocation word set
 2526: @c =====================================================================
 2528: @menu
 2529: * memory-idef::                 Implementation Defined Options                 
 2530: @end menu
 2533: @c ---------------------------------------------------------------------
 2534: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
 2535: @subsection Implementation Defined Options
 2536: @c ---------------------------------------------------------------------
 2538: @table @i
 2540: @item values and meaning of @var{ior}:
 2541: The @var{ior}s returned by the file and memory allocation words are
 2542: intended as throw codes. They typically are in the range
 2543: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
 2544: @var{ior}s is -512@minus{}@var{errno}.
 2546: @end table
 2548: @c =====================================================================
 2549: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
 2550: @section The optional Programming-Tools word set
 2551: @c =====================================================================
 2553: @menu
 2554: * programming-idef::            Implementation Defined Options            
 2555: * programming-ambcond::         Ambiguous Conditions         
 2556: @end menu
 2559: @c ---------------------------------------------------------------------
 2560: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
 2561: @subsection Implementation Defined Options
 2562: @c ---------------------------------------------------------------------
 2564: @table @i
 2566: @item ending sequence for input following @code{;code} and @code{code}:
 2567: Not implemented (yet).
 2569: @item manner of processing input following @code{;code} and @code{code}:
 2570: Not implemented (yet).
 2572: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
 2573: Not implemented (yet). If they were implemented, they would use the
 2574: search order wordset.
 2576: @item source and format of display by @code{SEE}:
 2577: The source for @code{see} is the intermediate code used by the inner
 2578: interpreter.  The current @code{see} tries to output Forth source code
 2579: as well as possible.
 2581: @end table
 2583: @c ---------------------------------------------------------------------
 2584: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
 2585: @subsection Ambiguous conditions
 2586: @c ---------------------------------------------------------------------
 2588: @table @i
 2590: @item deleting the compilation wordlist (@code{FORGET}):
 2591: Not implemented (yet).
 2593: @item fewer than @var{u}+1 items on the control flow stack (@code{CS-PICK}, @code{CS-ROLL}):
 2594: This typically results in an @code{abort"} with a descriptive error
 2595: message (may change into a @code{-22 throw} (Control structure mismatch)
 2596: in the future). You may also get a memory access error. If you are
 2597: unlucky, this ambiguous condition is not caught.
 2599: @item @var{name} can't be found (@code{forget}):
 2600: Not implemented (yet).
 2602: @item @var{name} not defined via @code{CREATE}:
 2603: @code{;code} is not implemented (yet). If it were, it would behave like
 2604: @code{DOES>} in this respect, i.e., change the execution semantics of
 2605: the last defined word no matter how it was defined.
 2607: @item @code{POSTPONE} applied to @code{[IF]}:
 2608: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
 2609: equivalent to @code{[IF]}.
 2611: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
 2612: Continue in the same state of conditional compilation in the next outer
 2613: input source. Currently there is no warning to the user about this.
 2615: @item removing a needed definition (@code{FORGET}):
 2616: Not implemented (yet).
 2618: @end table
 2621: @c =====================================================================
 2622: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
 2623: @section The optional Search-Order word set
 2624: @c =====================================================================
 2626: @menu
 2627: * search-idef::                 Implementation Defined Options                 
 2628: * search-ambcond::              Ambiguous Conditions              
 2629: @end menu
 2632: @c ---------------------------------------------------------------------
 2633: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
 2634: @subsection Implementation Defined Options
 2635: @c ---------------------------------------------------------------------
 2637: @table @i
 2639: @item maximum number of word lists in search order:
 2640: @code{s" wordlists" environment? drop .}. Currently 16.
 2642: @item minimum search order:
 2643: @code{root root}.
 2645: @end table
 2647: @c ---------------------------------------------------------------------
 2648: @node search-ambcond,  , search-idef, The optional Search-Order word set
 2649: @subsection Ambiguous conditions
 2650: @c ---------------------------------------------------------------------
 2652: @table @i
 2654: @item changing the compilation wordlist (during compilation):
 2655: The definition is put into the wordlist that is the compilation wordlist
 2656: when @code{REVEAL} is executed (by @code{;}, @code{DOES>},
 2657: @code{RECURSIVE}, etc.).
 2659: @item search order empty (@code{previous}):
 2660: @code{abort" Vocstack empty"}.
 2662: @item too many word lists in search order (@code{also}):
 2663: @code{abort" Vocstack full"}.
 2665: @end table
 2668: @node Model, Emacs and GForth, ANS conformance, Top
 2669: @chapter Model
 2671: @node Emacs and GForth, Internals, Model, Top
 2672: @chapter Emacs and GForth
 2674: GForth comes with @file{gforth.el}, an improved version of
 2675: @file{forth.el} by Goran Rydqvist (icluded in the TILE package). The
 2676: improvements are a better (but still not perfect) handling of
 2677: indentation. I have also added comment paragraph filling (@kbd{M-q}),
 2678: commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) regions and
 2679: removing debugging tracers (@kbd{C-x ~}, @pxref{Debugging}). I left the
 2680: stuff I do not use alone, even though some of it only makes sense for
 2681: TILE. To get a description of these features, enter Forth mode and type
 2682: @kbd{C-h m}.
 2684: In addition, GForth supports Emacs quite well: The source code locations
 2685: given in error messages, debugging output (from @code{~~}) and failed
 2686: assertion messages are in the right format for Emacs' compilation mode
 2687: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
 2688: Manual}) so the source location corresponding to an error or other
 2689: message is only a few keystrokes away (@kbd{C-x `} for the next error,
 2690: @kbd{C-c C-c} for the error under the cursor).
 2692: Also, if you @code{include} @file{etags.fs}, a new @file{TAGS} file
 2693: (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) will be produced that
 2694: contains the definitions of all words defined afterwards. You can then
 2695: find the source for a word using @kbd{M-.}. Note that emacs can use
 2696: several tags files at the same time (e.g., one for the gforth sources
 2697: and one for your program).
 2699: To get all these benefits, add the following lines to your @file{.emacs}
 2700: file:
 2702: @example
 2703: (autoload 'forth-mode "gforth.el")
 2704: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
 2705: @end example
 2707: @node Internals, Bugs, Emacs and GForth, Top
 2708: @chapter Internals
 2710: Reading this section is not necessary for programming with gforth. It
 2711: should be helpful for finding your way in the gforth sources.
 2713: @menu
 2714: * Portability::                 
 2715: * Threading::                   
 2716: * Primitives::                  
 2717: * System Architecture::         
 2718: @end menu
 2720: @node Portability, Threading, Internals, Internals
 2721: @section Portability
 2723: One of the main goals of the effort is availability across a wide range
 2724: of personal machines. fig-Forth, and, to a lesser extent, F83, achieved
 2725: this goal by manually coding the engine in assembly language for several
 2726: then-popular processors. This approach is very labor-intensive and the
 2727: results are short-lived due to progress in computer architecture.
 2729: Others have avoided this problem by coding in C, e.g., Mitch Bradley
 2730: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
 2731: particularly popular for UNIX-based Forths due to the large variety of
 2732: architectures of UNIX machines. Unfortunately an implementation in C
 2733: does not mix well with the goals of efficiency and with using
 2734: traditional techniques: Indirect or direct threading cannot be expressed
 2735: in C, and switch threading, the fastest technique available in C, is
 2736: significantly slower. Another problem with C is that it's very
 2737: cumbersome to express double integer arithmetic.
 2739: Fortunately, there is a portable language that does not have these
 2740: limitations: GNU C, the version of C processed by the GNU C compiler
 2741: (@pxref{C Extensions, , Extensions to the C Language Family,,
 2742: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
 2743: Labels as Values,, GNU C Manual}) makes direct and indirect
 2744: threading possible, its @code{long long} type (@pxref{Long Long, ,
 2745: Double-Word Integers,, GNU C Manual}) corresponds to Forths
 2746: double numbers. GNU C is available for free on all important (and many
 2747: unimportant) UNIX machines, VMS, 80386s running MS-DOS, the Amiga, and
 2748: the Atari ST, so a Forth written in GNU C can run on all these
 2749: machines@footnote{Due to Apple's look-and-feel lawsuit it is not
 2750: available on the Mac (@pxref{Boycott, , Protect Your Freedom---Fight
 2751: ``Look And Feel'',, GNU C Manual}).}.
 2753: Writing in a portable language has the reputation of producing code that
 2754: is slower than assembly. For our Forth engine we repeatedly looked at
 2755: the code produced by the compiler and eliminated most compiler-induced
 2756: inefficiencies by appropriate changes in the source-code.
 2758: However, register allocation cannot be portably influenced by the
 2759: programmer, leading to some inefficiencies on register-starved
 2760: machines. We use explicit register declarations (@pxref{Explicit Reg
 2761: Vars, , Variables in Specified Registers,, GNU C Manual}) to
 2762: improve the speed on some machines. They are turned on by using the
 2763: @code{gcc} switch @code{-DFORCE_REG}. Unfortunately, this feature not
 2764: only depends on the machine, but also on the compiler version: On some
 2765: machines some compiler versions produce incorrect code when certain
 2766: explicit register declarations are used. So by default
 2767: @code{-DFORCE_REG} is not used.
 2769: @node Threading, Primitives, Portability, Internals
 2770: @section Threading
 2772: GNU C's labels as values extension (available since @code{gcc-2.0},
 2773: @pxref{Labels as Values, , Labels as Values,, GNU C Manual})
 2774: makes it possible to take the address of @var{label} by writing
 2775: @code{&&@var{label}}.  This address can then be used in a statement like
 2776: @code{goto *@var{address}}. I.e., @code{goto *&&x} is the same as
 2777: @code{goto x}.
 2779: With this feature an indirect threaded NEXT looks like:
 2780: @example
 2781: cfa = *ip++;
 2782: ca = *cfa;
 2783: goto *ca;
 2784: @end example
 2785: For those unfamiliar with the names: @code{ip} is the Forth instruction
 2786: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
 2787: execution token and points to the code field of the next word to be
 2788: executed; The @code{ca} (code address) fetched from there points to some
 2789: executable code, e.g., a primitive or the colon definition handler
 2790: @code{docol}.
 2792: Direct threading is even simpler:
 2793: @example
 2794: ca = *ip++;
 2795: goto *ca;
 2796: @end example
 2798: Of course we have packaged the whole thing neatly in macros called
 2799: @code{NEXT} and @code{NEXT1} (the part of NEXT after fetching the cfa).
 2801: @menu
 2802: * Scheduling::                  
 2803: * Direct or Indirect Threaded?::  
 2804: * DOES>::                       
 2805: @end menu
 2807: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
 2808: @subsection Scheduling
 2810: There is a little complication: Pipelined and superscalar processors,
 2811: i.e., RISC and some modern CISC machines can process independent
 2812: instructions while waiting for the results of an instruction. The
 2813: compiler usually reorders (schedules) the instructions in a way that
 2814: achieves good usage of these delay slots. However, on our first tries
 2815: the compiler did not do well on scheduling primitives. E.g., for
 2816: @code{+} implemented as
 2817: @example
 2818: n=sp[0]+sp[1];
 2819: sp++;
 2820: sp[0]=n;
 2821: NEXT;
 2822: @end example
 2823: the NEXT comes strictly after the other code, i.e., there is nearly no
 2824: scheduling. After a little thought the problem becomes clear: The
 2825: compiler cannot know that sp and ip point to different addresses (and
 2826: the version of @code{gcc} we used would not know it even if it was
 2827: possible), so it could not move the load of the cfa above the store to
 2828: the TOS. Indeed the pointers could be the same, if code on or very near
 2829: the top of stack were executed. In the interest of speed we chose to
 2830: forbid this probably unused ``feature'' and helped the compiler in
 2831: scheduling: NEXT is divided into the loading part (@code{NEXT_P1}) and
 2832: the goto part (@code{NEXT_P2}). @code{+} now looks like:
 2833: @example
 2834: n=sp[0]+sp[1];
 2835: sp++;
 2836: NEXT_P1;
 2837: sp[0]=n;
 2838: NEXT_P2;
 2839: @end example
 2840: This can be scheduled optimally by the compiler.
 2842: This division can be turned off with the switch @code{-DCISC_NEXT}. This
 2843: switch is on by default on machines that do not profit from scheduling
 2844: (e.g., the 80386), in order to preserve registers.
 2846: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
 2847: @subsection Direct or Indirect Threaded?
 2849: Both! After packaging the nasty details in macro definitions we
 2850: realized that we could switch between direct and indirect threading by
 2851: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
 2852: defining a few machine-specific macros for the direct-threading case.
 2853: On the Forth level we also offer access words that hide the
 2854: differences between the threading methods (@pxref{Threading Words}).
 2856: Indirect threading is implemented completely
 2857: machine-independently. Direct threading needs routines for creating
 2858: jumps to the executable code (e.g. to docol or dodoes). These routines
 2859: are inherently machine-dependent, but they do not amount to many source
 2860: lines. I.e., even porting direct threading to a new machine is a small
 2861: effort.
 2863: @node DOES>,  , Direct or Indirect Threaded?, Threading
 2864: @subsection DOES>
 2865: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
 2866: the chunk of code executed by every word defined by a
 2867: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
 2868: the Forth code to be executed, i.e. the code after the @code{DOES>} (the
 2869: DOES-code)? There are two solutions:
 2871: In fig-Forth the code field points directly to the dodoes and the
 2872: DOES-code address is stored in the cell after the code address
 2873: (i.e. at cfa cell+). It may seem that this solution is illegal in the
 2874: Forth-79 and all later standards, because in fig-Forth this address
 2875: lies in the body (which is illegal in these standards). However, by
 2876: making the code field larger for all words this solution becomes legal
 2877: again. We use this approach for the indirect threaded version. Leaving
 2878: a cell unused in most words is a bit wasteful, but on the machines we
 2879: are targetting this is hardly a problem. The other reason for having a
 2880: code field size of two cells is to avoid having different image files
 2881: for direct and indirect threaded systems (@pxref{System Architecture}).
 2883: The other approach is that the code field points or jumps to the cell
 2884: after @code{DOES}. In this variant there is a jump to @code{dodoes} at
 2885: this address. @code{dodoes} can then get the DOES-code address by
 2886: computing the code address, i.e., the address of the jump to dodoes,
 2887: and add the length of that jump field. A variant of this is to have a
 2888: call to @code{dodoes} after the @code{DOES>}; then the return address
 2889: (which can be found in the return register on RISCs) is the DOES-code
 2890: address. Since the two cells available in the code field are usually
 2891: used up by the jump to the code address in direct threading, we use
 2892: this approach for direct threading. We did not want to add another
 2893: cell to the code field.
 2895: @node Primitives, System Architecture, Threading, Internals
 2896: @section Primitives
 2898: @menu
 2899: * Automatic Generation::        
 2900: * TOS Optimization::            
 2901: * Produced code::               
 2902: @end menu
 2904: @node Automatic Generation, TOS Optimization, Primitives, Primitives
 2905: @subsection Automatic Generation
 2907: Since the primitives are implemented in a portable language, there is no
 2908: longer any need to minimize the number of primitives. On the contrary,
 2909: having many primitives is an advantage: speed. In order to reduce the
 2910: number of errors in primitives and to make programming them easier, we
 2911: provide a tool, the primitive generator (@file{prims2x.fs}), that
 2912: automatically generates most (and sometimes all) of the C code for a
 2913: primitive from the stack effect notation.  The source for a primitive
 2914: has the following form:
 2916: @format
 2917: @var{Forth-name}	@var{stack-effect}	@var{category}	[@var{pronounc.}]
 2918: [@code{""}@var{glossary entry}@code{""}]
 2919: @var{C code}
 2920: [@code{:}
 2921: @var{Forth code}]
 2922: @end format
 2924: The items in brackets are optional. The category and glossary fields
 2925: are there for generating the documentation, the Forth code is there
 2926: for manual implementations on machines without GNU C. E.g., the source
 2927: for the primitive @code{+} is:
 2928: @example
 2929: +    n1 n2 -- n    core    plus
 2930: n = n1+n2;
 2931: @end example
 2933: This looks like a specification, but in fact @code{n = n1+n2} is C
 2934: code. Our primitive generation tool extracts a lot of information from
 2935: the stack effect notations@footnote{We use a one-stack notation, even
 2936: though we have separate data and floating-point stacks; The separate
 2937: notation can be generated easily from the unified notation.}: The number
 2938: of items popped from and pushed on the stack, their type, and by what
 2939: name they are referred to in the C code. It then generates a C code
 2940: prelude and postlude for each primitive. The final C code for @code{+}
 2941: looks like this:
 2943: @example
 2944: I_plus:	/* + ( n1 n2 -- n ) */  /* label, stack effect */
 2945: /*  */                          /* documentation */
 2946: @{
 2947: DEF_CA                          /* definition of variable ca (indirect threading) */
 2948: Cell n1;                        /* definitions of variables */
 2949: Cell n2;
 2950: Cell n;
 2951: n1 = (Cell) sp[1];              /* input */
 2952: n2 = (Cell) TOS;
 2953: sp += 1;                        /* stack adjustment */
 2954: NAME("+")                       /* debugging output (with -DDEBUG) */
 2955: @{
 2956: n = n1+n2;                      /* C code taken from the source */
 2957: @}
 2958: NEXT_P1;                        /* NEXT part 1 */
 2959: TOS = (Cell)n;                  /* output */
 2960: NEXT_P2;                        /* NEXT part 2 */
 2961: @}
 2962: @end example
 2964: This looks long and inefficient, but the GNU C compiler optimizes quite
 2965: well and produces optimal code for @code{+} on, e.g., the R3000 and the
 2966: HP RISC machines: Defining the @code{n}s does not produce any code, and
 2967: using them as intermediate storage also adds no cost.
 2969: There are also other optimizations, that are not illustrated by this
 2970: example: Assignments between simple variables are usually for free (copy
 2971: propagation). If one of the stack items is not used by the primitive
 2972: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
 2973: (dead code elimination). On the other hand, there are some things that
 2974: the compiler does not do, therefore they are performed by
 2975: @file{prims2x.fs}: The compiler does not optimize code away that stores
 2976: a stack item to the place where it just came from (e.g., @code{over}).
 2978: While programming a primitive is usually easy, there are a few cases
 2979: where the programmer has to take the actions of the generator into
 2980: account, most notably @code{?dup}, but also words that do not (always)
 2981: fall through to NEXT.
 2983: @node TOS Optimization, Produced code, Automatic Generation, Primitives
 2984: @subsection TOS Optimization
 2986: An important optimization for stack machine emulators, e.g., Forth
 2987: engines, is keeping  one or more of the top stack items in
 2988: registers.  If a word has the stack effect @var{in1}...@var{inx} @code{--}
 2989: @var{out1}...@var{outy}, keeping the top @var{n} items in registers
 2990: @itemize
 2991: @item
 2992: is better than keeping @var{n-1} items, if @var{x>=n} and @var{y>=n},
 2993: due to fewer loads from and stores to the stack.
 2994: @item is slower than keeping @var{n-1} items, if @var{x<>y} and @var{x<n} and
 2995: @var{y<n}, due to additional moves between registers.
 2996: @end itemize
 2998: In particular, keeping one item in a register is never a disadvantage,
 2999: if there are enough registers. Keeping two items in registers is a
 3000: disadvantage for frequent words like @code{?branch}, constants,
 3001: variables, literals and @code{i}. Therefore our generator only produces
 3002: code that keeps zero or one items in registers. The generated C code
 3003: covers both cases; the selection between these alternatives is made at
 3004: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
 3005: code for @code{+} is just a simple variable name in the one-item case,
 3006: otherwise it is a macro that expands into @code{sp[0]}. Note that the
 3007: GNU C compiler tries to keep simple variables like @code{TOS} in
 3008: registers, and it usually succeeds, if there are enough registers.
 3010: The primitive generator performs the TOS optimization for the
 3011: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
 3012: operations the benefit of this optimization is even larger:
 3013: floating-point operations take quite long on most processors, but can be
 3014: performed in parallel with other operations as long as their results are
 3015: not used. If the FP-TOS is kept in a register, this works. If
 3016: it is kept on the stack, i.e., in memory, the store into memory has to
 3017: wait for the result of the floating-point operation, lengthening the
 3018: execution time of the primitive considerably.
 3020: The TOS optimization makes the automatic generation of primitives a
 3021: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
 3022: @code{TOS} is not sufficient. There are some special cases to
 3023: consider:
 3024: @itemize
 3025: @item In the case of @code{dup ( w -- w w )} the generator must not
 3026: eliminate the store to the original location of the item on the stack,
 3027: if the TOS optimization is turned on.
 3028: @item Primitives with stack effects of the form @code{--}
 3029: @var{out1}...@var{outy} must store the TOS to the stack at the start.
 3030: Likewise, primitives with the stack effect @var{in1}...@var{inx} @code{--}
 3031: must load the TOS from the stack at the end. But for the null stack
 3032: effect @code{--} no stores or loads should be generated.
 3033: @end itemize
 3035: @node Produced code,  , TOS Optimization, Primitives
 3036: @subsection Produced code
 3038: To see what assembly code is produced for the primitives on your machine
 3039: with your compiler and your flag settings, type @code{make engine.s} and
 3040: look at the resulting file @file{engine.s}.
 3042: @node System Architecture,  , Primitives, Internals
 3043: @section System Architecture
 3045: Our Forth system consists not only of primitives, but also of
 3046: definitions written in Forth. Since the Forth compiler itself belongs
 3047: to those definitions, it is not possible to start the system with the
 3048: primitives and the Forth source alone. Therefore we provide the Forth
 3049: code as an image file in nearly executable form. At the start of the
 3050: system a C routine loads the image file into memory, sets up the
 3051: memory (stacks etc.) according to information in the image file, and
 3052: starts executing Forth code.
 3054: The image file format is a compromise between the goals of making it
 3055: easy to generate image files and making them portable. The easiest way
 3056: to generate an image file is to just generate a memory dump. However,
 3057: this kind of image file cannot be used on a different machine, or on
 3058: the next version of the engine on the same machine, it even might not
 3059: work with the same engine compiled by a different version of the C
 3060: compiler. We would like to have as few versions of the image file as
 3061: possible, because we do not want to distribute many versions of the
 3062: same image file, and to make it easy for the users to use their image
 3063: files on many machines. We currently need to create a different image
 3064: file for machines with different cell sizes and different byte order
 3065: (little- or big-endian)@footnote{We consider adding information to the
 3066: image file that enables the loader to change the byte order.}.
 3068: Forth code that is going to end up in a portable image file has to
 3069: comply to some restrictions: addresses have to be stored in memory with
 3070: special words (@code{A!}, @code{A,}, etc.) in order to make the code
 3071: relocatable. Cells, floats, etc., have to be stored at the natural
 3072: alignment boundaries@footnote{E.g., store floats (8 bytes) at an address
 3073: dividable by~8. This happens automatically in our system when you use
 3074: the ANS Forth alignment words.}, in order to avoid alignment faults on
 3075: machines with stricter alignment. The image file is produced by a
 3076: metacompiler (@file{cross.fs}).
 3078: So, unlike the image file of Mitch Bradleys @code{cforth}, our image
 3079: file is not directly executable, but has to undergo some manipulations
 3080: during loading. Address relocation is performed at image load-time, not
 3081: at run-time. The loader also has to replace tokens standing for
 3082: primitive calls with the appropriate code-field addresses (or code
 3083: addresses in the case of direct threading).
 3085: @node Bugs, Pedigree, Internals, Top
 3086: @chapter Bugs
 3088: @node Pedigree, Word Index, Bugs, Top
 3089: @chapter Pedigree
 3091: @node Word Index, Node Index, Pedigree, Top
 3092: @chapter Word Index
 3094: @node Node Index,  , Word Index, Top
 3095: @chapter Node Index
 3097: @contents
 3098: @bye

FreeBSD-CVSweb <>