File:  [gforth] / gforth / Attic / gforth.ds
Wed Nov 23 16:54:39 1994 UTC (25 years, 2 months ago) by anton
Branches: MAIN
added package target to Makefile.in
some documentation changes


    1: \input texinfo   @c -*-texinfo-*-
2: @comment The source is gforth.ds, from which gforth.texi is generated
3: @comment %**start of header (This is for running Texinfo on a region.)
4: @setfilename gforth-info
5: @settitle GNU Forth Manual
6: @setchapternewpage odd
7: @comment %**end of header (This is for running Texinfo on a region.)
8:
9: @ifinfo
10: This file documents GNU Forth 0.0
11:
13:
14:      Permission is granted to make and distribute verbatim copies of
15:      this manual provided the copyright notice and this permission notice
16:      are preserved on all copies.
17:
18:      @ignore
19:      Permission is granted to process this file through TeX and print the
20:      results, provided the printed document carries a copying permission
21:      notice identical to this one except for the removal of this paragraph
22:      (this paragraph not being relevant to the printed manual).
23:
24:      @end ignore
25:      Permission is granted to copy and distribute modified versions of this
26:      manual under the conditions for verbatim copying, provided also that the
27:      sections entitled "Distribution" and "General Public License" are
28:      included exactly as in the original, and provided that the entire
29:      resulting derived work is distributed under the terms of a permission
30:      notice identical to this one.
31:
32:      Permission is granted to copy and distribute translations of this manual
33:      into another language, under the above conditions for modified versions,
34:      except that the sections entitled "Distribution" and "General Public
35:      License" may be included in a translation approved by the author instead
36:      of in the original English.
37: @end ifinfo
38:
39: @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
46:
47: @comment  The following two commands start the copyright page.
48: @page
49: @vskip 0pt plus 1filll
51:
52: @comment !! Published by ... or You can get a copy of this manual ...
53:
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.
57:
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.
64:
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
71:
72:
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
78:
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
94:
95: @node License, Goals, Top, Top
97: !! Insert GPL here
98:
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
105:
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:
112:
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
123:
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
139:
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.
150:
151: @node Other Books, Invocation, Goals, Top
152: @chapter Other books on ANS Forth
153:
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.
158:
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 ftp.uu.net:/vendor/minerva/x3j14.
164:
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.
171:
172: @node Invocation, Words, Other Books, Top
173: @chapter Invocation
174:
175: You will usually just say @code{gforth}. In many other cases the default
176: GNU Forth image will be invoked like this:
177:
178: @example
179: gforth [files] [-e forth-code]
180: @end example
181:
182: executing the contents of the files and the Forth code in the order they
183: are given.
184:
185: In general, the command line looks like this:
186:
187: @example
188: gforth [initialization options] [image-specific options]
189: @end example
190:
191: The initialization options must come before the rest of the command
192: line. They are:
193:
194: @table @code
195: @item --image-file @var{file}
197: @file{gforth.fi}.
198:
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.
205:
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.
214:
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).
219:
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).
224:
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.
230:
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).
235:
236: @end table
237:
238: As explained above, the image-specific command-line arguments for the
239: default image @file{gforth.fi} 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.
247:
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).
255:
256: @node Words,  , Invocation, Top
257: @chapter Forth Words
258:
260: * Notation::
261: * Arithmetic::
262: * Stack Manipulation::
263: * Memory access::
264: * Control Structures::
265: * Local Variables::
266: * Defining Words::
267: * Vocabularies::
268: * Files::
269: * Blocks::
270: * Other I/O::
271: * Programming Tools::
273:
274: @node Notation, Arithmetic, Words, Words
275: @section Notation
276:
277: The Forth words are described in this section in the glossary notation
278: that has become a de-facto standard for Forth texts, i.e.
279:
280: @quotation
281: @var{word}     @var{Stack effect}   @var{wordset}   @var{pronunciation}
282: @var{Description}
283: @end quotation
284:
285: @table @var
286: @item word
287: The name of the word. BTW, GNU Forth is case insensitive, so you can
288: type the words in in lower case.
289:
290: @item Stack effect
291: The stack effect is written in the notation @code{@var{before} --
292: @var{after}}, where @var{before} and @var{after} describe the top of
293: stack entries before and after the execution of the word. The rest of
294: the stack is not touched by the word. The top of stack is rightmost,
295: i.e., a stack sequence is written as it is typed in. Note that GNU Forth
296: uses a separate floating point stack, but a unified stack
297: notation. Also, return stack effects are not shown in @var{stack
298: effect}, but in @var{Description}. The name of a stack item describes
299: the type and/or the function of the item. See below for a discussion of
300: the types.
301:
302: @item pronunciation
303: How the word is pronounced
304:
305: @item wordset
306: The ANS Forth standard is divided into several wordsets. A standard
307: system need not support all of them. So, the fewer wordsets your program
308: uses the more portable it will be in theory. However, we suspect that
309: most ANS Forth systems on personal machines will feature all
310: wordsets. Words that are not defined in the ANS standard have
311: @code{gforth} as wordset.
312:
313: @item Description
314: A description of the behaviour of the word.
315: @end table
316:
317: The name of a stack item corresponds in the following way with its type:
318:
319: @table @code
320: @item name starts with
321: Type
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_
340: @item c_
341: Char-aligned address (note that a Char is two bytes in Windows NT)
342: @item f_
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
355:
356: @node Arithmetic,  , 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).
367:
368: @subsection Single precision
369: doc-+
370: doc--
371: doc-*
372: doc-/
373: doc-mod
374: doc-/mod
375: doc-negate
376: doc-abs
377: doc-min
378: doc-max
379:
380: @subsection Bitwise operations
381: doc-and
382: doc-or
383: doc-xor
384: doc-invert
385: doc-2*
386: doc-2/
387:
388: @subsection Mixed precision
389: doc-m+
390: doc-*/
391: doc-*/mod
392: doc-m*
393: doc-um*
394: doc-m*/
395: doc-um/mod
396: doc-fm/mod
397: doc-sm/rem
398:
399: @subsection Double precision
400: doc-d+
401: doc-d-
402: doc-dnegate
403: doc-dabs
404: doc-dmin
405: doc-dmax
406:
407: @node Stack Manipulation,,,
408: @section Stack Manipulation
409:
410: gforth has a data stack (aka parameter stack) for characters, cells,
411: addresses, and double cells, a floating point stack for floating point
412: numbers, a return stack for storing the return addresses of colon
413: definitions and other data, and a locals stack for storing local
414: variables. Note that while every sane Forth has a separate floating
415: point stack, this is not strictly required; an ANS Forth system could
416: theoretically keep floating point numbers on the data stack. As an
417: additional difficulty, you don't know how many cells a floating point
418: number takes. It is reportedly possible to write words in a way that
419: they work also for a unified stack model, but we do not recommend trying
420: it. Also, a Forth system is allowed to keep the local variables on the
421: return stack. This is reasonable, as local variables usually eliminate
422: the need to use the return stack explicitly. So, if you want to produce
423: a standard complying program and if you are using local variables in a
424: word, forget about return stack manipulations in that word (see the
425: standard document for the exact rules).
426:
427: @subsection Data stack
428: doc-drop
429: doc-nip
430: doc-dup
431: doc-over
432: doc-tuck
433: doc-swap
434: doc-rot
435: doc--rot
436: doc-?dup
437: doc-pick
438: doc-roll
439: doc-2drop
440: doc-2nip
441: doc-2dup
442: doc-2over
443: doc-2tuck
444: doc-2swap
445: doc-2rot
446:
447: @subsection Floating point stack
448: doc-fdrop
449: doc-fnip
450: doc-fdup
451: doc-fover
452: doc-ftuck
453: doc-fswap
454: doc-frot
455:
456: @subsection Return stack
457: doc->r
458: doc-r>
459: doc-r@
460: doc-rdrop
461: doc-2>r
462: doc-2r>
463: doc-2r@
464: doc-2rdrop
465:
466: @subsection Locals stack
467:
468: @subsection Stack pointer manipulation
469: doc-sp@
470: doc-sp!
471: doc-fp@
472: doc-fp!
473: doc-rp@
474: doc-rp!
475: doc-lp@
476: doc-lp!
477:
478: @node Memory access
479: @section Memory access
480:
481: @subsection Stack-Memory transfers
482:
483: doc-@
484: doc-!
485: doc-+!
486: doc-c@
487: doc-c!
488: doc-2@
489: doc-2!
490: doc-f@
491: doc-f!
492: doc-sf@
493: doc-sf!
494: doc-df@
495: doc-df!
496:
498:
499: ANS Forth does not specify the sizes of the data types. Instead, it
500: offers a number of words for computing sizes and doing address
501: arithmetic. Basically, address arithmetic is performed in terms of
502: address units (aus); on most systems the address unit is one byte. Note
503: that a character may have more than one au, so @code{chars} is no noop
504: (on systems where it is a noop, it compiles to nothing).
505:
506: ANS Forth also defines words for aligning addresses for specific
507: addresses. Many computers require that accesses to specific data types
508: must only occur at specific addresses; e.g., that cells may only be
509: accessed at addresses divisible by 4. Even if a machine allows unaligned
510: accesses, it can usually perform aligned accesses faster.
511:
512: For the performance-concious: alignment operations are usually only
513: necessary during the definition of a data structure, not during the
514: (more frequent) accesses to it.
515:
516: ANS Forth defines no words for character-aligning addresses. This is not
517: an oversight, but reflects the fact that addresses that are not
518: char-aligned have no use in the standard and therefore will not be
519: created.
520:
521: The standard guarantees that addresses returned by @code{CREATE}d words
523: are aligned for all purposes.
524:
525: doc-chars
526: doc-char+
527: doc-cells
528: doc-cell+
529: doc-align
530: doc-aligned
531: doc-floats
532: doc-float+
533: doc-falign
534: doc-faligned
535: doc-sfloats
536: doc-sfloat+
537: doc-sfalign
538: doc-sfaligned
539: doc-dfloats
540: doc-dfloat+
541: doc-dfalign
542: doc-dfaligned
544:
545: @subsection Memory block access
546:
547: doc-move
548: doc-erase
549:
550: While the previous words work on address units, the rest works on
551: characters.
552:
553: doc-cmove
554: doc-cmove>
555: doc-fill
556: doc-blank
557:
558: @node Control Structures
559: @section Control Structures
560:
561: Control structures in Forth cannot be used in interpret state, only in
562: compile state, i.e., in a colon definition. We do not like this
563: limitation, but have not seen a satisfying way around it yet, although
564: many schemes have been proposed.
565:
566: @subsection Selection
567:
568: @example
569: @var{flag}
570: IF
571:   @var{code}
572: ENDIF
573: @end example
574: or
575: @example
576: @var{flag}
577: IF
578:   @var{code1}
579: ELSE
580:   @var{code2}
581: ENDIF
582: @end example
583:
584: You can use @code{THEN} instead of {ENDIF}. Indeed, @code{THEN} is
585: standard, and @code{ENDIF} is not, although it is quite popular. We
586: recommend using @code{ENDIF}, because it is less confusing for people
587: who also know other languages (and is not prone to reinforcing negative
588: prejudices against Forth in these people). Adding @code{ENDIF} to a
589: system that only supplies @code{THEN} is simple:
590: @example
591: : endif   POSTPONE then ; immediate
592: @end example
593:
594: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
595: (adv.)}  has the following meanings:
596: @quotation
597: ... 2b: following next after in order ... 3d: as a necessary consequence
598: (if you were there, then you saw them).
599: @end quotation
600: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
601: and many other programming languages has the meaning 3d.]
602:
603: We also provide the words @code{?dup-if} and @code{?dup-0=-if}, so you
604: can avoid using @code{?dup}.
605:
606: @example
607: @var{n}
608: CASE
609:   @var{n1} OF @var{code1} ENDOF
610:   @var{n2} OF @var{code2} ENDOF
611:   @dots
612: ENDCASE
613: @end example
614:
615: Executes the first @var{codei}, where the @var{ni} is equal to
616: @var{n}. A default case can be added by simply writing the code after
617: the last @code{ENDOF}. It may use @var{n}, which is on top of the stack,
618: but must not consume it.
619:
620: @subsection Simple Loops
621:
622: @example
623: BEGIN
624:   @var{code1}
625:   @var{flag}
626: WHILE
627:   @var{code2}
628: REPEAT
629: @end example
630:
631: @var{code1} is executed and @var{flag} is computed. If it is true,
632: @var{code2} is executed and the loop is restarted; If @var{flag} is false, execution continues after the @code{REPEAT}.
633:
634: @example
635: BEGIN
636:   @var{code}
637:   @var{flag}
638: UNTIL
639: @end example
640:
641: @var{code} is executed. The loop is restarted if @code{flag} is false.
642:
643: @example
644: BEGIN
645:   @var{code}
646: AGAIN
647: @end example
648:
649: This is an endless loop.
650:
651: @subsection Counted Loops
652:
653: The basic counted loop is:
654: @example
655: @var{limit} @var{start}
656: ?DO
657:   @var{body}
658: LOOP
659: @end example
660:
661: This performs one iteration for every integer, starting from @var{start}
662: and up to, but excluding @var{limit}. The counter, aka index, can be
663: accessed with @code{i}. E.g., the loop
664: @example
665: 10 0 ?DO
666:   i .
667: LOOP
668: @end example
669: prints
670: @example
671: 0 1 2 3 4 5 6 7 8 9
672: @end example
673: The index of the innermost loop can be accessed with @code{i}, the index
674: of the next loop with @code{j}, and the index of the third loop with
675: @code{k}.
676:
677: The loop control data are kept on the return stack, so there are some
678: restrictions on mixing return stack accesses and counted loop
679: words. E.g., if you put values on the return stack outside the loop, you
680: cannot read them inside the loop. If you put values on the return stack
681: within a loop, you have to remove them before the end of the loop and
682: before accessing the index of the loop.
683:
684: There are several variations on the counted loop:
685:
686: @code{LEAVE} leaves the innermost counted loop immediately.
687:
688: @code{LOOP} can be replaced with @code{@var{n} +LOOP}; this updates the
689: index by @var{n} instead of by 1. The loop is terminated when the border
690: between @var{limit-1} and @var{limit} is crossed. E.g.:
691:
692: @code{4 0 ?DO  i .  2 +LOOP}   prints @code{0 2}
693:
694: @code{4 1 ?DO  i .  2 +LOOP}   prints @code{1 3}
695:
696: The behaviour of @code{@var{n} +LOOP} is peculiar when @var{n} is negative:
697:
698: @code{-1 0 ?DO  i .  -1 +LOOP}  prints @code{0 -1}
699:
700: @code{ 0 0 ?DO  i .  -1 +LOOP}  prints nothing
701:
702: Therefore we recommend avoiding using @code{@var{n} +LOOP} with negative
703: @var{n}. One alternative is @code{@var{n} S+LOOP}, where the negative
704: case behaves symmetrical to the positive case:
705:
706: @code{-2 0 ?DO  i .  -1 +LOOP}  prints @code{0 -1}
707:
708: @code{-1 0 ?DO  i .  -1 +LOOP}  prints @code{0}
709:
710: @code{ 0 0 ?DO  i .  -1 +LOOP}  prints nothing
711:
712: The loop is terminated when the border between @var{limit@minus{}sgn(n)} and
713: @var{limit} is crossed. However, @code{S+LOOP} is not part of the ANS
714: Forth standard.
715:
716: @code{?DO} can be replaced by @code{DO}. @code{DO} enters the loop even
717: when the start and the limit value are equal. We do not recommend using
718: @code{DO}. It will just give you maintenance troubles.
719:
720: @code{UNLOOP} is used to prepare for an abnormal loop exit, e.g., via
721: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
722: return stack so @code{EXIT} can get to its return address.
723:
724: Another counted loop is
725: @example
726: @var{n}
727: FOR
728:   @var{body}
729: NEXT
730: @end example
731: This is the preferred loop of native code compiler writers who are too
732: lazy to optimize @code{?DO} loops properly. In GNU Forth, this loop
733: iterates @var{n+1} times; @code{i} produces values starting with @var{n}
734: and ending with 0. Other Forth systems may behave differently, even if
735: they support @code{FOR} loops.
736:
737: @subsection Arbitrary control structures
738:
739: ANS Forth permits and supports using control structures in a non-nested
740: way. Information about incomplete control structures is stored on the
741: control-flow stack. This stack may be implemented on the Forth data
742: stack, and this is what we have done in gforth.
743:
744: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
745: entry represents a backward branch target. A few words are the basis for
746: building any control structure possible (except control structures that
747: need storage, like calls, coroutines, and backtracking).
748:
749: doc-if
751: doc-then
752: doc-begin
753: doc-until
754: doc-again
755: doc-cs-pick
756: doc-cs-roll
757:
758: On many systems control-flow stack items take one word, in gforth they
759: currently take three (this may change in the future). Therefore it is a
760: really good idea to manipulate the control flow stack with
761: @code{cs-pick} and @code{cs-roll}, not with data stack manipulation
762: words.
763:
764: Some standard control structure words are built from these words:
765:
766: doc-else
767: doc-while
768: doc-repeat
769:
770: Counted loop words constitute a separate group of words:
771:
772: doc-?do
773: doc-do
774: doc-for
775: doc-loop
776: doc-s+loop
777: doc-+loop
778: doc-next
779: doc-leave
780: doc-?leave
781: doc-unloop
782: doc-undo
783:
784: The standard does not allow using @code{cs-pick} and @code{cs-roll} on
785: @i{do-sys}. Our system allows it, but it's your job to ensure that for
786: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
787: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
788: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
789: resolved (by using one of the loop-ending words or @code{UNDO}).
790:
791: Another group of control structure words are
792:
793: doc-case
794: doc-endcase
795: doc-of
796: doc-endof
797:
798: @i{case-sys} and @i{of-sys} cannot be processed using @code{cs-pick} and
799: @code{cs-roll}.
800:
801: @subsubsection Programming Style
802:
803: In order to ensure readability we recommend that you do not create
804: arbitrary control structures directly, but define new control structure
805: words for the control structure you want and use these words in your
806: program.
807:
809:
810: @example
811: begin
812:   ...
813: if [ 1 cs-roll ]
814:   ...
815: again then
816: @end example
817:
818: we recommend defining control structure words, e.g.,
819:
820: @example
821: : while ( dest -- orig dest )
822:  POSTPONE if
823:  1 cs-roll ; immediate
824:
825: : repeat ( orig dest -- )
826:  POSTPONE again
827:  POSTPONE then ; immediate
828: @end example
829:
830: and then using these to create the control structure:
831:
832: @example
833: begin
834:   ...
835: while
836:   ...
837: repeat
838: @end example
839:
840: That's much easier to read, isn't it? Of course, @code{BEGIN} and
841: @code{WHILE} are predefined, so in this example it would not be
842: necessary to define them.
843:
844: @subsection Calls and returns
845:
846: A definition can be called simply be writing the name of the
847: definition. When the end of the definition is reached, it returns. An earlier return can be forced using
848:
849: doc-exit
850:
851: Don't forget to clean up the return stack and @code{UNLOOP} any
852: outstanding @code{?DO}...@code{LOOP}s before @code{EXIT}ing. The
853: primitive compiled by @code{EXIT} is
854:
855: doc-;s
856:
857: @subsection Exception Handling
858:
859: doc-catch
860: doc-throw
861:
862: @node Locals
863: @section Locals
864:
865: Local variables can make Forth programming more enjoyable and Forth
866: programs easier to read. Unfortunately, the locals of ANS Forth are
867: laden with restrictions. Therefore, we provide not only the ANS Forth
868: locals wordset, but also our own, more powerful locals wordset (we
869: implemented the ANS Forth locals wordset through our locals wordset).
870:
873:
874: @subsection gforth locals
875:
876: Locals can be defined with
877:
878: @example
879: @{ local1 local2 ... -- comment @}
880: @end example
881: or
882: @example
883: @{ local1 local2 ... @}
884: @end example
885:
886: E.g.,
887: @example
888: : max @{ n1 n2 -- n3 @}
889:  n1 n2 > if
890:    n1
891:  else
892:    n2
893:  endif ;
894: @end example
895:
896: The similarity of locals definitions with stack comments is intended. A
897: locals definition often replaces the stack comment of a word. The order
898: of the locals corresponds to the order in a stack comment and everything
899: after the @code{--} is really a comment.
900:
901: This similarity has one disadvantage: It is too easy to confuse locals
902: declarations with stack comments, causing bugs and making them hard to
903: find. However, this problem can be avoided by appropriate coding
904: conventions: Do not use both notations in the same program. If you do,
905: they should be distinguished using additional means, e.g. by position.
906:
907: The name of the local may be preceded by a type specifier, e.g.,
908: @code{F:} for a floating point value:
909:
910: @example
911: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
912: \ complex multiplication
913:  Ar Br f* Ai Bi f* f-
914:  Ar Bi f* Ai Br f* f+ ;
915: @end example
916:
917: GNU Forth currently supports cells (@code{W:}, @code{W^}), doubles
918: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
919: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
920: with @code{W:}, @code{D:} etc.) produces its value and can be changed
921: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
922: produces its address (which becomes invalid when the variable's scope is
923: left). E.g., the standard word @code{emit} can be defined in therms of
924: @code{type} like this:
925:
926: @example
927: : emit @{ C^ char* -- @}
928:     char* 1 type ;
929: @end example
930:
931: A local without type specifier is a @code{W:} local. Both flavours of
932: locals are initialized with values from the data or FP stack.
933:
934: Currently there is no way to define locals with user-defined data
935: structures, but we are working on it.
936:
937: GNU Forth allows defining locals everywhere in a colon definition. This poses the following questions:
938:
939: @subsubsection Where are locals visible by name?
940:
941: Basically, the answer is that locals are visible where you would expect
942: it in block-structured languages, and sometimes a little longer. If you
943: want to restrict the scope of a local, enclose its definition in
944: @code{SCOPE}...@code{ENDSCOPE}.
945:
946: doc-scope
947: doc-endscope
948:
949: These words behave like control structure words, so you can use them
950: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
951: arbitrary ways.
952:
953: If you want a more exact answer to the visibility question, here's the
954: basic principle: A local is visible in all places that can only be
955: reached through the definition of the local@footnote{In compiler
956: construction terminology, all places dominated by the definition of the
957: local.}. In other words, it is not visible in places that can be reached
958: without going through the definition of the local. E.g., locals defined
959: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
960: defined in @code{BEGIN}...@code{UNTIL} are visible after the
961: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
962:
963: The reasoning behind this solution is: We want to have the locals
964: visible as long as it is meaningful. The user can always make the
965: visibility shorter by using explicit scoping. In a place that can
966: only be reached through the definition of a local, the meaning of a
967: local name is clear. In other places it is not: How is the local
968: initialized at the control flow path that does not contain the
969: definition? Which local is meant, if the same name is defined twice in
970: two independent control flow paths?
971:
972: This should be enough detail for nearly all users, so you can skip the
973: rest of this section. If you relly must know all the gory details and
975:
976: In order to implement this rule, the compiler has to know which places
977: are unreachable. It knows this automatically after @code{AHEAD},
978: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
979: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
980: compiler that the control flow never reaches that place. If
981: @code{UNREACHABLE} is not used where it could, the only consequence is
982: that the visibility of some locals is more limited than the rule above
983: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
984: lie to the compiler), buggy code will be produced.
985:
986: Another problem with this rule is that at @code{BEGIN}, the compiler
987: does not know which locals will be visible on the incoming
988: back-edge. All problems discussed in the following are due to this
989: ignorance of the compiler (we discuss the problems using @code{BEGIN}
990: loops as examples; the discussion also applies to @code{?DO} and other
991: loops). Perhaps the most insidious example is:
992: @example
994: BEGIN
995:   x
996: [ 1 CS-ROLL ] THEN
997:   { x }
998:   ...
999: UNTIL
1000: @end example
1001:
1002: This should be legal according to the visibility rule. The use of
1003: @code{x} can only be reached through the definition; but that appears
1004: textually below the use.
1005:
1006: From this example it is clear that the visibility rules cannot be fully
1007: implemented without major headaches. Our implementation treats common
1008: cases as advertised and the exceptions are treated in a safe way: The
1009: compiler makes a reasonable guess about the locals visible after a
1010: @code{BEGIN}; if it is too pessimistic, the
1011: user will get a spurious error about the local not being defined; if the
1012: compiler is too optimistic, it will notice this later and issue a
1013: warning. In the case above the compiler would complain about @code{x}
1014: being undefined at its use. You can see from the obscure examples in
1015: this section that it takes quite unusual control structures to get the
1016: compiler into trouble, and even then it will often do fine.
1017:
1018: If the @code{BEGIN} is reachable from above, the most optimistic guess
1019: is that all locals visible before the @code{BEGIN} will also be
1020: visible after the @code{BEGIN}. This guess is valid for all loops that
1021: are entered only through the @code{BEGIN}, in particular, for normal
1022: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
1023: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
1024: compiler. When the branch to the @code{BEGIN} is finally generated by
1025: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
1026: warns the user if it was too optimisitic:
1027: @example
1028: IF
1029:   { x }
1030: BEGIN
1031:   \ x ?
1032: [ 1 cs-roll ] THEN
1033:   ...
1034: UNTIL
1035: @end example
1036:
1037: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
1038: optimistically assumes that it lives until the @code{THEN}. It notices
1039: this difference when it compiles the @code{UNTIL} and issues a
1040: warning. The user can avoid the warning, and make sure that @code{x}
1041: is not used in the wrong area by using explicit scoping:
1042: @example
1043: IF
1044:   SCOPE
1045:   { x }
1046:   ENDSCOPE
1047: BEGIN
1048: [ 1 cs-roll ] THEN
1049:   ...
1050: UNTIL
1051: @end example
1052:
1053: Since the guess is optimistic, there will be no spurious error messages
1055:
1056: If the @code{BEGIN} is not reachable from above (e.g., after
1057: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
1058: optimistic guess, as the locals visible after the @code{BEGIN} may be
1059: defined later. Therefore, the compiler assumes that no locals are
1060: visible after the @code{BEGIN}. However, the useer can use
1061: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
1062: visible at the BEGIN as at the point where the item was created.
1063:
1064: doc-assume-live
1065:
1066: E.g.,
1067: @example
1068: { x }
1070: ASSUME-LIVE
1071: BEGIN
1072:   x
1073: [ 1 CS-ROLL ] THEN
1074:   ...
1075: UNTIL
1076: @end example
1077:
1078: Other cases where the locals are defined before the @code{BEGIN} can be
1079: handled by inserting an appropriate @code{CS-ROLL} before the
1080: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
1081: behind the @code{ASSUME-LIVE}).
1082:
1083: Cases where locals are defined after the @code{BEGIN} (but should be
1084: visible immediately after the @code{BEGIN}) can only be handled by
1085: rearranging the loop. E.g., the most insidious'' example above can be
1086: arranged into:
1087: @example
1088: BEGIN
1089:   { x }
1090:   ... 0=
1091: WHILE
1092:   x
1093: REPEAT
1094: @end example
1095:
1096: @subsubsection How long do locals live?
1097:
1098: The right answer for the lifetime question would be: A local lives at
1099: least as long as it can be accessed. For a value-flavoured local this
1100: means: until the end of its visibility. However, a variable-flavoured
1101: local could be accessed through its address far beyond its visibility
1102: scope. Ultimately, this would mean that such locals would have to be
1103: garbage collected. Since this entails un-Forth-like implementation
1104: complexities, I adopted the same cowardly solution as some other
1105: languages (e.g., C): The local lives only as long as it is visible;
1106: afterwards its address is invalid (and programs that access it
1107: afterwards are erroneous).
1108:
1109: @subsubsection Programming Style
1110:
1111: The freedom to define locals anywhere has the potential to change
1112: programming styles dramatically. In particular, the need to use the
1113: return stack for intermediate storage vanishes. Moreover, all stack
1114: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
1115: determined arguments) can be eliminated: If the stack items are in the
1116: wrong order, just write a locals definition for all of them; then
1117: write the items in the order you want.
1118:
1119: This seems a little far-fetched and eliminating stack manipulations is
1120: unlikely to become a conscious programming objective. Still, the
1121: number of stack manipulations will be reduced dramatically if local
1122: variables are used liberally (e.g., compare @code{max} in \sect{misc}
1123: with a traditional implementation of @code{max}).
1124:
1125: This shows one potential benefit of locals: making Forth programs more
1126: readable. Of course, this benefit will only be realized if the
1127: programmers continue to honour the principle of factoring instead of
1128: using the added latitude to make the words longer.
1129:
1130: Using @code{TO} can and should be avoided.  Without @code{TO},
1131: every value-flavoured local has only a single assignment and many
1132: advantages of functional languages apply to Forth. I.e., programs are
1133: easier to analyse, to optimize and to read: It is clear from the
1134: definition what the local stands for, it does not turn into something
1135: different later.
1136:
1137: E.g., a definition using @code{TO} might look like this:
1138: @example
1140:  u1 u2 min 0
1141:  ?do
1143:    if
1144:      unloop exit
1145:    then
1148:  loop
1149:  u1 u2 - ;
1150: @end example
1152: every loop iteration. @code{strcmp} is a typical example of the
1154: @code{strcmp}, you think that @code{addr1} refers to the start of the
1155: string. Only near the end of the loop you realize that it is something
1156: else.
1157:
1158: This can be avoided by defining two locals at the start of the loop that
1159: are initialized with the right value for the current iteration.
1160: @example
1163:  u1 u2 min 0
1164:  ?do @{ s1 s2 @}
1165:    s1 c@ s2 c@ - ?dup
1166:    if
1167:      unloop exit
1168:    then
1169:    s1 char+ s2 char+
1170:  loop
1171:  2drop
1172:  u1 u2 - ;
1173: @end example
1174: Here it is clear from the start that @code{s1} has a different value
1175: in every loop iteration.
1176:
1177: @subsubsection Implementation
1178:
1179: GNU Forth uses an extra locals stack. The most compelling reason for
1180: this is that the return stack is not float-aligned; using an extra stack
1181: also eliminates the problems and restrictions of using the return stack
1182: as locals stack. Like the other stacks, the locals stack grows toward
1183: lower addresses. A few primitives allow an efficient implementation:
1184:
1185: doc-@local#
1186: doc-f@local#
1188: doc-lp+!#
1189: doc-lp!
1190: doc->l
1191: doc-f>l
1192:
1193: In addition to these primitives, some specializations of these
1194: primitives for commonly occurring inline arguments are provided for
1195: efficiency reasons, e.g., @code{@@local0} as specialization of
1196: @code{@@local#} for the inline argument 0. The following compiling words
1197: compile the right specialized version, or the general version, as
1198: appropriate:
1199:
1200: doc-compile-@@local
1201: doc-compile-f@@local
1202: doc-compile-lp+!
1203:
1204: Combinations of conditional branches and @code{lp+!#} like
1205: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
1206: is taken) are provided for efficiency and correctness in loops.
1207:
1208: A special area in the dictionary space is reserved for keeping the
1209: local variable names. @code{@{} switches the dictionary pointer to this
1210: area and @code{@}} switches it back and generates the locals
1211: initializing code. @code{W:} etc.@ are normal defining words. This
1212: special area is cleared at the start of every colon definition.
1213:
1214: A special feature of GNU Forths dictionary is used to implement the
1215: definition of locals without type specifiers: every wordlist (aka
1216: vocabulary) has its own methods for searching
1217: etc. (@xref{dictionary}). For the present purpose we defined a wordlist
1218: with a special search method: When it is searched for a word, it
1219: actually creates that word using @code{W:}. @code{@{} changes the search
1220: order to first search the wordlist containing @code{@}}, @code{W:} etc.,
1221: and then the wordlist for defining locals without type specifiers.
1222:
1223: The lifetime rules support a stack discipline within a colon
1224: definition: The lifetime of a local is either nested with other locals
1225: lifetimes or it does not overlap them.
1226:
1227: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
1228: pointer manipulation is generated. Between control structure words
1229: locals definitions can push locals onto the locals stack. @code{AGAIN}
1230: is the simplest of the other three control flow words. It has to
1231: restore the locals stack depth of the corresponding @code{BEGIN}
1232: before branching. The code looks like this:
1233: @format
1234: @code{lp+!#} current-locals-size @minus{} dest-locals-size
1235: @code{branch} <begin>
1236: @end format
1237:
1238: @code{UNTIL} is a little more complicated: If it branches back, it
1239: must adjust the stack just like @code{AGAIN}. But if it falls through,
1240: the locals stack must not be changed. The compiler generates the
1241: following code:
1242: @format
1243: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
1244: @end format
1245: The locals stack pointer is only adjusted if the branch is taken.
1246:
1247: @code{THEN} can produce somewhat inefficient code:
1248: @format
1249: @code{lp+!#} current-locals-size @minus{} orig-locals-size
1250: <orig target>:
1251: @code{lp+!#} orig-locals-size @minus{} new-locals-size
1252: @end format
1253: The second @code{lp+!#} adjusts the locals stack pointer from the
1254: level at the {\em orig} point to the level after the @code{THEN}. The
1255: first @code{lp+!#} adjusts the locals stack pointer from the current
1256: level to the level at the orig point, so the complete effect is an
1257: adjustment from the current level to the right level after the
1258: @code{THEN}.
1259:
1260: In a conventional Forth implementation a dest control-flow stack entry
1261: is just the target address and an orig entry is just the address to be
1262: patched. Our locals implementation adds a wordlist to every orig or dest
1263: item. It is the list of locals visible (or assumed visible) at the point
1264: described by the entry. Our implementation also adds a tag to identify
1265: the kind of entry, in particular to differentiate between live and dead
1266: (reachable and unreachable) orig entries.
1267:
1268: A few unusual operations have to be performed on locals wordlists:
1269:
1270: doc-common-list
1271: doc-sub-list?
1272: doc-list-size
1273:
1274: Several features of our locals wordlist implementation make these
1275: operations easy to implement: The locals wordlists are organised as
1276: linked lists; the tails of these lists are shared, if the lists
1277: contain some of the same locals; and the address of a name is greater
1278: than the address of the names behind it in the list.
1279:
1280: Another important implementation detail is the variable
1281: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
1282: determine if they can be reached directly or only through the branch
1283: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
1284: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
1285: definition, by @code{BEGIN} and usually by @code{THEN}.
1286:
1287: Counted loops are similar to other loops in most respects, but
1288: @code{LEAVE} requires special attention: It performs basically the same
1289: service as @code{AHEAD}, but it does not create a control-flow stack
1290: entry. Therefore the information has to be stored elsewhere;
1291: traditionally, the information was stored in the target fields of the
1292: branches created by the @code{LEAVE}s, by organizing these fields into a
1293: linked list. Unfortunately, this clever trick does not provide enough
1294: space for storing our extended control flow information. Therefore, we
1295: introduce another stack, the leave stack. It contains the control-flow
1296: stack entries for all unresolved @code{LEAVE}s.
1297:
1298: Local names are kept until the end of the colon definition, even if
1299: they are no longer visible in any control-flow path. In a few cases
1300: this may lead to increased space needs for the locals name area, but
1301: usually less than reclaiming this space would cost in code size.
1302:
1303:
1304: @subsection ANS Forth locals
1305:
1306: The ANS Forth locals wordset does not define a syntax for locals, but
1307: words that make it possible to define various syntaxes. One of the
1308: possible syntaxes is a subset of the syntax we used in the gforth locals
1309: wordset, i.e.:
1310:
1311: @example
1312: @{ local1 local2 ... -- comment @}
1313: @end example
1314: or
1315: @example
1316: @{ local1 local2 ... @}
1317: @end example
1318:
1319: The order of the locals corresponds to the order in a stack comment. The
1320: restrictions are:
1321:
1322: @itemize @bullet
1323: @item
1324: Locals can only be cell-sized values (no type specifers are allowed).
1325: @item
1326: Locals can be defined only outside control structures.
1327: @item
1328: Locals can interfere with explicit usage of the return stack. For the
1329: exact (and long) rules, see the standard. If you don't use return stack
1330: accessing words in a definition using locals, you will we all right. The
1331: purpose of this rule is to make locals implementation on the return
1332: stack easier.
1333: @item
1334: The whole definition must be in one line.
1335: @end itemize
1336:
1337: Locals defined in this way behave like @code{VALUE}s
1338: (@xref{values}). I.e., they are initialized from the stack. Using their
1339: name produces their value. Their value can be changed using @code{TO}.
1340:
1341: Since this syntax is supported by gforth directly, you need not do
1342: anything to use it. If you want to port a program using this syntax to
1343: another ANS Forth system, use @file{anslocal.fs} to implement the syntax
1344: on the other system.
1345:
1346: Note that a syntax shown in the standard, section A.13 looks
1347: similar, but is quite different in having the order of locals
1348: reversed. Beware!
1349:
1350: The ANS Forth locals wordset itself consists of the following word
1351:
1352: doc-(local)
1353:
1354: The ANS Forth locals extension wordset defines a syntax, but it is so
1355: awful that we strongly recommend not to use it. We have implemented this
1356: syntax to make porting to gforth easy, but do not document it here. The
1357: problem with this syntax is that the locals are defined in an order
1358: reversed with respect to the standard stack comment notation, making
1359: programs harder to read, and easier to misread and miswrite. The only
1360: merit of this syntax is that it is easy to implement using the ANS Forth
1361: locals wordset.
1362:
1363: @node Internals
1364: @chapter Internals
1365:
1366: Reading this section is not necessary for programming with gforth. It
1367: should be helpful for finding your way in the gforth sources.
1368:
1369: @section Portability
1370:
1371: One of the main goals of the effort is availability across a wide range
1372: of personal machines. fig-Forth, and, to a lesser extent, F83, achieved
1373: this goal by manually coding the engine in assembly language for several
1374: then-popular processors. This approach is very labor-intensive and the
1375: results are short-lived due to progress in computer architecture.
1376:
1377: Others have avoided this problem by coding in C, e.g., Mitch Bradley
1378: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
1379: particularly popular for UNIX-based Forths due to the large variety of
1380: architectures of UNIX machines. Unfortunately an implementation in C
1381: does not mix well with the goals of efficiency and with using
1383: in C, and switch threading, the fastest technique available in C, is
1384: significantly slower. Another problem with C is that it's very
1385: cumbersome to express double integer arithmetic.
1386:
1387: Fortunately, there is a portable language that does not have these
1388: limitations: GNU C, the version of C processed by the GNU C compiler
1389: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
1390: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
1391: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
1392: threading possible, its @code{long long} type (@pxref{Long Long, ,
1393: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forths
1394: double numbers. GNU C is available for free on all important (and many
1395: unimportant) UNIX machines, VMS, 80386s running MS-DOS, the Amiga, and
1396: the Atari ST, so a Forth written in GNU C can run on all these
1397: machines@footnote{Due to Apple's look-and-feel lawsuit it is not
1398: available on the Mac (@pxref{Boycott, , Protect Your Freedom--Fight
1399: Look And Feel'', gcc.info, GNU C Manual}).}.
1400:
1401: Writing in a portable language has the reputation of producing code that
1402: is slower than assembly. For our Forth engine we repeatedly looked at
1403: the code produced by the compiler and eliminated most compiler-induced
1404: inefficiencies by appropriate changes in the source-code.
1405:
1406: However, register allocation cannot be portably influenced by the
1407: programmer, leading to some inefficiencies on register-starved
1408: machines. We use explicit register declarations (@pxref{Explicit Reg
1409: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
1410: improve the speed on some machines. They are turned on by using the
1411: @code{gcc} switch @code{-DFORCE_REG}. Unfortunately, this feature not
1412: only depends on the machine, but also on the compiler version: On some
1413: machines some compiler versions produce incorrect code when certain
1414: explicit register declarations are used. So by default
1415: @code{-DFORCE_REG} is not used.
1416:
1418:
1419: GNU C's labels as values extension (available since @code{gcc-2.0},
1420: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1421: makes it possible to take the address of @var{label} by writing
1422: @code{&&@var{label}}.  This address can then be used in a statement like
1423: @code{goto *@var{address}}. I.e., @code{goto *&&x} is the same as
1424: @code{goto x}.
1425:
1426: With this feature an indirect threaded NEXT looks like:
1427: @example
1428: cfa = *ip++;
1429: ca = *cfa;
1430: goto *ca;
1431: @end example
1432: For those unfamiliar with the names: @code{ip} is the Forth instruction
1433: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
1434: execution token and points to the code field of the next word to be
1435: executed; The @code{ca} (code address) fetched from there points to some
1436: executable code, e.g., a primitive or the colon definition handler
1437: @code{docol}.
1438:
1439: Direct threading is even simpler:
1440: @example
1441: ca = *ip++;
1442: goto *ca;
1443: @end example
1444:
1445: Of course we have packaged the whole thing neatly in macros called
1446: @code{NEXT} and @code{NEXT1} (the part of NEXT after fetching the cfa).
1447:
1448: @subsection Scheduling
1449:
1450: There is a little complication: Pipelined and superscalar processors,
1451: i.e., RISC and some modern CISC machines can process independent
1452: instructions while waiting for the results of an instruction. The
1453: compiler usually reorders (schedules) the instructions in a way that
1454: achieves good usage of these delay slots. However, on our first tries
1455: the compiler did not do well on scheduling primitives. E.g., for
1456: @code{+} implemented as
1457: @example
1458: n=sp[0]+sp[1];
1459: sp++;
1460: sp[0]=n;
1461: NEXT;
1462: @end example
1463: the NEXT comes strictly after the other code, i.e., there is nearly no
1464: scheduling. After a little thought the problem becomes clear: The
1465: compiler cannot know that sp and ip point to different addresses (and
1466: the version of @code{gcc} we used would not know it even if it could),
1467: so it could not move the load of the cfa above the store to the
1468: TOS. Indeed the pointers could be the same, if code on or very near the
1469: top of stack were executed. In the interest of speed we chose to forbid
1470: this probably unused feature'' and helped the compiler in scheduling:
1471: NEXT is divided into the loading part (@code{NEXT_P1}) and the goto part
1472: (@code{NEXT_P2}). @code{+} now looks like:
1473: @example
1474: n=sp[0]+sp[1];
1475: sp++;
1476: NEXT_P1;
1477: sp[0]=n;
1478: NEXT_P2;
1479: @end example
1480: This can be scheduled optimally by the compiler (see \sect{TOS}).
1481:
1482: This division can be turned off with the switch @code{-DCISC_NEXT}. This
1483: switch is on by default on machines that do not profit from scheduling
1484: (e.g., the 80386), in order to preserve registers.
1485:
1486: @subsection Direct or Indirect Threaded?
1487:
1488: Both! After packaging the nasty details in macro definitions we
1489: realized that we could switch between direct and indirect threading by
1490: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
1491: defining a few machine-specific macros for the direct-threading case.
1492: On the Forth level we also offer access words that hide the
1494:
1495: Indirect threading is implemented completely
1496: machine-independently. Direct threading needs routines for creating
1497: jumps to the executable code (e.g. to docol or dodoes). These routines
1498: are inherently machine-dependent, but they do not amount to many source
1499: lines. I.e., even porting direct threading to a new machine is a small
1500: effort.
1501:
1502: @subsection DOES>
1503: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
1504: the chunk of code executed by every word defined by a
1505: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
1506: the Forth code to be executed, i.e. the code after the @code{DOES>} (the
1507: DOES-code)? There are two solutions:
1508:
1509: In fig-Forth the code field points directly to the dodoes and the
1510: DOES-code address is stored in the cell after the code address
1511: (i.e. at cfa cell+). It may seem that this solution is illegal in the
1512: Forth-79 and all later standards, because in fig-Forth this address
1513: lies in the body (which is illegal in these standards). However, by
1514: making the code field larger for all words this solution becomes legal
1515: again. We use this approach for the indirect threaded version. Leaving
1516: a cell unused in most words is a bit wasteful, but on the machines we
1517: are targetting this is hardly a problem. The other reason for having a
1518: code field size of two cells is to avoid having different image files
1519: for direct and indirect threaded systems (@pxref{image-format}).
1520:
1521: The other approach is that the code field points or jumps to the cell
1522: after @code{DOES}. In this variant there is a jump to @code{dodoes} at
1525: and add the length of that jump field. A variant of this is to have a
1526: call to @code{dodoes} after the @code{DOES>}; then the return address
1527: (which can be found in the return register on RISCs) is the DOES-code
1528: address. Since the two cells available in the code field are usually
1530: this approach for direct threading. We did not want to add another
1531: cell to the code field.
1532:
1533: @section Primitives
1534:
1535: @subsection Automatic Generation
1536:
1537: Since the primitives are implemented in a portable language, there is no
1538: longer any need to minimize the number of primitives. On the contrary,
1539: having many primitives is an advantage: speed. In order to reduce the
1540: number of errors in primitives and to make programming them easier, we
1541: provide a tool, the primitive generator (@file{prims2x.fs}), that
1542: automatically generates most (and sometimes all) of the C code for a
1543: primitive from the stack effect notation.  The source for a primitive
1544: has the following form:
1545:
1546: @format
1547: @var{Forth-name}	@var{stack-effect}	@var{category}	[@var{pronounc.}]
1548: [@code{""}@var{glossary entry}@code{""}]
1549: @var{C code}
1550: [@code{:}
1551: @var{Forth code}]
1552: @end format
1553:
1554: The items in brackets are optional. The category and glossary fields
1555: are there for generating the documentation, the Forth code is there
1556: for manual implementations on machines without GNU C. E.g., the source
1557: for the primitive @code{+} is:
1558: @example
1559: +    n1 n2 -- n    core    plus
1560: n = n1+n2;
1561: @end example
1562:
1563: This looks like a specification, but in fact @code{n = n1+n2} is C
1564: code. Our primitive generation tool extracts a lot of information from
1565: the stack effect notations@footnote{We use a one-stack notation, even
1566: though we have separate data and floating-point stacks; The separate
1567: notation can be generated easily from the unified notation.}: The number
1568: of items popped from and pushed on the stack, their type, and by what
1569: name they are referred to in the C code. It then generates a C code
1570: prelude and postlude for each primitive. The final C code for @code{+}
1571: looks like this:
1572:
1573: @example
1574: I_plus:	/* + ( n1 n2 -- n ) */  /* label, stack effect */
1575: /*  */                          /* documentation */
1576: {
1577: DEF_CA                          /* definition of variable ca (indirect threading) */
1578: Cell n1;                        /* definitions of variables */
1579: Cell n2;
1580: Cell n;
1581: n1 = (Cell) sp[1];              /* input */
1582: n2 = (Cell) TOS;
1583: sp += 1;                        /* stack adjustment */
1584: NAME("+")                       /* debugging output (with -DDEBUG) */
1585: {
1586: n = n1+n2;                      /* C code taken from the source */
1587: }
1588: NEXT_P1;                        /* NEXT part 1 */
1589: TOS = (Cell)n;                  /* output */
1590: NEXT_P2;                        /* NEXT part 2 */
1591: }
1592: @end example
1593:
1594: This looks long and inefficient, but the GNU C compiler optimizes quite
1595: well and produces optimal code for @code{+} on, e.g., the R3000 and the
1596: HP RISC machines: Defining the @code{n}s does not produce any code, and
1597: using them as intermediate storage also adds no cost.
1598:
1599: There are also other optimizations, that are not illustrated by this
1601: propagation). If one of the stack items is not used by the primitive
1602: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
1603: (dead code elimination). On the other hand, there are some things that
1604: the compiler does not do, therefore they are performed by
1605: @file{prims2x.fs}: The compiler does not optimize code away that stores
1606: a stack item to the place where it just came from (e.g., @code{over}).
1607:
1608: While programming a primitive is usually easy, there are a few cases
1609: where the programmer has to take the actions of the generator into
1610: account, most notably @code{?dup}, but also words that do not (always)
1611: fall through to NEXT.
1612:
1613: @subsection TOS Optimization
1614:
1615: An important optimization for stack machine emulators, e.g., Forth
1616: engines, is keeping  one or more of the top stack items in
1617: registers.  If a word has the stack effect {@var{in1}...@var{inx} @code{--}
1618: @var{out1}...@var{outy}}, keeping the top @var{n} items in registers
1619: @itemize
1620: @item
1621: is better than keeping @var{n-1} items, if @var{x>=n} and @var{y>=n},
1622: due to fewer loads from and stores to the stack.
1623: @item is slower than keeping @var{n-1} items, if @var{x<>y} and @var{x<n} and
1624: @var{y<n}, due to additional moves between registers.
1625: @end itemize
1626:
1627: In particular, keeping one item in a register is never a disadvantage,
1628: if there are enough registers. Keeping two items in registers is a
1629: disadvantage for frequent words like @code{?branch}, constants,
1630: variables, literals and @code{i}. Therefore our generator only produces
1631: code that keeps zero or one items in registers. The generated C code
1632: covers both cases; the selection between these alternatives is made at
1633: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
1634: code for @code{+} is just a simple variable name in the one-item case,
1635: otherwise it is a macro that expands into @code{sp[0]}. Note that the
1636: GNU C compiler tries to keep simple variables like @code{TOS} in
1637: registers, and it usually succeeds, if there are enough registers.
1638:
1639: The primitive generator performs the TOS optimization for the
1640: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
1641: operations the benefit of this optimization is even larger:
1642: floating-point operations take quite long on most processors, but can be
1643: performed in parallel with other operations as long as their results are
1644: not used. If the FP-TOS is kept in a register, this works. If
1645: it is kept on the stack, i.e., in memory, the store into memory has to
1646: wait for the result of the floating-point operation, lengthening the
1647: execution time of the primitive considerably.
1648:
1649: The TOS optimization makes the automatic generation of primitives a
1650: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
1651: @code{TOS} is not sufficient. There are some special cases to
1652: consider:
1653: @itemize
1654: @item In the case of @code{dup ( w -- w w )} the generator must not
1655: eliminate the store to the original location of the item on the stack,
1656: if the TOS optimization is turned on.
1657: @item Primitives with stack effects of the form {@code{--}
1658: @var{out1}...@var{outy}} must store the TOS to the stack at the start.
1659: Likewise, primitives with the stack effect {@var{in1}...@var{inx} @code{--}}
1660: must load the TOS from the stack at the end. But for the null stack
1661: effect @code{--} no stores or loads should be generated.
1662: @end itemize
1663:
1664: @subsection Produced code
1665:
1666: To see what assembly code is produced for the primitives on your machine
1667: with your compiler and your flag settings, type @code{make engine.s} and
1668: look at the resulting file @file{engine.c}.
1669:
1670: @section System Architecture
1671:
1672: Our Forth system consists not only of primitives, but also of
1673: definitions written in Forth. Since the Forth compiler itself belongs
1674: to those definitions, it is not possible to start the system with the
1675: primitives and the Forth source alone. Therefore we provide the Forth
1676: code as an image file in nearly executable form. At the start of the
1677: system a C routine loads the image file into memory, sets up the
1678: memory (stacks etc.) according to information in the image file, and
1679: starts executing Forth code.
1680:
1681: The image file format is a compromise between the goals of making it
1682: easy to generate image files and making them portable. The easiest way
1683: to generate an image file is to just generate a memory dump. However,
1684: this kind of image file cannot be used on a different machine, or on
1685: the next version of the engine on the same machine, it even might not
1686: work with the same engine compiled by a different version of the C
1687: compiler. We would like to have as few versions of the image file as
1688: possible, because we do not want to distribute many versions of the
1689: same image file, and to make it easy for the users to use their image
1690: files on many machines. We currently need to create a different image
1691: file for machines with different cell sizes and different byte order
1692: (little- or big-endian)@footnote{We consider adding information to the
1693: image file that enables the loader to change the byte order.}.
1694:
1695: Forth code that is going to end up in a portable image file has to
1696: comply to some restrictions: addresses have to be stored in memory
1697: with special words (@code{A!}, @code{A,}, etc.) in order to make the
1698: code relocatable. Cells, floats, etc., have to be stored at the
1699: natural alignment boundaries@footnote{E.g., store floats (8 bytes) at
1700: an address dividable by~8. This happens automatically in our system
1701: when you use the ANSI alignment words.}, in order to avoid alignment
1702: faults on machines with stricter alignment. The image file is produced
1703: by a metacompiler (@file{cross.fs}).
1704:
1705: So, unlike the image file of Mitch Bradleys @code{cforth}, our image
1706: file is not directly executable, but has to undergo some manipulations