[gforth] / gforth / Attic / gforth.ds  

gforth: gforth/Attic/gforth.ds


1 : anton 1.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 : anton 1.4 @setfilename gforth.info
5 : anton 1.17 @settitle Gforth Manual
6 : anton 1.4 @comment @setchapternewpage odd
7 : anton 1.1 @comment %**end of header (This is for running Texinfo on a region.)
8 :    
9 :     @ifinfo
10 : anton 1.17 This file documents Gforth 0.1
11 : anton 1.1
12 : anton 1.17 Copyright @copyright{} 1994 Gforth Development Group
13 : anton 1.1
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 : anton 1.4 @ignore
19 : anton 1.1 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 : anton 1.4 @end ignore
25 : anton 1.1 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 : anton 1.17 @center @titlefont{Gforth Manual}
42 : anton 1.1 @sp 2
43 : anton 1.17 @center for version 0.1
44 : anton 1.1 @sp 2
45 :     @center Anton Ertl
46 : anton 1.17 @sp 3
47 :     @center This manual is under construction
48 : anton 1.1
49 :     @comment The following two commands start the copyright page.
50 :     @page
51 :     @vskip 0pt plus 1filll
52 : anton 1.17 Copyright @copyright{} 1994 Gforth Development Group
53 : anton 1.1
54 :     @comment !! Published by ... or You can get a copy of this manual ...
55 :    
56 :     Permission is granted to make and distribute verbatim copies of
57 :     this manual provided the copyright notice and this permission notice
58 :     are preserved on all copies.
59 :    
60 :     Permission is granted to copy and distribute modified versions of this
61 :     manual under the conditions for verbatim copying, provided also that the
62 :     sections entitled "Distribution" and "General Public License" are
63 :     included exactly as in the original, and provided that the entire
64 :     resulting derived work is distributed under the terms of a permission
65 :     notice identical to this one.
66 :    
67 :     Permission is granted to copy and distribute translations of this manual
68 :     into another language, under the above conditions for modified versions,
69 :     except that the sections entitled "Distribution" and "General Public
70 :     License" may be included in a translation approved by the author instead
71 :     of in the original English.
72 :     @end titlepage
73 :    
74 :    
75 :     @node Top, License, (dir), (dir)
76 :     @ifinfo
77 : anton 1.17 Gforth is a free implementation of ANS Forth available on many
78 : anton 1.1 personal machines. This manual corresponds to version 0.0.
79 :     @end ifinfo
80 :    
81 :     @menu
82 : anton 1.4 * License::
83 : anton 1.17 * Goals:: About the Gforth Project
84 : anton 1.4 * Other Books:: Things you might want to read
85 : anton 1.17 * Invocation:: Starting Gforth
86 :     * Words:: Forth words available in Gforth
87 : anton 1.4 * ANS conformance:: Implementation-defined options etc.
88 : anton 1.17 * Model:: The abstract machine of Gforth
89 :     * Emacs and Gforth:: The Gforth Mode
90 : anton 1.4 * Internals:: Implementation details
91 :     * Bugs:: How to report them
92 : anton 1.17 * Pedigree:: Ancestors of Gforth
93 : anton 1.4 * Word Index:: An item for each Forth word
94 :     * Node Index:: An item for each node
95 : anton 1.1 @end menu
96 :    
97 :     @node License, Goals, Top, Top
98 :     @unnumbered License
99 :     !! Insert GPL here
100 :    
101 :     @iftex
102 :     @unnumbered Preface
103 : anton 1.17 This manual documents Gforth. The reader is expected to know
104 : anton 1.1 Forth. This manual is primarily a reference manual. @xref{Other Books}
105 :     for introductory material.
106 :     @end iftex
107 :    
108 :     @node Goals, Other Books, License, Top
109 :     @comment node-name, next, previous, up
110 : anton 1.17 @chapter Goals of Gforth
111 : anton 1.1 @cindex Goals
112 : anton 1.17 The goal of the Gforth Project is to develop a standard model for
113 : anton 1.1 ANSI Forth. This can be split into several subgoals:
114 :    
115 :     @itemize @bullet
116 :     @item
117 : anton 1.17 Gforth should conform to the ANSI Forth standard.
118 : anton 1.1 @item
119 :     It should be a model, i.e. it should define all the
120 :     implementation-dependent things.
121 :     @item
122 :     It should become standard, i.e. widely accepted and used. This goal
123 :     is the most difficult one.
124 :     @end itemize
125 :    
126 : anton 1.17 To achieve these goals Gforth should be
127 : anton 1.1 @itemize @bullet
128 :     @item
129 :     Similar to previous models (fig-Forth, F83)
130 :     @item
131 :     Powerful. It should provide for all the things that are considered
132 :     necessary today and even some that are not yet considered necessary.
133 :     @item
134 :     Efficient. It should not get the reputation of being exceptionally
135 :     slow.
136 :     @item
137 :     Free.
138 :     @item
139 :     Available on many machines/easy to port.
140 :     @end itemize
141 :    
142 : anton 1.17 Have we achieved these goals? Gforth conforms to the ANS Forth
143 :     standard. It may be considered a model, but we have not yet documented
144 : anton 1.1 which parts of the model are stable and which parts we are likely to
145 : anton 1.17 change. It certainly has not yet become a de facto standard. It has some
146 :     similarities and some differences to previous models. It has some
147 :     powerful features, but not yet everything that we envisioned. We
148 :     certainly have achieved our execution speed goals (@pxref{Performance}).
149 :     It is free and available on many machines.
150 : anton 1.1
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 : anton 1.17 is not recommended to learn Forth by using Gforth and a book that is
156 : anton 1.1 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 : anton 1.17 Gforth image will be invoked like this:
177 : anton 1.1
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}
196 :     Loads the Forth image @var{file} instead of the default
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 : anton 1.4 @node Words, ANS conformance, Invocation, Top
257 : anton 1.1 @chapter Forth Words
258 :    
259 :     @menu
260 : anton 1.4 * 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 : anton 1.1 @end menu
274 :    
275 :     @node Notation, Arithmetic, Words, Words
276 :     @section Notation
277 :    
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.
280 :    
281 : anton 1.4 @format
282 : anton 1.1 @var{word} @var{Stack effect} @var{wordset} @var{pronunciation}
283 : anton 1.4 @end format
284 : anton 1.1 @var{Description}
285 :    
286 :     @table @var
287 :     @item word
288 : anton 1.17 The name of the word. BTW, Gforth is case insensitive, so you can
289 : anton 1.14 type the words in in lower case (However, @pxref{core-idef}).
290 : anton 1.1
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 : anton 1.17 i.e., a stack sequence is written as it is typed in. Note that Gforth
297 : anton 1.1 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.
302 :    
303 :     @item pronunciation
304 :     How the word is pronounced
305 :    
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.
313 :    
314 :     @item Description
315 :     A description of the behaviour of the word.
316 :     @end table
317 :    
318 : anton 1.4 The type of a stack item is specified by the character(s) the name
319 :     starts with:
320 : anton 1.1
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
355 :    
356 : anton 1.4 @node Arithmetic, Stack Manipulation, Notation, Words
357 : anton 1.1 @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 : anton 1.4 former, @pxref{Mixed precision}).
367 :    
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
375 : anton 1.1
376 : anton 1.4 @node Single precision, Bitwise operations, Arithmetic, Arithmetic
377 : anton 1.1 @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
388 :    
389 : anton 1.4 @node Bitwise operations, Mixed precision, Single precision, Arithmetic
390 : anton 1.1 @subsection Bitwise operations
391 :     doc-and
392 :     doc-or
393 :     doc-xor
394 :     doc-invert
395 :     doc-2*
396 :     doc-2/
397 :    
398 : anton 1.4 @node Mixed precision, Double precision, Bitwise operations, Arithmetic
399 : anton 1.1 @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
409 :    
410 : anton 1.4 @node Double precision, Floating Point, Mixed precision, Arithmetic
411 : anton 1.1 @subsection Double precision
412 : anton 1.16
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.
416 :    
417 : anton 1.1 doc-d+
418 :     doc-d-
419 :     doc-dnegate
420 :     doc-dabs
421 :     doc-dmin
422 :     doc-dmax
423 :    
424 : anton 1.4 @node Floating Point, , Double precision, Arithmetic
425 :     @subsection Floating Point
426 : anton 1.16
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).
439 : anton 1.4
440 :     Angles in floating point operations are given in radians (a full circle
441 : anton 1.17 has 2 pi radians). Note, that Gforth has a separate floating point
442 : anton 1.4 stack, but we use the unified notation.
443 :    
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 : anton 1.11 avoid them), you might start with @cite{David Goldberg, What Every
450 : anton 1.6 Computer Scientist Should Know About Floating-Point Arithmetic, ACM
451 :     Computing Surveys 23(1):5@minus{}48, March 1991}.
452 : anton 1.4
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 : anton 1.6 doc-falog
471 : anton 1.4 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
485 :    
486 :     @node Stack Manipulation, Memory access, Arithmetic, Words
487 : anton 1.1 @section Stack Manipulation
488 :    
489 : anton 1.17 Gforth has a data stack (aka parameter stack) for characters, cells,
490 : anton 1.1 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 : anton 1.4 it. Instead, just say that your program has an environmental dependency
500 :     on a separate FP stack.
501 :    
502 :     Also, a Forth system is allowed to keep the local variables on the
503 : anton 1.1 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).
508 :    
509 : anton 1.4 @menu
510 :     * Data stack::
511 :     * Floating point stack::
512 :     * Return stack::
513 :     * Locals stack::
514 :     * Stack pointer manipulation::
515 :     @end menu
516 :    
517 :     @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
518 : anton 1.1 @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
537 :    
538 : anton 1.4 @node Floating point stack, Return stack, Data stack, Stack Manipulation
539 : anton 1.1 @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
547 :    
548 : anton 1.4 @node Return stack, Locals stack, Floating point stack, Stack Manipulation
549 : anton 1.1 @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
558 :    
559 : anton 1.4 @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
560 : anton 1.1 @subsection Locals stack
561 :    
562 : anton 1.4 @node Stack pointer manipulation, , Locals stack, Stack Manipulation
563 : anton 1.1 @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!
572 :    
573 : anton 1.4 @node Memory access, Control Structures, Stack Manipulation, Words
574 : anton 1.1 @section Memory access
575 :    
576 : anton 1.4 @menu
577 :     * Stack-Memory transfers::
578 :     * Address arithmetic::
579 :     * Memory block access::
580 :     @end menu
581 :    
582 :     @node Stack-Memory transfers, Address arithmetic, Memory access, Memory access
583 : anton 1.1 @subsection Stack-Memory transfers
584 :    
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!
598 :    
599 : anton 1.4 @node Address arithmetic, Memory block access, Stack-Memory transfers, Memory access
600 : anton 1.1 @subsection Address arithmetic
601 :    
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).
608 :    
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.
614 :    
615 : anton 1.17 For the performance-conscious: alignment operations are usually only
616 : anton 1.1 necessary during the definition of a data structure, not during the
617 :     (more frequent) accesses to it.
618 :    
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.
623 :    
624 :     The standard guarantees that addresses returned by @code{CREATE}d words
625 : anton 1.17 are cell-aligned; in addition, Gforth guarantees that these addresses
626 : anton 1.1 are aligned for all purposes.
627 :    
628 : anton 1.9 Note that the standard defines a word @code{char}, which has nothing to
629 :     do with address arithmetic.
630 :    
631 : anton 1.1 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 : anton 1.10 doc-maxalign
650 :     doc-maxaligned
651 :     doc-cfalign
652 :     doc-cfaligned
653 : anton 1.1 doc-address-unit-bits
654 :    
655 : anton 1.4 @node Memory block access, , Address arithmetic, Memory access
656 : anton 1.1 @subsection Memory block access
657 :    
658 :     doc-move
659 :     doc-erase
660 :    
661 :     While the previous words work on address units, the rest works on
662 :     characters.
663 :    
664 :     doc-cmove
665 :     doc-cmove>
666 :     doc-fill
667 :     doc-blank
668 :    
669 : anton 1.4 @node Control Structures, Locals, Memory access, Words
670 : anton 1.1 @section Control Structures
671 :    
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.
676 :    
677 : anton 1.4 @menu
678 :     * Selection::
679 :     * Simple Loops::
680 :     * Counted Loops::
681 :     * Arbitrary control structures::
682 :     * Calls and returns::
683 :     * Exception Handling::
684 :     @end menu
685 :    
686 :     @node Selection, Simple Loops, Control Structures, Control Structures
687 : anton 1.1 @subsection Selection
688 :    
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
704 :    
705 : anton 1.4 You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
706 : anton 1.1 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
714 :    
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.]
723 :    
724 :     We also provide the words @code{?dup-if} and @code{?dup-0=-if}, so you
725 :     can avoid using @code{?dup}.
726 :    
727 :     @example
728 :     @var{n}
729 :     CASE
730 :     @var{n1} OF @var{code1} ENDOF
731 :     @var{n2} OF @var{code2} ENDOF
732 : anton 1.4 @dots{}
733 : anton 1.1 ENDCASE
734 :     @end example
735 :    
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.
740 :    
741 : anton 1.4 @node Simple Loops, Counted Loops, Selection, Control Structures
742 : anton 1.1 @subsection Simple Loops
743 :    
744 :     @example
745 :     BEGIN
746 :     @var{code1}
747 :     @var{flag}
748 :     WHILE
749 :     @var{code2}
750 :     REPEAT
751 :     @end example
752 :    
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}.
755 :    
756 :     @example
757 :     BEGIN
758 :     @var{code}
759 :     @var{flag}
760 :     UNTIL
761 :     @end example
762 :    
763 :     @var{code} is executed. The loop is restarted if @code{flag} is false.
764 :    
765 :     @example
766 :     BEGIN
767 :     @var{code}
768 :     AGAIN
769 :     @end example
770 :    
771 :     This is an endless loop.
772 :    
773 : anton 1.4 @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
774 : anton 1.1 @subsection Counted Loops
775 :    
776 :     The basic counted loop is:
777 :     @example
778 :     @var{limit} @var{start}
779 :     ?DO
780 :     @var{body}
781 :     LOOP
782 :     @end example
783 :    
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}.
799 :    
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.
806 :    
807 :     There are several variations on the counted loop:
808 :    
809 :     @code{LEAVE} leaves the innermost counted loop immediately.
810 :    
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.:
814 :    
815 : anton 1.2 @code{4 0 ?DO i . 2 +LOOP} prints @code{0 2}
816 : anton 1.1
817 : anton 1.2 @code{4 1 ?DO i . 2 +LOOP} prints @code{1 3}
818 : anton 1.1
819 :     The behaviour of @code{@var{n} +LOOP} is peculiar when @var{n} is negative:
820 :    
821 : anton 1.2 @code{-1 0 ?DO i . -1 +LOOP} prints @code{0 -1}
822 : anton 1.1
823 : anton 1.2 @code{ 0 0 ?DO i . -1 +LOOP} prints nothing
824 : anton 1.1
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:
828 :    
829 : pazsan 1.7 @code{-2 0 ?DO i . -1 S+LOOP} prints @code{0 -1}
830 : anton 1.1
831 : pazsan 1.7 @code{-1 0 ?DO i . -1 S+LOOP} prints @code{0}
832 : anton 1.1
833 : pazsan 1.7 @code{ 0 0 ?DO i . -1 S+LOOP} prints nothing
834 : anton 1.1
835 : anton 1.2 The loop is terminated when the border between @var{limit@minus{}sgn(n)} and
836 : anton 1.1 @var{limit} is crossed. However, @code{S+LOOP} is not part of the ANS
837 :     Forth standard.
838 :    
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.
842 :    
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.
846 :    
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 : anton 1.17 lazy to optimize @code{?DO} loops properly. In Gforth, this loop
856 : anton 1.1 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.
859 :    
860 : anton 1.4 @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
861 : anton 1.2 @subsection Arbitrary control structures
862 :    
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 : anton 1.17 stack, and this is what we have done in Gforth.
867 : anton 1.2
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).
872 :    
873 : anton 1.3 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
881 : anton 1.2
882 : anton 1.17 On many systems control-flow stack items take one word, in Gforth they
883 : anton 1.2 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.
887 :    
888 :     Some standard control structure words are built from these words:
889 :    
890 : anton 1.3 doc-else
891 :     doc-while
892 :     doc-repeat
893 : anton 1.2
894 :     Counted loop words constitute a separate group of words:
895 :    
896 : anton 1.3 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 : anton 1.10 doc-done
907 : anton 1.2
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 : anton 1.3 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 : pazsan 1.7 resolved (by using one of the loop-ending words or @code{DONE}).
914 : anton 1.2
915 :     Another group of control structure words are
916 :    
917 : anton 1.3 doc-case
918 :     doc-endcase
919 :     doc-of
920 :     doc-endof
921 : anton 1.2
922 :     @i{case-sys} and @i{of-sys} cannot be processed using @code{cs-pick} and
923 :     @code{cs-roll}.
924 :    
925 : anton 1.3 @subsubsection Programming Style
926 :    
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.
931 :    
932 :     E.g., instead of writing
933 :    
934 :     @example
935 :     begin
936 :     ...
937 :     if [ 1 cs-roll ]
938 :     ...
939 :     again then
940 :     @end example
941 :    
942 :     we recommend defining control structure words, e.g.,
943 :    
944 :     @example
945 :     : while ( dest -- orig dest )
946 :     POSTPONE if
947 :     1 cs-roll ; immediate
948 :    
949 :     : repeat ( orig dest -- )
950 :     POSTPONE again
951 :     POSTPONE then ; immediate
952 :     @end example
953 :    
954 :     and then using these to create the control structure:
955 :    
956 :     @example
957 :     begin
958 :     ...
959 :     while
960 :     ...
961 :     repeat
962 :     @end example
963 :    
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.
967 :    
968 : anton 1.4 @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
969 : anton 1.3 @subsection Calls and returns
970 :    
971 :     A definition can be called simply be writing the name of the
972 : anton 1.17 definition. When the end of the definition is reached, it returns. An
973 :     earlier return can be forced using
974 : anton 1.3
975 :     doc-exit
976 :    
977 :     Don't forget to clean up the return stack and @code{UNLOOP} any
978 :     outstanding @code{?DO}...@code{LOOP}s before @code{EXIT}ing. The
979 :     primitive compiled by @code{EXIT} is
980 :    
981 :     doc-;s
982 :    
983 : anton 1.4 @node Exception Handling, , Calls and returns, Control Structures
984 : anton 1.3 @subsection Exception Handling
985 :    
986 :     doc-catch
987 :     doc-throw
988 :    
989 : anton 1.4 @node Locals, Defining Words, Control Structures, Words
990 : anton 1.1 @section Locals
991 :    
992 : anton 1.2 Local variables can make Forth programming more enjoyable and Forth
993 :     programs easier to read. Unfortunately, the locals of ANS Forth are
994 :     laden with restrictions. Therefore, we provide not only the ANS Forth
995 :     locals wordset, but also our own, more powerful locals wordset (we
996 :     implemented the ANS Forth locals wordset through our locals wordset).
997 :    
998 :     @menu
999 : anton 1.17 * Gforth locals::
1000 : anton 1.4 * ANS Forth locals::
1001 : anton 1.2 @end menu
1002 :    
1003 : anton 1.17 @node Gforth locals, ANS Forth locals, Locals, Locals
1004 :     @subsection Gforth locals
1005 : anton 1.2
1006 :     Locals can be defined with
1007 :    
1008 :     @example
1009 :     @{ local1 local2 ... -- comment @}
1010 :     @end example
1011 :     or
1012 :     @example
1013 :     @{ local1 local2 ... @}
1014 :     @end example
1015 :    
1016 :     E.g.,
1017 :     @example
1018 :     : max @{ n1 n2 -- n3 @}
1019 :     n1 n2 > if
1020 :     n1
1021 :     else
1022 :     n2
1023 :     endif ;
1024 :     @end example
1025 :    
1026 :     The similarity of locals definitions with stack comments is intended. A
1027 :     locals definition often replaces the stack comment of a word. The order
1028 :     of the locals corresponds to the order in a stack comment and everything
1029 :     after the @code{--} is really a comment.
1030 :    
1031 :     This similarity has one disadvantage: It is too easy to confuse locals
1032 :     declarations with stack comments, causing bugs and making them hard to
1033 :     find. However, this problem can be avoided by appropriate coding
1034 :     conventions: Do not use both notations in the same program. If you do,
1035 :     they should be distinguished using additional means, e.g. by position.
1036 :    
1037 :     The name of the local may be preceded by a type specifier, e.g.,
1038 :     @code{F:} for a floating point value:
1039 :    
1040 :     @example
1041 :     : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
1042 :     \ complex multiplication
1043 :     Ar Br f* Ai Bi f* f-
1044 :     Ar Bi f* Ai Br f* f+ ;
1045 :     @end example
1046 :    
1047 : anton 1.17 Gforth currently supports cells (@code{W:}, @code{W^}), doubles
1048 : anton 1.2 (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
1049 :     (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
1050 :     with @code{W:}, @code{D:} etc.) produces its value and can be changed
1051 :     with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
1052 :     produces its address (which becomes invalid when the variable's scope is
1053 :     left). E.g., the standard word @code{emit} can be defined in therms of
1054 :     @code{type} like this:
1055 :    
1056 :     @example
1057 :     : emit @{ C^ char* -- @}
1058 :     char* 1 type ;
1059 :     @end example
1060 :    
1061 :     A local without type specifier is a @code{W:} local. Both flavours of
1062 :     locals are initialized with values from the data or FP stack.
1063 :    
1064 :     Currently there is no way to define locals with user-defined data
1065 :     structures, but we are working on it.
1066 :    
1067 : anton 1.17 Gforth allows defining locals everywhere in a colon definition. This
1068 : pazsan 1.7 poses the following questions:
1069 : anton 1.2
1070 : anton 1.4 @menu
1071 :     * Where are locals visible by name?::
1072 : anton 1.14 * How long do locals live?::
1073 : anton 1.4 * Programming Style::
1074 :     * Implementation::
1075 :     @end menu
1076 :    
1077 : anton 1.17 @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
1078 : anton 1.2 @subsubsection Where are locals visible by name?
1079 :    
1080 :     Basically, the answer is that locals are visible where you would expect
1081 :     it in block-structured languages, and sometimes a little longer. If you
1082 :     want to restrict the scope of a local, enclose its definition in
1083 :     @code{SCOPE}...@code{ENDSCOPE}.
1084 :    
1085 :     doc-scope
1086 :     doc-endscope
1087 :    
1088 :     These words behave like control structure words, so you can use them
1089 :     with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
1090 :     arbitrary ways.
1091 :    
1092 :     If you want a more exact answer to the visibility question, here's the
1093 :     basic principle: A local is visible in all places that can only be
1094 :     reached through the definition of the local@footnote{In compiler
1095 :     construction terminology, all places dominated by the definition of the
1096 :     local.}. In other words, it is not visible in places that can be reached
1097 :     without going through the definition of the local. E.g., locals defined
1098 :     in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
1099 :     defined in @code{BEGIN}...@code{UNTIL} are visible after the
1100 :     @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1101 :    
1102 :     The reasoning behind this solution is: We want to have the locals
1103 :     visible as long as it is meaningful. The user can always make the
1104 :     visibility shorter by using explicit scoping. In a place that can
1105 :     only be reached through the definition of a local, the meaning of a
1106 :     local name is clear. In other places it is not: How is the local
1107 :     initialized at the control flow path that does not contain the
1108 :     definition? Which local is meant, if the same name is defined twice in
1109 :     two independent control flow paths?
1110 :    
1111 :     This should be enough detail for nearly all users, so you can skip the
1112 :     rest of this section. If you relly must know all the gory details and
1113 :     options, read on.
1114 :    
1115 :     In order to implement this rule, the compiler has to know which places
1116 :     are unreachable. It knows this automatically after @code{AHEAD},
1117 :     @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
1118 :     most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
1119 :     compiler that the control flow never reaches that place. If
1120 :     @code{UNREACHABLE} is not used where it could, the only consequence is
1121 :     that the visibility of some locals is more limited than the rule above
1122 :     says. If @code{UNREACHABLE} is used where it should not (i.e., if you
1123 :     lie to the compiler), buggy code will be produced.
1124 :    
1125 :     Another problem with this rule is that at @code{BEGIN}, the compiler
1126 : anton 1.3 does not know which locals will be visible on the incoming
1127 :     back-edge. All problems discussed in the following are due to this
1128 :     ignorance of the compiler (we discuss the problems using @code{BEGIN}
1129 :     loops as examples; the discussion also applies to @code{?DO} and other
1130 : anton 1.2 loops). Perhaps the most insidious example is:
1131 :     @example
1132 :     AHEAD
1133 :     BEGIN
1134 :     x
1135 :     [ 1 CS-ROLL ] THEN
1136 : anton 1.4 @{ x @}
1137 : anton 1.2 ...
1138 :     UNTIL
1139 :     @end example
1140 :    
1141 :     This should be legal according to the visibility rule. The use of
1142 :     @code{x} can only be reached through the definition; but that appears
1143 :     textually below the use.
1144 :    
1145 :     From this example it is clear that the visibility rules cannot be fully
1146 :     implemented without major headaches. Our implementation treats common
1147 :     cases as advertised and the exceptions are treated in a safe way: The
1148 :     compiler makes a reasonable guess about the locals visible after a
1149 :     @code{BEGIN}; if it is too pessimistic, the
1150 :     user will get a spurious error about the local not being defined; if the
1151 :     compiler is too optimistic, it will notice this later and issue a
1152 :     warning. In the case above the compiler would complain about @code{x}
1153 :     being undefined at its use. You can see from the obscure examples in
1154 :     this section that it takes quite unusual control structures to get the
1155 :     compiler into trouble, and even then it will often do fine.
1156 :    
1157 :     If the @code{BEGIN} is reachable from above, the most optimistic guess
1158 :     is that all locals visible before the @code{BEGIN} will also be
1159 :     visible after the @code{BEGIN}. This guess is valid for all loops that
1160 :     are entered only through the @code{BEGIN}, in particular, for normal
1161 :     @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
1162 :     @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
1163 :     compiler. When the branch to the @code{BEGIN} is finally generated by
1164 :     @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
1165 :     warns the user if it was too optimisitic:
1166 :     @example
1167 :     IF
1168 : anton 1.4 @{ x @}
1169 : anton 1.2 BEGIN
1170 :     \ x ?
1171 :     [ 1 cs-roll ] THEN
1172 :     ...
1173 :     UNTIL
1174 :     @end example
1175 :    
1176 :     Here, @code{x} lives only until the @code{BEGIN}, but the compiler
1177 :     optimistically assumes that it lives until the @code{THEN}. It notices
1178 :     this difference when it compiles the @code{UNTIL} and issues a
1179 :     warning. The user can avoid the warning, and make sure that @code{x}
1180 :     is not used in the wrong area by using explicit scoping:
1181 :     @example
1182 :     IF
1183 :     SCOPE
1184 : anton 1.4 @{ x @}
1185 : anton 1.2 ENDSCOPE
1186 :     BEGIN
1187 :     [ 1 cs-roll ] THEN
1188 :     ...
1189 :     UNTIL
1190 :     @end example
1191 :    
1192 :     Since the guess is optimistic, there will be no spurious error messages
1193 :     about undefined locals.
1194 :    
1195 :     If the @code{BEGIN} is not reachable from above (e.g., after
1196 :     @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
1197 :     optimistic guess, as the locals visible after the @code{BEGIN} may be
1198 :     defined later. Therefore, the compiler assumes that no locals are
1199 : anton 1.17 visible after the @code{BEGIN}. However, the user can use
1200 : anton 1.2 @code{ASSUME-LIVE} to make the compiler assume that the same locals are
1201 : anton 1.17 visible at the BEGIN as at the point where the top control-flow stack
1202 :     item was created.
1203 : anton 1.2
1204 :     doc-assume-live
1205 :    
1206 :     E.g.,
1207 :     @example
1208 : anton 1.4 @{ x @}
1209 : anton 1.2 AHEAD
1210 :     ASSUME-LIVE
1211 :     BEGIN
1212 :     x
1213 :     [ 1 CS-ROLL ] THEN
1214 :     ...
1215 :     UNTIL
1216 :     @end example
1217 :    
1218 :     Other cases where the locals are defined before the @code{BEGIN} can be
1219 :     handled by inserting an appropriate @code{CS-ROLL} before the
1220 :     @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
1221 :     behind the @code{ASSUME-LIVE}).
1222 :    
1223 :     Cases where locals are defined after the @code{BEGIN} (but should be
1224 :     visible immediately after the @code{BEGIN}) can only be handled by
1225 :     rearranging the loop. E.g., the ``most insidious'' example above can be
1226 :     arranged into:
1227 :     @example
1228 :     BEGIN
1229 : anton 1.4 @{ x @}
1230 : anton 1.2 ... 0=
1231 :     WHILE
1232 :     x
1233 :     REPEAT
1234 :     @end example
1235 :    
1236 : anton 1.17 @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
1237 : anton 1.2 @subsubsection How long do locals live?
1238 :    
1239 :     The right answer for the lifetime question would be: A local lives at
1240 :     least as long as it can be accessed. For a value-flavoured local this
1241 :     means: until the end of its visibility. However, a variable-flavoured
1242 :     local could be accessed through its address far beyond its visibility
1243 :     scope. Ultimately, this would mean that such locals would have to be
1244 :     garbage collected. Since this entails un-Forth-like implementation
1245 :     complexities, I adopted the same cowardly solution as some other
1246 :     languages (e.g., C): The local lives only as long as it is visible;
1247 :     afterwards its address is invalid (and programs that access it
1248 :     afterwards are erroneous).
1249 :    
1250 : anton 1.17 @node Programming Style, Implementation, How long do locals live?, Gforth locals
1251 : anton 1.2 @subsubsection Programming Style
1252 :    
1253 :     The freedom to define locals anywhere has the potential to change
1254 :     programming styles dramatically. In particular, the need to use the
1255 :     return stack for intermediate storage vanishes. Moreover, all stack
1256 :     manipulations (except @code{PICK}s and @code{ROLL}s with run-time
1257 :     determined arguments) can be eliminated: If the stack items are in the
1258 :     wrong order, just write a locals definition for all of them; then
1259 :     write the items in the order you want.
1260 :    
1261 :     This seems a little far-fetched and eliminating stack manipulations is
1262 : anton 1.4 unlikely to become a conscious programming objective. Still, the number
1263 :     of stack manipulations will be reduced dramatically if local variables
1264 : anton 1.17 are used liberally (e.g., compare @code{max} in @ref{Gforth locals} with
1265 : anton 1.4 a traditional implementation of @code{max}).
1266 : anton 1.2
1267 :     This shows one potential benefit of locals: making Forth programs more
1268 :     readable. Of course, this benefit will only be realized if the
1269 :     programmers continue to honour the principle of factoring instead of
1270 :     using the added latitude to make the words longer.
1271 :    
1272 :     Using @code{TO} can and should be avoided. Without @code{TO},
1273 :     every value-flavoured local has only a single assignment and many
1274 :     advantages of functional languages apply to Forth. I.e., programs are
1275 :     easier to analyse, to optimize and to read: It is clear from the
1276 :     definition what the local stands for, it does not turn into something
1277 :     different later.
1278 :    
1279 :     E.g., a definition using @code{TO} might look like this:
1280 :     @example
1281 :     : strcmp @{ addr1 u1 addr2 u2 -- n @}
1282 :     u1 u2 min 0
1283 :     ?do
1284 :     addr1 c@ addr2 c@ - ?dup
1285 :     if
1286 :     unloop exit
1287 :     then
1288 :     addr1 char+ TO addr1
1289 :     addr2 char+ TO addr2
1290 :     loop
1291 :     u1 u2 - ;
1292 :     @end example
1293 :     Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
1294 :     every loop iteration. @code{strcmp} is a typical example of the
1295 :     readability problems of using @code{TO}. When you start reading
1296 :     @code{strcmp}, you think that @code{addr1} refers to the start of the
1297 :     string. Only near the end of the loop you realize that it is something
1298 :     else.
1299 :    
1300 :     This can be avoided by defining two locals at the start of the loop that
1301 :     are initialized with the right value for the current iteration.
1302 :     @example
1303 :     : strcmp @{ addr1 u1 addr2 u2 -- n @}
1304 :     addr1 addr2
1305 :     u1 u2 min 0
1306 :     ?do @{ s1 s2 @}
1307 :     s1 c@ s2 c@ - ?dup
1308 :     if
1309 :     unloop exit
1310 :     then
1311 :     s1 char+ s2 char+
1312 :     loop
1313 :     2drop
1314 :     u1 u2 - ;
1315 :     @end example
1316 :     Here it is clear from the start that @code{s1} has a different value
1317 :     in every loop iteration.
1318 :    
1319 : anton 1.17 @node Implementation, , Programming Style, Gforth locals
1320 : anton 1.2 @subsubsection Implementation
1321 :    
1322 : anton 1.17 Gforth uses an extra locals stack. The most compelling reason for
1323 : anton 1.2 this is that the return stack is not float-aligned; using an extra stack
1324 :     also eliminates the problems and restrictions of using the return stack
1325 :     as locals stack. Like the other stacks, the locals stack grows toward
1326 :     lower addresses. A few primitives allow an efficient implementation:
1327 :    
1328 :     doc-@local#
1329 :     doc-f@local#
1330 :     doc-laddr#
1331 :     doc-lp+!#
1332 :     doc-lp!
1333 :     doc->l
1334 :     doc-f>l
1335 :    
1336 :     In addition to these primitives, some specializations of these
1337 :     primitives for commonly occurring inline arguments are provided for
1338 :     efficiency reasons, e.g., @code{@@local0} as specialization of
1339 :     @code{@@local#} for the inline argument 0. The following compiling words
1340 :     compile the right specialized version, or the general version, as
1341 :     appropriate:
1342 :    
1343 : anton 1.12 doc-compile-@local
1344 :     doc-compile-f@local
1345 : anton 1.2 doc-compile-lp+!
1346 :    
1347 :     Combinations of conditional branches and @code{lp+!#} like
1348 :     @code{?branch-lp+!#} (the locals pointer is only changed if the branch
1349 :     is taken) are provided for efficiency and correctness in loops.
1350 :    
1351 :     A special area in the dictionary space is reserved for keeping the
1352 :     local variable names. @code{@{} switches the dictionary pointer to this
1353 :     area and @code{@}} switches it back and generates the locals
1354 :     initializing code. @code{W:} etc.@ are normal defining words. This
1355 :     special area is cleared at the start of every colon definition.
1356 :    
1357 : anton 1.17 A special feature of Gforth's dictionary is used to implement the
1358 : anton 1.2 definition of locals without type specifiers: every wordlist (aka
1359 :     vocabulary) has its own methods for searching
1360 : anton 1.4 etc. (@pxref{Wordlists}). For the present purpose we defined a wordlist
1361 : anton 1.2 with a special search method: When it is searched for a word, it
1362 :     actually creates that word using @code{W:}. @code{@{} changes the search
1363 :     order to first search the wordlist containing @code{@}}, @code{W:} etc.,
1364 :     and then the wordlist for defining locals without type specifiers.
1365 :    
1366 :     The lifetime rules support a stack discipline within a colon
1367 :     definition: The lifetime of a local is either nested with other locals
1368 :     lifetimes or it does not overlap them.
1369 :    
1370 :     At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
1371 :     pointer manipulation is generated. Between control structure words
1372 :     locals definitions can push locals onto the locals stack. @code{AGAIN}
1373 :     is the simplest of the other three control flow words. It has to
1374 :     restore the locals stack depth of the corresponding @code{BEGIN}
1375 :     before branching. The code looks like this:
1376 :     @format
1377 :     @code{lp+!#} current-locals-size @minus{} dest-locals-size
1378 :     @code{branch} <begin>
1379 :     @end format
1380 :    
1381 :     @code{UNTIL} is a little more complicated: If it branches back, it
1382 :     must adjust the stack just like @code{AGAIN}. But if it falls through,
1383 :     the locals stack must not be changed. The compiler generates the
1384 :     following code:
1385 :     @format
1386 :     @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
1387 :     @end format
1388 :     The locals stack pointer is only adjusted if the branch is taken.
1389 :    
1390 :     @code{THEN} can produce somewhat inefficient code:
1391 :     @format
1392 :     @code{lp+!#} current-locals-size @minus{} orig-locals-size
1393 :     <orig target>:
1394 :     @code{lp+!#} orig-locals-size @minus{} new-locals-size
1395 :     @end format
1396 :     The second @code{lp+!#} adjusts the locals stack pointer from the
1397 : anton 1.4 level at the @var{orig} point to the level after the @code{THEN}. The
1398 : anton 1.2 first @code{lp+!#} adjusts the locals stack pointer from the current
1399 :     level to the level at the orig point, so the complete effect is an
1400 :     adjustment from the current level to the right level after the
1401 :     @code{THEN}.
1402 :    
1403 :     In a conventional Forth implementation a dest control-flow stack entry
1404 :     is just the target address and an orig entry is just the address to be
1405 :     patched. Our locals implementation adds a wordlist to every orig or dest
1406 :     item. It is the list of locals visible (or assumed visible) at the point
1407 :     described by the entry. Our implementation also adds a tag to identify
1408 :     the kind of entry, in particular to differentiate between live and dead
1409 :     (reachable and unreachable) orig entries.
1410 :    
1411 :     A few unusual operations have to be performed on locals wordlists:
1412 :    
1413 :     doc-common-list
1414 :     doc-sub-list?
1415 :     doc-list-size
1416 :    
1417 :     Several features of our locals wordlist implementation make these
1418 :     operations easy to implement: The locals wordlists are organised as
1419 :     linked lists; the tails of these lists are shared, if the lists
1420 :     contain some of the same locals; and the address of a name is greater
1421 :     than the address of the names behind it in the list.
1422 :    
1423 :     Another important implementation detail is the variable
1424 :     @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
1425 :     determine if they can be reached directly or only through the branch
1426 :     that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
1427 :     @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
1428 :     definition, by @code{BEGIN} and usually by @code{THEN}.
1429 :    
1430 :     Counted loops are similar to other loops in most respects, but
1431 :     @code{LEAVE} requires special attention: It performs basically the same
1432 :     service as @code{AHEAD}, but it does not create a control-flow stack
1433 :     entry. Therefore the information has to be stored elsewhere;
1434 :     traditionally, the information was stored in the target fields of the
1435 :     branches created by the @code{LEAVE}s, by organizing these fields into a
1436 :     linked list. Unfortunately, this clever trick does not provide enough
1437 :     space for storing our extended control flow information. Therefore, we
1438 :     introduce another stack, the leave stack. It contains the control-flow
1439 :     stack entries for all unresolved @code{LEAVE}s.
1440 :    
1441 :     Local names are kept until the end of the colon definition, even if
1442 :     they are no longer visible in any control-flow path. In a few cases
1443 :     this may lead to increased space needs for the locals name area, but
1444 :     usually less than reclaiming this space would cost in code size.
1445 :    
1446 :    
1447 : anton 1.17 @node ANS Forth locals, , Gforth locals, Locals
1448 : anton 1.2 @subsection ANS Forth locals
1449 :    
1450 :     The ANS Forth locals wordset does not define a syntax for locals, but
1451 :     words that make it possible to define various syntaxes. One of the
1452 : anton 1.17 possible syntaxes is a subset of the syntax we used in the Gforth locals
1453 : anton 1.2 wordset, i.e.:
1454 :    
1455 :     @example
1456 :     @{ local1 local2 ... -- comment @}
1457 :     @end example
1458 :     or
1459 :     @example
1460 :     @{ local1 local2 ... @}
1461 :     @end example
1462 :    
1463 :     The order of the locals corresponds to the order in a stack comment. The
1464 :     restrictions are:
1465 : anton 1.1
1466 : anton 1.2 @itemize @bullet
1467 :     @item
1468 : anton 1.17 Locals can only be cell-sized values (no type specifiers are allowed).
1469 : anton 1.2 @item
1470 :     Locals can be defined only outside control structures.
1471 :     @item
1472 :     Locals can interfere with explicit usage of the return stack. For the
1473 :     exact (and long) rules, see the standard. If you don't use return stack
1474 : anton 1.17 accessing words in a definition using locals, you will be all right. The
1475 : anton 1.2 purpose of this rule is to make locals implementation on the return
1476 :     stack easier.
1477 :     @item
1478 :     The whole definition must be in one line.
1479 :     @end itemize
1480 :    
1481 :     Locals defined in this way behave like @code{VALUE}s
1482 : anton 1.4 (@xref{Values}). I.e., they are initialized from the stack. Using their
1483 : anton 1.2 name produces their value. Their value can be changed using @code{TO}.
1484 :    
1485 : anton 1.17 Since this syntax is supported by Gforth directly, you need not do
1486 : anton 1.2 anything to use it. If you want to port a program using this syntax to
1487 :     another ANS Forth system, use @file{anslocal.fs} to implement the syntax
1488 :     on the other system.
1489 :    
1490 :     Note that a syntax shown in the standard, section A.13 looks
1491 :     similar, but is quite different in having the order of locals
1492 :     reversed. Beware!
1493 :    
1494 :     The ANS Forth locals wordset itself consists of the following word
1495 :    
1496 :     doc-(local)
1497 :    
1498 :     The ANS Forth locals extension wordset defines a syntax, but it is so
1499 :     awful that we strongly recommend not to use it. We have implemented this
1500 : anton 1.17 syntax to make porting to Gforth easy, but do not document it here. The
1501 : anton 1.2 problem with this syntax is that the locals are defined in an order
1502 :     reversed with respect to the standard stack comment notation, making
1503 :     programs harder to read, and easier to misread and miswrite. The only
1504 :     merit of this syntax is that it is easy to implement using the ANS Forth
1505 :     locals wordset.
1506 : anton 1.3
1507 : anton 1.4 @node Defining Words, Wordlists, Locals, Words
1508 :     @section Defining Words
1509 :    
1510 : anton 1.14 @menu
1511 :     * Values::
1512 :     @end menu
1513 :    
1514 : anton 1.4 @node Values, , Defining Words, Defining Words
1515 :     @subsection Values
1516 :    
1517 :     @node Wordlists, Files, Defining Words, Words
1518 :     @section Wordlists
1519 :    
1520 :     @node Files, Blocks, Wordlists, Words
1521 :     @section Files
1522 :    
1523 :     @node Blocks, Other I/O, Files, Words
1524 :     @section Blocks
1525 :    
1526 :     @node Other I/O, Programming Tools, Blocks, Words
1527 :     @section Other I/O
1528 :    
1529 :     @node Programming Tools, Threading Words, Other I/O, Words
1530 :     @section Programming Tools
1531 :    
1532 : anton 1.5 @menu
1533 :     * Debugging:: Simple and quick.
1534 :     * Assertions:: Making your programs self-checking.
1535 :     @end menu
1536 :    
1537 :     @node Debugging, Assertions, Programming Tools, Programming Tools
1538 : anton 1.4 @subsection Debugging
1539 :    
1540 :     The simple debugging aids provided in @file{debugging.fs}
1541 :     are meant to support a different style of debugging than the
1542 :     tracing/stepping debuggers used in languages with long turn-around
1543 :     times.
1544 :    
1545 :     A much better (faster) way in fast-compilig languages is to add
1546 :     printing code at well-selected places, let the program run, look at
1547 :     the output, see where things went wrong, add more printing code, etc.,
1548 :     until the bug is found.
1549 :    
1550 :     The word @code{~~} is easy to insert. It just prints debugging
1551 :     information (by default the source location and the stack contents). It
1552 :     is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
1553 :     query-replace them with nothing). The deferred words
1554 :     @code{printdebugdata} and @code{printdebugline} control the output of
1555 :     @code{~~}. The default source location output format works well with
1556 :     Emacs' compilation mode, so you can step through the program at the
1557 : anton 1.5 source level using @kbd{C-x `} (the advantage over a stepping debugger
1558 :     is that you can step in any direction and you know where the crash has
1559 :     happened or where the strange data has occurred).
1560 : anton 1.4
1561 :     Note that the default actions clobber the contents of the pictured
1562 :     numeric output string, so you should not use @code{~~}, e.g., between
1563 :     @code{<#} and @code{#>}.
1564 :    
1565 :     doc-~~
1566 :     doc-printdebugdata
1567 :     doc-printdebugline
1568 :    
1569 : anton 1.5 @node Assertions, , Debugging, Programming Tools
1570 : anton 1.4 @subsection Assertions
1571 :    
1572 : anton 1.5 It is a good idea to make your programs self-checking, in particular, if
1573 :     you use an assumption (e.g., that a certain field of a data structure is
1574 : anton 1.17 never zero) that may become wrong during maintenance. Gforth supports
1575 : anton 1.5 assertions for this purpose. They are used like this:
1576 :    
1577 :     @example
1578 :     assert( @var{flag} )
1579 :     @end example
1580 :    
1581 :     The code between @code{assert(} and @code{)} should compute a flag, that
1582 :     should be true if everything is alright and false otherwise. It should
1583 :     not change anything else on the stack. The overall stack effect of the
1584 :     assertion is @code{( -- )}. E.g.
1585 :    
1586 :     @example
1587 :     assert( 1 1 + 2 = ) \ what we learn in school
1588 :     assert( dup 0<> ) \ assert that the top of stack is not zero
1589 :     assert( false ) \ this code should not be reached
1590 :     @end example
1591 :    
1592 :     The need for assertions is different at different times. During
1593 :     debugging, we want more checking, in production we sometimes care more
1594 :     for speed. Therefore, assertions can be turned off, i.e., the assertion
1595 :     becomes a comment. Depending on the importance of an assertion and the
1596 :     time it takes to check it, you may want to turn off some assertions and
1597 : anton 1.17 keep others turned on. Gforth provides several levels of assertions for
1598 : anton 1.5 this purpose:
1599 :    
1600 :     doc-assert0(
1601 :     doc-assert1(
1602 :     doc-assert2(
1603 :     doc-assert3(
1604 :     doc-assert(
1605 :     doc-)
1606 :    
1607 :     @code{Assert(} is the same as @code{assert1(}. The variable
1608 :     @code{assert-level} specifies the highest assertions that are turned
1609 :     on. I.e., at the default @code{assert-level} of one, @code{assert0(} and
1610 :     @code{assert1(} assertions perform checking, while @code{assert2(} and
1611 :     @code{assert3(} assertions are treated as comments.
1612 :    
1613 :     Note that the @code{assert-level} is evaluated at compile-time, not at
1614 :     run-time. I.e., you cannot turn assertions on or off at run-time, you
1615 :     have to set the @code{assert-level} appropriately before compiling a
1616 :     piece of code. You can compile several pieces of code at several
1617 :     @code{assert-level}s (e.g., a trusted library at level 1 and newly
1618 :     written code at level 3).
1619 :    
1620 :     doc-assert-level
1621 :    
1622 :     If an assertion fails, a message compatible with Emacs' compilation mode
1623 :     is produced and the execution is aborted (currently with @code{ABORT"}.
1624 :     If there is interest, we will introduce a special throw code. But if you
1625 :     intend to @code{catch} a specific condition, using @code{throw} is
1626 :     probably more appropriate than an assertion).
1627 :    
1628 : anton 1.4 @node Threading Words, , Programming Tools, Words
1629 :     @section Threading Words
1630 :    
1631 :     These words provide access to code addresses and other threading stuff
1632 : anton 1.17 in Gforth (and, possibly, other interpretive Forths). It more or less
1633 : anton 1.4 abstracts away the differences between direct and indirect threading
1634 :     (and, for direct threading, the machine dependences). However, at
1635 :     present this wordset is still inclomplete. It is also pretty low-level;
1636 :     some day it will hopefully be made unnecessary by an internals words set
1637 :     that abstracts implementation details away completely.
1638 :    
1639 :     doc->code-address
1640 :     doc->does-code
1641 :     doc-code-address!
1642 :     doc-does-code!
1643 :     doc-does-handler!
1644 :     doc-/does-handler
1645 :    
1646 : anton 1.14
1647 :    
1648 : anton 1.4 @node ANS conformance, Model, Words, Top
1649 :     @chapter ANS conformance
1650 :    
1651 : anton 1.17 To the best of our knowledge, Gforth is an
1652 : anton 1.14
1653 : anton 1.15 ANS Forth System
1654 :     @itemize
1655 :     @item providing the Core Extensions word set
1656 :     @item providing the Block word set
1657 :     @item providing the Block Extensions word set
1658 :     @item providing the Double-Number word set
1659 :     @item providing the Double-Number Extensions word set
1660 :     @item providing the Exception word set
1661 :     @item providing the Exception Extensions word set
1662 :     @item providing the Facility word set
1663 :     @item providing @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1664 :     @item providing the File Access word set
1665 :     @item providing the File Access Extensions word set
1666 :     @item providing the Floating-Point word set
1667 :     @item providing the Floating-Point Extensions word set
1668 :     @item providing the Locals word set
1669 :     @item providing the Locals Extensions word set
1670 :     @item providing the Memory-Allocation word set
1671 :     @item providing the Memory-Allocation Extensions word set (that one's easy)
1672 :     @item providing the Programming-Tools word set
1673 :     @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
1674 :     @item providing the Search-Order word set
1675 :     @item providing the Search-Order Extensions word set
1676 :     @item providing the String word set
1677 :     @item providing the String Extensions word set (another easy one)
1678 :     @end itemize
1679 :    
1680 :     In addition, ANS Forth systems are required to document certain
1681 :     implementation choices. This chapter tries to meet these
1682 :     requirements. In many cases it gives a way to ask the system for the
1683 :     information instead of providing the information directly, in
1684 :     particular, if the information depends on the processor, the operating
1685 :     system or the installation options chosen, or if they are likely to
1686 : anton 1.17 change during the maintenance of Gforth.
1687 : anton 1.15
1688 : anton 1.14 @comment The framework for the rest has been taken from pfe.
1689 :    
1690 :     @menu
1691 :     * The Core Words::
1692 :     * The optional Block word set::
1693 :     * The optional Double Number word set::
1694 :     * The optional Exception word set::
1695 :     * The optional Facility word set::
1696 :     * The optional File-Access word set::
1697 :     * The optional Floating-Point word set::
1698 :     * The optional Locals word set::
1699 :     * The optional Memory-Allocation word set::
1700 :     * The optional Programming-Tools word set::
1701 :     * The optional Search-Order word set::
1702 :     @end menu
1703 :    
1704 :    
1705 :     @c =====================================================================
1706 :     @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
1707 :     @comment node-name, next, previous, up
1708 :     @section The Core Words
1709 :     @c =====================================================================
1710 :    
1711 :     @menu
1712 : anton 1.15 * core-idef:: Implementation Defined Options
1713 :     * core-ambcond:: Ambiguous Conditions
1714 :     * core-other:: Other System Documentation
1715 : anton 1.14 @end menu
1716 :    
1717 :     @c ---------------------------------------------------------------------
1718 :     @node core-idef, core-ambcond, The Core Words, The Core Words
1719 :     @subsection Implementation Defined Options
1720 :     @c ---------------------------------------------------------------------
1721 :    
1722 :     @table @i
1723 :    
1724 :     @item (Cell) aligned addresses:
1725 : anton 1.17 processor-dependent. Gforth's alignment words perform natural alignment
1726 : anton 1.14 (e.g., an address aligned for a datum of size 8 is divisible by
1727 :     8). Unaligned accesses usually result in a @code{-23 THROW}.
1728 :    
1729 :     @item @code{EMIT} and non-graphic characters:
1730 :     The character is output using the C library function (actually, macro)
1731 :     @code{putchar}.
1732 :    
1733 :     @item character editing of @code{ACCEPT} and @code{EXPECT}:
1734 :     This is modeled on the GNU readline library (@pxref{Readline
1735 :     Interaction, , Command Line Editing, readline, The GNU Readline
1736 :     Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
1737 :     producing a full word completion every time you type it (instead of
1738 :     producing the common prefix of all completions).
1739 :    
1740 :     @item character set:
1741 :     The character set of your computer and display device. Gforth is
1742 :     8-bit-clean (but some other component in your system may make trouble).
1743 :    
1744 :     @item Character-aligned address requirements:
1745 :     installation-dependent. Currently a character is represented by a C
1746 :     @code{unsigned char}; in the future we might switch to @code{wchar_t}
1747 :     (Comments on that requested).
1748 :    
1749 :     @item character-set extensions and matching of names:
1750 : anton 1.17 Any character except the ASCII NUL charcter can be used in a
1751 :     name. Matching is case-insensitive. The matching is performed using the
1752 :     C function @code{strncasecmp}, whose function is probably influenced by
1753 :     the locale. E.g., the @code{C} locale does not know about accents and
1754 : anton 1.14 umlauts, so they are matched case-sensitively in that locale. For
1755 :     portability reasons it is best to write programs such that they work in
1756 :     the @code{C} locale. Then one can use libraries written by a Polish
1757 :     programmer (who might use words containing ISO Latin-2 encoded
1758 :     characters) and by a French programmer (ISO Latin-1) in the same program
1759 :     (of course, @code{WORDS} will produce funny results for some of the
1760 :     words (which ones, depends on the font you are using)). Also, the locale
1761 :     you prefer may not be available in other operating systems. Hopefully,
1762 :     Unicode will solve these problems one day.
1763 :    
1764 :     @item conditions under which control characters match a space delimiter:
1765 :     If @code{WORD} is called with the space character as a delimiter, all
1766 :     white-space characters (as identified by the C macro @code{isspace()})
1767 :     are delimiters. @code{PARSE}, on the other hand, treats space like other
1768 :     delimiters. @code{PARSE-WORD} treats space like @code{WORD}, but behaves
1769 :     like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
1770 :     interpreter (aka text interpreter) by default, treats all white-space
1771 :     characters as delimiters.
1772 :    
1773 :     @item format of the control flow stack:
1774 :     The data stack is used as control flow stack. The size of a control flow
1775 :     stack item in cells is given by the constant @code{cs-item-size}. At the
1776 :     time of this writing, an item consists of a (pointer to a) locals list
1777 :     (third), an address in the code (second), and a tag for identifying the
1778 :     item (TOS). The following tags are used: @code{defstart},
1779 :     @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
1780 :     @code{scopestart}.
1781 :    
1782 :     @item conversion of digits > 35
1783 :     The characters @code{[\]^_'} are the digits with the decimal value
1784 :     36@minus{}41. There is no way to input many of the larger digits.
1785 :    
1786 :     @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
1787 :     The cursor is moved to the end of the entered string. If the input is
1788 :     terminated using the @kbd{Return} key, a space is typed.
1789 :    
1790 :     @item exception abort sequence of @code{ABORT"}:
1791 :     The error string is stored into the variable @code{"error} and a
1792 :     @code{-2 throw} is performed.
1793 :    
1794 :     @item input line terminator:
1795 :     For interactive input, @kbd{C-m} and @kbd{C-j} terminate lines. One of
1796 :     these characters is typically produced when you type the @kbd{Enter} or
1797 :     @kbd{Return} key.
1798 :    
1799 :     @item maximum size of a counted string:
1800 :     @code{s" /counted-string" environment? drop .}. Currently 255 characters
1801 :     on all ports, but this may change.
1802 :    
1803 :     @item maximum size of a parsed string:
1804 :     Given by the constant @code{/line}. Currently 255 characters.
1805 :    
1806 :     @item maximum size of a definition name, in characters:
1807 :     31
1808 :    
1809 :     @item maximum string length for @code{ENVIRONMENT?}, in characters:
1810 :     31
1811 :    
1812 :     @item method of selecting the user input device:
1813 : anton 1.17 The user input device is the standard input. There is currently no way to
1814 :     change it from within Gforth. However, the input can typically be
1815 :     redirected in the command line that starts Gforth.
1816 : anton 1.14
1817 :     @item method of selecting the user output device:
1818 :     The user output device is the standard output. It cannot be redirected
1819 : anton 1.17 from within Gforth, but typically from the command line that starts
1820 :     Gforth. Gforth uses buffered output, so output on a terminal does not
1821 : anton 1.14 become visible before the next newline or buffer overflow. Output on
1822 :     non-terminals is invisible until the buffer overflows.
1823 :    
1824 :     @item methods of dictionary compilation:
1825 : anton 1.17 What are we expected to document here?
1826 : anton 1.14
1827 :     @item number of bits in one address unit:
1828 :     @code{s" address-units-bits" environment? drop .}. 8 in all current
1829 :     ports.
1830 :    
1831 :     @item number representation and arithmetic:
1832 :     Processor-dependent. Binary two's complement on all current ports.
1833 :    
1834 :     @item ranges for integer types:
1835 :     Installation-dependent. Make environmental queries for @code{MAX-N},
1836 :     @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
1837 :     unsigned (and positive) types is 0. The lower bound for signed types on
1838 :     two's complement and one's complement machines machines can be computed
1839 :     by adding 1 to the upper bound.
1840 :    
1841 :     @item read-only data space regions:
1842 :     The whole Forth data space is writable.
1843 :    
1844 :     @item size of buffer at @code{WORD}:
1845 :     @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
1846 :     shared with the pictured numeric output string. If overwriting
1847 :     @code{PAD} is acceptable, it is as large as the remaining dictionary
1848 :     space, although only as much can be sensibly used as fits in a counted
1849 :     string.
1850 :    
1851 :     @item size of one cell in address units:
1852 :     @code{1 cells .}.
1853 :    
1854 :     @item size of one character in address units:
1855 :     @code{1 chars .}. 1 on all current ports.
1856 :    
1857 :     @item size of the keyboard terminal buffer:
1858 :     Varies. You can determine the size at a specific time using @code{lp@
1859 :     tib - .}. It is shared with the locals stack and TIBs of files that
1860 :     include the current file. You can change the amount of space for TIBs
1861 : anton 1.17 and locals stack at Gforth startup with the command line option
1862 : anton 1.14 @code{-l}.
1863 :    
1864 :     @item size of the pictured numeric output buffer:
1865 :     @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
1866 :     shared with @code{WORD}.
1867 :    
1868 :     @item size of the scratch area returned by @code{PAD}:
1869 :     The remainder of dictionary space. You can even use the unused part of
1870 :     the data stack space. The current size can be computed with @code{sp@
1871 :     pad - .}.
1872 :    
1873 :     @item system case-sensitivity characteristics:
1874 :     Dictionary searches are case insensitive. However, as explained above
1875 :     under @i{character-set extensions}, the matching for non-ASCII
1876 :     characters is determined by the locale you are using. In the default
1877 :     @code{C} locale all non-ASCII characters are matched case-sensitively.
1878 :    
1879 :     @item system prompt:
1880 :     @code{ ok} in interpret state, @code{ compiled} in compile state.
1881 :    
1882 :     @item division rounding:
1883 :     installation dependent. @code{s" floored" environment? drop .}. We leave
1884 :     the choice to gcc (what to use for @code{/}) and to you (whether to use
1885 :     @code{fm/mod}, @code{sm/rem} or simply @code{/}).
1886 :    
1887 :     @item values of @code{STATE} when true:
1888 :     -1.
1889 :    
1890 :     @item values returned after arithmetic overflow:
1891 :     On two's complement machines, arithmetic is performed modulo
1892 :     2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1893 :     arithmetic (with appropriate mapping for signed types). Division by zero
1894 :     typically results in a @code{-55 throw} (floatingpoint unidentified
1895 :     fault), although a @code{-10 throw} (divide by zero) would be more
1896 :     appropriate.
1897 :    
1898 :     @item whether the current definition can be found after @t{DOES>}:
1899 :     No.
1900 :    
1901 :     @end table
1902 :    
1903 :     @c ---------------------------------------------------------------------
1904 :     @node core-ambcond, core-other, core-idef, The Core Words
1905 :     @subsection Ambiguous conditions
1906 :     @c ---------------------------------------------------------------------
1907 :    
1908 :     @table @i
1909 :    
1910 :     @item a name is neither a word nor a number:
1911 :     @code{-13 throw} (Undefined word)
1912 :    
1913 :     @item a definition name exceeds the maximum length allowed:
1914 :     @code{-19 throw} (Word name too long)
1915 :    
1916 :     @item addressing a region not inside the various data spaces of the forth system:
1917 :     The stacks, code space and name space are accessible. Machine code space is
1918 :     typically readable. Accessing other addresses gives results dependent on
1919 :     the operating system. On decent systems: @code{-9 throw} (Invalid memory
1920 :     address).
1921 :    
1922 :     @item argument type incompatible with parameter:
1923 :     This is usually not caught. Some words perform checks, e.g., the control
1924 :     flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
1925 :     mismatch).
1926 :    
1927 :     @item attempting to obtain the execution token of a word with undefined execution semantics:
1928 :     You get an execution token representing the compilation semantics
1929 :     instead.
1930 :    
1931 :     @item dividing by zero:
1932 :     typically results in a @code{-55 throw} (floating point unidentified
1933 :     fault), although a @code{-10 throw} (divide by zero) would be more
1934 :     appropriate.
1935 :    
1936 :     @item insufficient data stack or return stack space:
1937 :     Not checked. This typically results in mysterious illegal memory
1938 :     accesses, producing @code{-9 throw} (Invalid memory address) or
1939 :     @code{-23 throw} (Address alignment exception).
1940 :    
1941 :     @item insufficient space for loop control parameters:
1942 :     like other return stack overflows.
1943 :    
1944 :     @item insufficient space in the dictionary:
1945 :     Not checked. Similar results as stack overflows. However, typically the
1946 :     error appears at a different place when one inserts or removes code.
1947 :    
1948 :     @item interpreting a word with undefined interpretation semantics:
1949 :     For some words, we defined interpretation semantics. For the others:
1950 :     @code{-14 throw} (Interpreting a compile-only word). Note that this is
1951 :     checked only by the outer (aka text) interpreter; if the word is
1952 :     @code{execute}d in some other way, it will typically perform it's
1953 :     compilation semantics even in interpret state. (We could change @code{'}
1954 :     and relatives not to give the xt of such words, but we think that would
1955 :     be too restrictive).
1956 :    
1957 :     @item modifying the contents of the input buffer or a string literal:
1958 :     These are located in writable memory and can be modified.
1959 :    
1960 :     @item overflow of the pictured numeric output string:
1961 :     Not checked.
1962 :    
1963 :     @item parsed string overflow:
1964 :     @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
1965 :    
1966 :     @item producing a result out of range:
1967 :     On two's complement machines, arithmetic is performed modulo
1968 :     2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1969 :     arithmetic (with appropriate mapping for signed types). Division by zero
1970 :     typically results in a @code{-55 throw} (floatingpoint unidentified
1971 :     fault), although a @code{-10 throw} (divide by zero) would be more
1972 :     appropriate. @code{convert} and @code{>number} currently overflow
1973 :     silently.
1974 :    
1975 :     @item reading from an empty data or return stack:
1976 :     The data stack is checked by the outer (aka text) interpreter after
1977 :     every word executed. If it has underflowed, a @code{-4 throw} (Stack
1978 :     underflow) is performed. Apart from that, the stacks are not checked and
1979 :     underflows can result in similar behaviour as overflows (of adjacent
1980 :     stacks).
1981 :    
1982 :     @item unexepected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
1983 :     @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
1984 :     use zero-length string as a name). Words like @code{'} probably will not
1985 :     find what they search. Note that it is possible to create zero-length
1986 :     names with @code{nextname} (should it not?).
1987 :    
1988 :     @item @code{>IN} greater than input buffer:
1989 :     The next invocation of a parsing word returns a string wih length 0.
1990 :    
1991 :     @item @code{RECURSE} appears after @code{DOES>}:
1992 :     Compiles a recursive call to the defining word not to the defined word.
1993 :    
1994 :     @item argument input source different than current input source for @code{RESTORE-INPUT}:
1995 :     !!???If the argument input source is a valid input source then it gets
1996 :     restored. Otherwise causes @code{-12 THROW} which unless caught issues
1997 :     the message "argument type mismatch" and aborts.
1998 :    
1999 :     @item data space containing definitions gets de-allocated:
2000 :     Deallocation with @code{allot} is not checked. This typically resuls in
2001 :     memory access faults or execution of illegal instructions.
2002 :    
2003 :     @item data space read/write with incorrect alignment:
2004 :     Processor-dependent. Typically results in a @code{-23 throw} (Address
2005 :     alignment exception). Under Linux on a 486 or later processor with
2006 :     alignment turned on, incorrect alignment results in a @code{-9 throw}
2007 :     (Invalid memory address). There are reportedly some processors with
2008 :     alignment restrictions that do not report them.
2009 :    
2010 :     @item data space pointer not properly aligned, @code{,}, @code{C,}:
2011 :     Like other alignment errors.
2012 :    
2013 :     @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
2014 :     Not checked. May cause an illegal memory access.
2015 :    
2016 :     @item loop control parameters not available:
2017 :     Not checked. The counted loop words simply assume that the top of return
2018 :     stack items are loop control parameters and behave accordingly.
2019 :    
2020 :     @item most recent definition does not have a name (@code{IMMEDIATE}):
2021 :     @code{abort" last word was headerless"}.
2022 :    
2023 :     @item name not defined by @code{VALUE} used by @code{TO}:
2024 :     @code{-32 throw} (Invalid name argument)
2025 :    
2026 : anton 1.15 @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
2027 : anton 1.14 @code{-13 throw} (Undefined word)
2028 :    
2029 :     @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
2030 :     Gforth behaves as if they were of the same type. I.e., you can predict
2031 :     the behaviour by interpreting all parameters as, e.g., signed.
2032 :    
2033 :     @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
2034 :     Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} is equivalent to
2035 :     @code{TO}.
2036 :    
2037 :     @item String longer than a counted string returned by @code{WORD}:
2038 :     Not checked. The string will be ok, but the count will, of course,
2039 :     contain only the least significant bits of the length.
2040 :    
2041 : anton 1.15 @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
2042 : anton 1.14 Processor-dependent. Typical behaviours are returning 0 and using only
2043 :     the low bits of the shift count.
2044 :    
2045 :     @item word not defined via @code{CREATE}:
2046 :     @code{>BODY} produces the PFA of the word no matter how it was defined.
2047 :    
2048 :     @code{DOES>} changes the execution semantics of the last defined word no
2049 :     matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
2050 :     @code{CREATE , DOES>}.
2051 :    
2052 :     @item words improperly used outside @code{<#} and @code{#>}:
2053 :     Not checked. As usual, you can expect memory faults.
2054 :    
2055 :     @end table
2056 :    
2057 :    
2058 :     @c ---------------------------------------------------------------------
2059 :     @node core-other, , core-ambcond, The Core Words
2060 :     @subsection Other system documentation
2061 :     @c ---------------------------------------------------------------------
2062 :    
2063 :     @table @i
2064 :    
2065 :     @item nonstandard words using @code{PAD}:
2066 :     None.
2067 :    
2068 :     @item operator's terminal facilities available:
2069 :     !!??
2070 :    
2071 :     @item program data space available:
2072 :     @code{sp@ here - .} gives the space remaining for dictionary and data
2073 :     stack together.
2074 :    
2075 :     @item return stack space available:
2076 :     !!??
2077 :    
2078 :     @item stack space available:
2079 :     @code{sp@ here - .} gives the space remaining for dictionary and data
2080 :     stack together.
2081 :    
2082 :     @item system dictionary space required, in address units:
2083 :     Type @code{here forthstart - .} after startup. At the time of this
2084 :     writing, this gives 70108 (bytes) on a 32-bit system.
2085 :     @end table
2086 :    
2087 :    
2088 :     @c =====================================================================
2089 :     @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
2090 :     @section The optional Block word set
2091 :     @c =====================================================================
2092 :    
2093 :     @menu
2094 : anton 1.15 * block-idef:: Implementation Defined Options
2095 :     * block-ambcond:: Ambiguous Conditions
2096 :     * block-other:: Other System Documentation
2097 : anton 1.14 @end menu
2098 :    
2099 :    
2100 :     @c ---------------------------------------------------------------------
2101 :     @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
2102 :     @subsection Implementation Defined Options
2103 :     @c ---------------------------------------------------------------------
2104 :    
2105 :     @table @i
2106 :    
2107 :     @item the format for display by @code{LIST}:
2108 :     First the screen number is displayed, then 16 lines of 64 characters,
2109 :     each line preceded by the line number.
2110 :    
2111 :     @item the length of a line affected by @code{\}:
2112 :     64 characters.
2113 :     @end table
2114 :    
2115 :    
2116 :     @c ---------------------------------------------------------------------
2117 :     @node block-ambcond, block-other, block-idef, The optional Block word set
2118 :     @subsection Ambiguous conditions
2119 :     @c ---------------------------------------------------------------------
2120 :    
2121 :     @table @i
2122 :    
2123 :     @item correct block read was not possible:
2124 :     Typically results in a @code{throw} of some OS-derived value (between
2125 :     -512 and -2048). If the blocks file was just not long enough, blanks are
2126 :     supplied for the missing portion.
2127 :    
2128 :     @item I/O exception in block transfer:
2129 :     Typically results in a @code{throw} of some OS-derived value (between
2130 :     -512 and -2048).
2131 :    
2132 :     @item invalid block number:
2133 :     @code{-35 throw} (Invalid block number)
2134 :    
2135 :     @item a program directly alters the contents of @code{BLK}:
2136 :     The input stream is switched to that other block, at the same
2137 :     position. If the storing to @code{BLK} happens when interpreting
2138 :     non-block input, the system will get quite confused when the block ends.
2139 :    
2140 :     @item no current block buffer for @code{UPDATE}:
2141 :     @code{UPDATE} has no effect.
2142 :    
2143 :     @end table
2144 :    
2145 :    
2146 :     @c ---------------------------------------------------------------------
2147 :     @node block-other, , block-ambcond, The optional Block word set
2148 :     @subsection Other system documentation
2149 :     @c ---------------------------------------------------------------------
2150 :    
2151 :     @table @i
2152 :    
2153 :     @item any restrictions a multiprogramming system places on the use of buffer addresses:
2154 :     No restrictions (yet).
2155 :    
2156 :     @item the number of blocks available for source and data:
2157 :     depends on your disk space.
2158 :    
2159 :     @end table
2160 :    
2161 :    
2162 :     @c =====================================================================
2163 :     @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
2164 :     @section The optional Double Number word set
2165 :     @c =====================================================================
2166 :    
2167 :     @menu
2168 : anton 1.15 * double-ambcond:: Ambiguous Conditions
2169 : anton 1.14 @end menu
2170 :    
2171 :    
2172 :     @c ---------------------------------------------------------------------
2173 : anton 1.15 @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
2174 : anton 1.14 @subsection Ambiguous conditions
2175 :     @c ---------------------------------------------------------------------
2176 :    
2177 :     @table @i
2178 :    
2179 : anton 1.15 @item @var{d} outside of range of @var{n} in @code{D>S}:
2180 : anton 1.14 The least significant cell of @var{d} is produced.
2181 :    
2182 :     @end table
2183 :    
2184 :    
2185 :     @c =====================================================================
2186 :     @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
2187 :     @section The optional Exception word set
2188 :     @c =====================================================================
2189 :    
2190 :     @menu
2191 : anton 1.15 * exception-idef:: Implementation Defined Options
2192 : anton 1.14 @end menu
2193 :    
2194 :    
2195 :     @c ---------------------------------------------------------------------
2196 : anton 1.15 @node exception-idef, , The optional Exception word set, The optional Exception word set
2197 : anton 1.14 @subsection Implementation Defined Options
2198 :     @c ---------------------------------------------------------------------
2199 :    
2200 :     @table @i
2201 :     @item @code{THROW}-codes used in the system:
2202 :     The codes -256@minus{}-511 are used for reporting signals (see
2203 :     @file{errore.fs}). The codes -512@minus{}-2047 are used for OS errors
2204 :     (for file and memory allocation operations). The mapping from OS error
2205 :     numbers to throw code is -512@minus{}@var{errno}. One side effect of
2206 :     this mapping is that undefined OS errors produce a message with a
2207 :     strange number; e.g., @code{-1000 THROW} results in @code{Unknown error
2208 :     488} on my system.
2209 :     @end table
2210 :    
2211 :     @c =====================================================================
2212 :     @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
2213 :     @section The optional Facility word set
2214 :     @c =====================================================================
2215 :    
2216 :     @menu
2217 : anton 1.15 * facility-idef:: Implementation Defined Options
2218 :     * facility-ambcond:: Ambiguous Conditions
2219 : anton 1.14 @end menu
2220 :    
2221 :    
2222 :     @c ---------------------------------------------------------------------
2223 :     @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
2224 :     @subsection Implementation Defined Options
2225 :     @c ---------------------------------------------------------------------
2226 :    
2227 :     @table @i
2228 :    
2229 :     @item encoding of keyboard events (@code{EKEY}):
2230 :     Not yet implemeted.
2231 :    
2232 :     @item duration of a system clock tick
2233 :     System dependent. With respect to @code{MS}, the time is specified in
2234 :     microseconds. How well the OS and the hardware implement this, is
2235 :     another question.
2236 :    
2237 :     @item repeatability to be expected from the execution of @code{MS}:
2238 :     System dependent. On Unix, a lot depends on load. If the system is
2239 : anton 1.17 lightly loaded, and the delay is short enough that Gforth does not get
2240 : anton 1.14 swapped out, the performance should be acceptable. Under MS-DOS and
2241 :     other single-tasking systems, it should be good.
2242 :    
2243 :     @end table
2244 :    
2245 :    
2246 :     @c ---------------------------------------------------------------------
2247 : anton 1.15 @node facility-ambcond, , facility-idef, The optional Facility word set
2248 : anton 1.14 @subsection Ambiguous conditions
2249 :     @c ---------------------------------------------------------------------
2250 :    
2251 :     @table @i
2252 :    
2253 :     @item @code{AT-XY} can't be performed on user output device:
2254 :     Largely terminal dependant. No range checks are done on the arguments.
2255 :     No errors are reported. You may see some garbage appearing, you may see
2256 :     simply nothing happen.
2257 :    
2258 :     @end table
2259 :    
2260 :    
2261 :     @c =====================================================================
2262 :     @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
2263 :     @section The optional File-Access word set
2264 :     @c =====================================================================
2265 :    
2266 :     @menu
2267 : anton 1.15 * file-idef:: Implementation Defined Options
2268 :     * file-ambcond:: Ambiguous Conditions
2269 : anton 1.14 @end menu
2270 :    
2271 :    
2272 :     @c ---------------------------------------------------------------------
2273 :     @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
2274 :     @subsection Implementation Defined Options
2275 :     @c ---------------------------------------------------------------------
2276 :    
2277 :     @table @i
2278 :    
2279 :     @item File access methods used:
2280 :     @code{R/O}, @code{R/W} and @code{BIN} work as you would
2281 :     expect. @code{W/O} translates into the C file opening mode @code{w} (or
2282 :     @code{wb}): The file is cleared, if it exists, and created, if it does
2283 : anton 1.15 not (both with @code{open-file} and @code{create-file}). Under Unix
2284 : anton 1.14 @code{create-file} creates a file with 666 permissions modified by your
2285 :     umask.
2286 :    
2287 :     @item file exceptions:
2288 :     The file words do not raise exceptions (except, perhaps, memory access
2289 :     faults when you pass illegal addresses or file-ids).
2290 :    
2291 :     @item file line terminator:
2292 :     System-dependent. Gforth uses C's newline character as line
2293 :     terminator. What the actual character code(s) of this are is
2294 :     system-dependent.
2295 :    
2296 :     @item file name format
2297 :     System dependent. Gforth just uses the file name format of your OS.
2298 :    
2299 :     @item information returned by @code{FILE-STATUS}:
2300 :     @code{FILE-STATUS} returns the most powerful file access mode allowed
2301 :     for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
2302 :     cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
2303 :     along with the retured mode.
2304 :    
2305 :     @item input file state after an exception when including source:
2306 :     All files that are left via the exception are closed.
2307 :    
2308 :     @item @var{ior} values and meaning:
2309 : anton 1.15 The @var{ior}s returned by the file and memory allocation words are
2310 :     intended as throw codes. They typically are in the range
2311 :     -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
2312 :     @var{ior}s is -512@minus{}@var{errno}.
2313 : anton 1.14
2314 :     @item maximum depth of file input nesting:
2315 :     limited by the amount of return stack, locals/TIB stack, and the number
2316 :     of open files available. This should not give you troubles.
2317 :    
2318 :     @item maximum size of input line:
2319 :     @code{/line}. Currently 255.
2320 :    
2321 :     @item methods of mapping block ranges to files:
2322 :     Currently, the block words automatically access the file
2323 :     @file{blocks.fb} in the currend working directory. More sophisticated
2324 :     methods could be implemented if there is demand (and a volunteer).
2325 :    
2326 :     @item number of string buffers provided by @code{S"}:
2327 :     1
2328 :    
2329 :     @item size of string buffer used by @code{S"}:
2330 :     @code{/line}. currently 255.
2331 :    
2332 :     @end table
2333 :    
2334 :     @c ---------------------------------------------------------------------
2335 : anton 1.15 @node file-ambcond, , file-idef, The optional File-Access word set
2336 : anton 1.14 @subsection Ambiguous conditions
2337 :     @c ---------------------------------------------------------------------
2338 :    
2339 :     @table @i
2340 :    
2341 :     @item attempting to position a file outside it's boundaries:
2342 :     @code{REPOSITION-FILE} is performed as usual: Afterwards,
2343 :     @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
2344 :    
2345 :     @item attempting to read from file positions not yet written:
2346 :     End-of-file, i.e., zero characters are read and no error is reported.
2347 :    
2348 :     @item @var{file-id} is invalid (@code{INCLUDE-FILE}):
2349 :     An appropriate exception may be thrown, but a memory fault or other
2350 :     problem is more probable.
2351 :    
2352 :     @item I/O exception reading or closing @var{file-id} (@code{include-file}, @code{included}):
2353 :     The @var{ior} produced by the operation, that discovered the problem, is
2354 :     thrown.
2355 :    
2356 :     @item named file cannot be opened (@code{included}):
2357 :     The @var{ior} produced by @code{open-file} is thrown.
2358 :    
2359 :     @item requesting an unmapped block number:
2360 :     There are no unmapped legal block numbers. On some operating systems,
2361 :     writing a block with a large number may overflow the file system and
2362 :     have an error message as consequence.
2363 :    
2364 :     @item using @code{source-id} when @code{blk} is non-zero:
2365 :     @code{source-id} performs its function. Typically it will give the id of
2366 :     the source which loaded the block. (Better ideas?)
2367 :    
2368 :     @end table
2369 :    
2370 :    
2371 :     @c =====================================================================
2372 :     @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
2373 : anton 1.15 @section The optional Floating-Point word set
2374 : anton 1.14 @c =====================================================================
2375 :    
2376 :     @menu
2377 : anton 1.15 * floating-idef:: Implementation Defined Options
2378 :     * floating-ambcond:: Ambiguous Conditions
2379 : anton 1.14 @end menu
2380 :    
2381 :    
2382 :     @c ---------------------------------------------------------------------
2383 :     @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
2384 :     @subsection Implementation Defined Options
2385 :     @c ---------------------------------------------------------------------
2386 :    
2387 :     @table @i
2388 :    
2389 : anton 1.15 @item format and range of floating point numbers:
2390 :     System-dependent; the @code{double} type of C.
2391 : anton 1.14
2392 : anton 1.15 @item results of @code{REPRESENT} when @var{float} is out of range:
2393 :     System dependent; @code{REPRESENT} is implemented using the C library
2394 :     function @code{ecvt()} and inherits its behaviour in this respect.
2395 : anton 1.14
2396 : anton 1.15 @item rounding or truncation of floating-point numbers:
2397 :     What's the question?!!
2398 : anton 1.14
2399 : anton 1.15 @item size of floating-point stack:
2400 :     @code{s" FLOATING-STACK" environment? drop .}. Can be changed at startup
2401 :     with the command-line option @code{-f}.
2402 : anton 1.14
2403 : anton 1.15 @item width of floating-point stack:
2404 :     @code{1 floats}.
2405 : anton 1.14
2406 :     @end table
2407 :    
2408 :    
2409 :     @c ---------------------------------------------------------------------
2410 : anton 1.15 @node floating-ambcond, , floating-idef, The optional Floating-Point word set
2411 :     @subsection Ambiguous conditions
2412 : anton 1.14 @c ---------------------------------------------------------------------
2413 :    
2414 :     @table @i
2415 :    
2416 : anton 1.15 @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
2417 :     System-dependent. Typically results in an alignment fault like other
2418 :     alignment violations.
2419 : anton 1.14
2420 : anton 1.15 @item @code{f@@} or @code{f!} used with an address that is not float aligned:
2421 :     System-dependent. Typically results in an alignment fault like other
2422 :     alignment violations.
2423 : anton 1.14
2424 : anton 1.15 @item Floating-point result out of range:
2425 :     System-dependent. Can result in a @code{-55 THROW} (Floating-point
2426 :     unidentified fault), or can produce a special value representing, e.g.,
2427 :     Infinity.
2428 : anton 1.14
2429 : anton 1.15 @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
2430 :     System-dependent. Typically results in an alignment fault like other
2431 :     alignment violations.
2432 : anton 1.14
2433 : anton 1.15 @item BASE is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
2434 :     The floating-point number is converted into decimal nonetheless.
2435 : anton 1.14
2436 : anton 1.15 @item Both arguments are equal to zero (@code{FATAN2}):
2437 :     System-dependent. @code{FATAN2} is implemented using the C library
2438 :     function @code{atan2()}.
2439 : anton 1.14
2440 : anton 1.15 @item Using ftan on an argument @var{r1} where cos(@var{r1}) is zero:
2441 :     System-dependent. Anyway, typically the cos of @var{r1} will not be zero
2442 :     because of small errors and the tan will be a very large (or very small)
2443 :     but finite number.
2444 : anton 1.14
2445 : anton 1.15 @item @var{d} cannot be presented precisely as a float in @code{D>F}:
2446 :     The result is rounded to the nearest float.
2447 : anton 1.14
2448 : anton 1.15 @item dividing by zero:
2449 :     @code{-55 throw} (Floating-point unidentified fault)
2450 : anton 1.14
2451 : anton 1.15 @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
2452 :     System dependent. On IEEE-FP based systems the number is converted into
2453 :     an infinity.
2454 : anton 1.14
2455 : anton 1.15 @item @var{float}<1 (@code{facosh}):
2456 :     @code{-55 throw} (Floating-point unidentified fault)
2457 : anton 1.14
2458 : anton 1.15 @item @var{float}=<-1 (@code{flnp1}):
2459 :     @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
2460 :     negative infinity is typically produced for @var{float}=-1.
2461 : anton 1.14
2462 : anton 1.15 @item @var{float}=<0 (@code{fln}, @code{flog}):
2463 :     @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
2464 :     negative infinity is typically produced for @var{float}=0.
2465 : anton 1.14
2466 : anton 1.15 @item @var{float}<0 (@code{fasinh}, @code{fsqrt}):
2467 :     @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
2468 :     produces values for these inputs on my Linux box (Bug in the C library?)
2469 : anton 1.14
2470 : anton 1.15 @item |@var{float}|>1 (@code{facos}, @code{fasin}, @code{fatanh}):
2471 :     @code{-55 throw} (Floating-point unidentified fault).
2472 : anton 1.14
2473 : anton 1.15 @item integer part of float cannot be represented by @var{d} in @code{f>d}:
2474 :     @code{-55 throw} (Floating-point unidentified fault).
2475 : anton 1.14
2476 : anton 1.15 @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
2477 :     This does not happen.
2478 :     @end table
2479 : anton 1.14
2480 :    
2481 :    
2482 :     @c =====================================================================
2483 : anton 1.15 @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
2484 :     @section The optional Locals word set
2485 : anton 1.14 @c =====================================================================
2486 :    
2487 :     @menu
2488 : anton 1.15 * locals-idef:: Implementation Defined Options
2489 :     * locals-ambcond:: Ambiguous Conditions
2490 : anton 1.14 @end menu
2491 :    
2492 :    
2493 :     @c ---------------------------------------------------------------------
2494 : anton 1.15 @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
2495 : anton 1.14 @subsection Implementation Defined Options
2496 :     @c ---------------------------------------------------------------------
2497 :    
2498 :     @table @i
2499 :    
2500 : anton 1.15 @item maximum number of locals in a definition:
2501 :     @code{s" #locals" environment? drop .}. Currently 15. This is a lower
2502 :     bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
2503 :     characters. The number of locals in a definition is bounded by the size
2504 :     of locals-buffer, which contains the names of the locals.
2505 : anton 1.14
2506 :     @end table
2507 :    
2508 :    
2509 :     @c ---------------------------------------------------------------------
2510 : anton 1.15 @node locals-ambcond, , locals-idef, The optional Locals word set
2511 : anton 1.14 @subsection Ambiguous conditions
2512 :     @c ---------------------------------------------------------------------
2513 :    
2514 :     @table @i
2515 :    
2516 : anton 1.15 @item executing a named local in interpretation state:
2517 :     @code{-14 throw} (Interpreting a compile-only word).
2518 : anton 1.14
2519 : anton 1.15 @item @var{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
2520 :     @code{-32 throw} (Invalid name argument)
2521 : anton 1.14
2522 :     @end table
2523 :    
2524 :    
2525 :     @c =====================================================================
2526 : anton 1.15 @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
2527 :     @section The optional Memory-Allocation word set
2528 : anton 1.14 @c =====================================================================
2529 :    
2530 :     @menu
2531 : anton 1.15 * memory-idef:: Implementation Defined Options
2532 : anton 1.14 @end menu
2533 :    
2534 :    
2535 :     @c ---------------------------------------------------------------------
2536 : anton 1.15 @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
2537 : anton 1.14 @subsection Implementation Defined Options
2538 :     @c ---------------------------------------------------------------------
2539 :    
2540 :     @table @i
2541 :    
2542 : anton 1.15 @item values and meaning of @var{ior}:
2543 :     The @var{ior}s returned by the file and memory allocation words are
2544 :     intended as throw codes. They typically are in the range
2545 :     -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
2546 :     @var{ior}s is -512@minus{}@var{errno}.
2547 : anton 1.14
2548 :     @end table
2549 :    
2550 :     @c =====================================================================
2551 : anton 1.15 @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
2552 :     @section The optional Programming-Tools word set
2553 : anton 1.14 @c =====================================================================
2554 :    
2555 :     @menu
2556 : anton 1.15 * programming-idef:: Implementation Defined Options
2557 :     * programming-ambcond:: Ambiguous Conditions
2558 : anton 1.14 @end menu
2559 :    
2560 :    
2561 :     @c ---------------------------------------------------------------------
2562 : anton 1.15 @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
2563 : anton 1.14 @subsection Implementation Defined Options
2564 :     @c ---------------------------------------------------------------------
2565 :    
2566 :     @table @i
2567 :    
2568 : anton 1.15 @item ending sequence for input following @code{;code} and @code{code}:
2569 :     Not implemented (yet).
2570 : anton 1.14
2571 : anton 1.15 @item manner of processing input following @code{;code} and @code{code}:
2572 :     Not implemented (yet).
2573 :    
2574 :     @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
2575 :     Not implemented (yet). If they were implemented, they would use the
2576 :     search order wordset.
2577 :    
2578 :     @item source and format of display by @code{SEE}:
2579 :     The source for @code{see} is the intermediate code used by the inner
2580 :     interpreter. The current @code{see} tries to output Forth source code
2581 :     as well as possible.
2582 :    
2583 : anton 1.14 @end table
2584 :    
2585 :     @c ---------------------------------------------------------------------
2586 : anton 1.15 @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
2587 : anton 1.14 @subsection Ambiguous conditions
2588 :     @c ---------------------------------------------------------------------
2589 :    
2590 :     @table @i
2591 :    
2592 : anton 1.15 @item deleting the compilation wordlist (@code{FORGET}):
2593 :     Not implemented (yet).
2594 : anton 1.14
2595 : anton 1.15 @item fewer than @var{u}+1 items on the control flow stack (@code{CS-PICK}, @code{CS-ROLL}):
2596 :     This typically results in an @code{abort"} with a descriptive error
2597 :     message (may change into a @code{-22 throw} (Control structure mismatch)
2598 :     in the future). You may also get a memory access error. If you are
2599 :     unlucky, this ambiguous condition is not caught.
2600 :    
2601 :     @item @var{name} can't be found (@code{forget}):
2602 :     Not implemented (yet).
2603 : anton 1.14
2604 : anton 1.15 @item @var{name} not defined via @code{CREATE}:
2605 :     @code{;code} is not implemented (yet). If it were, it would behave like
2606 :     @code{DOES>} in this respect, i.e., change the execution semantics of
2607 :     the last defined word no matter how it was defined.
2608 : anton 1.14
2609 : anton 1.15 @item @code{POSTPONE} applied to @code{[IF]}:
2610 :     After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
2611 :     equivalent to @code{[IF]}.
2612 : anton 1.14
2613 : anton 1.15 @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
2614 :     Continue in the same state of conditional compilation in the next outer
2615 :     input source. Currently there is no warning to the user about this.
2616 : anton 1.14
2617 : anton 1.15 @item removing a needed definition (@code{FORGET}):
2618 :     Not implemented (yet).
2619 : anton 1.14
2620 :     @end table
2621 :    
2622 :    
2623 :     @c =====================================================================
2624 : anton 1.15 @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
2625 :     @section The optional Search-Order word set
2626 : anton 1.14 @c =====================================================================
2627 :    
2628 :     @menu
2629 : anton 1.15 * search-idef:: Implementation Defined Options
2630 :     * search-ambcond:: Ambiguous Conditions
2631 : anton 1.14 @end menu
2632 :    
2633 :    
2634 :     @c ---------------------------------------------------------------------
2635 : anton 1.15 @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
2636 : anton 1.14 @subsection Implementation Defined Options
2637 :     @c ---------------------------------------------------------------------
2638 :    
2639 :     @table @i
2640 :    
2641 : anton 1.15 @item maximum number of word lists in search order:
2642 :     @code{s" wordlists" environment? drop .}. Currently 16.
2643 :    
2644 :     @item minimum search order:
2645 :     @code{root root}.
2646 : anton 1.14
2647 :     @end table
2648 :    
2649 :     @c ---------------------------------------------------------------------
2650 : anton 1.15 @node search-ambcond, , search-idef, The optional Search-Order word set
2651 : anton 1.14 @subsection Ambiguous conditions
2652 :     @c ---------------------------------------------------------------------
2653 :    
2654 :     @table @i
2655 :    
2656 : anton 1.15 @item changing the compilation wordlist (during compilation):
2657 :     The definition is put into the wordlist that is the compilation wordlist
2658 :     when @code{REVEAL} is executed (by @code{;}, @code{DOES>},
2659 :     @code{RECURSIVE}, etc.).
2660 : anton 1.14
2661 : anton 1.15 @item search order empty (@code{previous}):
2662 :     @code{abort" Vocstack empty"}.
2663 : anton 1.14
2664 : anton 1.15 @item too many word lists in search order (@code{also}):
2665 :     @code{abort" Vocstack full"}.
2666 : anton 1.14
2667 :     @end table
2668 : anton 1.13
2669 :    
2670 : anton 1.17 @node Model, Emacs and Gforth, ANS conformance, Top
2671 : anton 1.4 @chapter Model
2672 :    
2673 : anton 1.17 @node Emacs and Gforth, Internals, Model, Top
2674 :     @chapter Emacs and Gforth
2675 : anton 1.4
2676 : anton 1.17 Gforth comes with @file{gforth.el}, an improved version of
2677 : anton 1.4 @file{forth.el} by Goran Rydqvist (icluded in the TILE package). The
2678 :     improvements are a better (but still not perfect) handling of
2679 :     indentation. I have also added comment paragraph filling (@kbd{M-q}),
2680 : anton 1.8 commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) regions and
2681 :     removing debugging tracers (@kbd{C-x ~}, @pxref{Debugging}). I left the
2682 :     stuff I do not use alone, even though some of it only makes sense for
2683 :     TILE. To get a description of these features, enter Forth mode and type
2684 :     @kbd{C-h m}.
2685 : anton 1.4
2686 : anton 1.17 In addition, Gforth supports Emacs quite well: The source code locations
2687 : anton 1.4 given in error messages, debugging output (from @code{~~}) and failed
2688 :     assertion messages are in the right format for Emacs' compilation mode
2689 :     (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
2690 :     Manual}) so the source location corresponding to an error or other
2691 :     message is only a few keystrokes away (@kbd{C-x `} for the next error,
2692 :     @kbd{C-c C-c} for the error under the cursor).
2693 :    
2694 :     Also, if you @code{include} @file{etags.fs}, a new @file{TAGS} file
2695 :     (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) will be produced that
2696 :     contains the definitions of all words defined afterwards. You can then
2697 :     find the source for a word using @kbd{M-.}. Note that emacs can use
2698 : anton 1.17 several tags files at the same time (e.g., one for the Gforth sources
2699 : anton 1.4 and one for your program).
2700 :    
2701 :     To get all these benefits, add the following lines to your @file{.emacs}
2702 :     file:
2703 :    
2704 :     @example
2705 :     (autoload 'forth-mode "gforth.el")
2706 :     (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
2707 :     @end example
2708 :    
2709 : anton 1.17 @node Internals, Bugs, Emacs and Gforth, Top
2710 : anton 1.3 @chapter Internals
2711 :    
2712 : anton 1.17 Reading this section is not necessary for programming with Gforth. It
2713 :     should be helpful for finding your way in the Gforth sources.
2714 : anton 1.3
2715 : anton 1.4 @menu
2716 :     * Portability::
2717 :     * Threading::
2718 :     * Primitives::
2719 :     * System Architecture::
2720 : anton 1.17 * Performance::
2721 : anton 1.4 @end menu
2722 :    
2723 :     @node Portability, Threading, Internals, Internals
2724 : anton 1.3 @section Portability
2725 :    
2726 :     One of the main goals of the effort is availability across a wide range
2727 :     of personal machines. fig-Forth, and, to a lesser extent, F83, achieved
2728 :     this goal by manually coding the engine in assembly language for several
2729 :     then-popular processors. This approach is very labor-intensive and the
2730 :     results are short-lived due to progress in computer architecture.
2731 :    
2732 :     Others have avoided this problem by coding in C, e.g., Mitch Bradley
2733 :     (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
2734 :     particularly popular for UNIX-based Forths due to the large variety of
2735 :     architectures of UNIX machines. Unfortunately an implementation in C
2736 :     does not mix well with the goals of efficiency and with using
2737 :     traditional techniques: Indirect or direct threading cannot be expressed
2738 :     in C, and switch threading, the fastest technique available in C, is
2739 :     significantly slower. Another problem with C is that it's very
2740 :     cumbersome to express double integer arithmetic.
2741 :    
2742 :     Fortunately, there is a portable language that does not have these
2743 :     limitations: GNU C, the version of C processed by the GNU C compiler
2744 :     (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
2745 :     GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
2746 :     Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
2747 :     threading possible, its @code{long long} type (@pxref{Long Long, ,
2748 :     Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forths
2749 :     double numbers. GNU C is available for free on all important (and many
2750 :     unimportant) UNIX machines, VMS, 80386s running MS-DOS, the Amiga, and
2751 :     the Atari ST, so a Forth written in GNU C can run on all these
2752 : anton 1.17 machines.
2753 : anton 1.3
2754 :     Writing in a portable language has the reputation of producing code that
2755 :     is slower than assembly. For our Forth engine we repeatedly looked at
2756 :     the code produced by the compiler and eliminated most compiler-induced
2757 :     inefficiencies by appropriate changes in the source-code.
2758 :    
2759 :     However, register allocation cannot be portably influenced by the
2760 :     programmer, leading to some inefficiencies on register-starved
2761 :     machines. We use explicit register declarations (@pxref{Explicit Reg
2762 :     Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
2763 :     improve the speed on some machines. They are turned on by using the
2764 :     @code{gcc} switch @code{-DFORCE_REG}. Unfortunately, this feature not
2765 :     only depends on the machine, but also on the compiler version: On some
2766 :     machines some compiler versions produce incorrect code when certain
2767 :     explicit register declarations are used. So by default
2768 :     @code{-DFORCE_REG} is not used.
2769 :    
2770 : anton 1.4 @node Threading, Primitives, Portability, Internals
2771 : anton 1.3 @section Threading
2772 :    
2773 :     GNU C's labels as values extension (available since @code{gcc-2.0},
2774 :     @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
2775 :     makes it possible to take the address of @var{label} by writing
2776 :     @code{&&@var{label}}. This address can then be used in a statement like
2777 :     @code{goto *@var{address}}. I.e., @code{goto *&&x} is the same as
2778 :     @code{goto x}.
2779 :    
2780 :     With this feature an indirect threaded NEXT looks like:
2781 :     @example
2782 :     cfa = *ip++;
2783 :     ca = *cfa;
2784 :     goto *ca;
2785 :     @end example
2786 :     For those unfamiliar with the names: @code{ip} is the Forth instruction
2787 :     pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
2788 :     execution token and points to the code field of the next word to be
2789 :     executed; The @code{ca} (code address) fetched from there points to some
2790 :     executable code, e.g., a primitive or the colon definition handler
2791 :     @code{docol}.
2792 :    
2793 :     Direct threading is even simpler:
2794 :     @example
2795 :     ca = *ip++;
2796 :     goto *ca;
2797 :     @end example
2798 :    
2799 :     Of course we have packaged the whole thing neatly in macros called
2800 :     @code{NEXT} and @code{NEXT1} (the part of NEXT after fetching the cfa).
2801 :    
2802 : anton 1.4 @menu
2803 :     * Scheduling::
2804 :     * Direct or Indirect Threaded?::
2805 :     * DOES>::
2806 :     @end menu
2807 :    
2808 :     @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
2809 : anton 1.3 @subsection Scheduling
2810 :    
2811 :     There is a little complication: Pipelined and superscalar processors,
2812 :     i.e., RISC and some modern CISC machines can process independent
2813 :     instructions while waiting for the results of an instruction. The
2814 :     compiler usually reorders (schedules) the instructions in a way that
2815 :     achieves good usage of these delay slots. However, on our first tries
2816 :     the compiler did not do well on scheduling primitives. E.g., for
2817 :     @code{+} implemented as
2818 :     @example
2819 :     n=sp[0]+sp[1];
2820 :     sp++;
2821 :     sp[0]=n;
2822 :     NEXT;
2823 :     @end example
2824 :     the NEXT comes strictly after the other code, i.e., there is nearly no
2825 :     scheduling. After a little thought the problem becomes clear: The
2826 :     compiler cannot know that sp and ip point to different addresses (and
2827 : anton 1.4 the version of @code{gcc} we used would not know it even if it was
2828 :     possible), so it could not move the load of the cfa above the store to
2829 :     the TOS. Indeed the pointers could be the same, if code on or very near
2830 :     the top of stack were executed. In the interest of speed we chose to
2831 :     forbid this probably unused ``feature'' and helped the compiler in
2832 :     scheduling: NEXT is divided into the loading part (@code{NEXT_P1}) and
2833 :     the goto part (@code{NEXT_P2}). @code{+} now looks like:
2834 : anton 1.3 @example
2835 :     n=sp[0]+sp[1];
2836 :     sp++;
2837 :     NEXT_P1;
2838 :     sp[0]=n;
2839 :     NEXT_P2;
2840 :     @end example
2841 : anton 1.4 This can be scheduled optimally by the compiler.
2842 : anton 1.3
2843 :     This division can be turned off with the switch @code{-DCISC_NEXT}. This
2844 :     switch is on by default on machines that do not profit from scheduling
2845 :     (e.g., the 80386), in order to preserve registers.
2846 :    
2847 : anton 1.4 @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
2848 : anton 1.3 @subsection Direct or Indirect Threaded?
2849 :    
2850 :     Both! After packaging the nasty details in macro definitions we
2851 :     realized that we could switch between direct and indirect threading by
2852 :     simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
2853 :     defining a few machine-specific macros for the direct-threading case.
2854 :     On the Forth level we also offer access words that hide the
2855 :     differences between the threading methods (@pxref{Threading Words}).
2856 :    
2857 :     Indirect threading is implemented completely
2858 :     machine-independently. Direct threading needs routines for creating
2859 :     jumps to the executable code (e.g. to docol or dodoes). These routines
2860 :     are inherently machine-dependent, but they do not amount to many source
2861 :     lines. I.e., even porting direct threading to a new machine is a small
2862 :     effort.
2863 :    
2864 : anton 1.4 @node DOES>, , Direct or Indirect Threaded?, Threading
2865 : anton 1.3 @subsection DOES>
2866 :     One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
2867 :     the chunk of code executed by every word defined by a
2868 :     @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
2869 :     the Forth code to be executed, i.e. the code after the @code{DOES>} (the
2870 :     DOES-code)? There are two solutions:
2871 :    
2872 :     In fig-Forth the code field points directly to the dodoes and the
2873 :     DOES-code address is stored in the cell after the code address
2874 :     (i.e. at cfa cell+). It may seem that this solution is illegal in the
2875 :     Forth-79 and all later standards, because in fig-Forth this address
2876 :     lies in the body (which is illegal in these standards). However, by
2877 :     making the code field larger for all words this solution becomes legal
2878 :     again. We use this approach for the indirect threaded version. Leaving
2879 :     a cell unused in most words is a bit wasteful, but on the machines we
2880 :     are targetting this is hardly a problem. The other reason for having a
2881 :     code field size of two cells is to avoid having different image files
2882 : anton 1.4 for direct and indirect threaded systems (@pxref{System Architecture}).
2883 : anton 1.3
2884 :     The other approach is that the code field points or jumps to the cell
2885 :     after @code{DOES}. In this variant there is a jump to @code{dodoes} at
2886 :     this address. @code{dodoes} can then get the DOES-code address by
2887 :     computing the code address, i.e., the address of the jump to dodoes,
2888 :     and add the length of that jump field. A variant of this is to have a
2889 :     call to @code{dodoes} after the @code{DOES>}; then the return address
2890 :     (which can be found in the return register on RISCs) is the DOES-code
2891 :     address. Since the two cells available in the code field are usually
2892 :     used up by the jump to the code address in direct threading, we use
2893 :     this approach for direct threading. We did not want to add another
2894 :     cell to the code field.
2895 :    
2896 : anton 1.4 @node Primitives, System Architecture, Threading, Internals
2897 : anton 1.3 @section Primitives
2898 :    
2899 : anton 1.4 @menu
2900 :     * Automatic Generation::
2901 :     * TOS Optimization::
2902 :     * Produced code::
2903 :     @end menu
2904 :    
2905 :     @node Automatic Generation, TOS Optimization, Primitives, Primitives
2906 : anton 1.3 @subsection Automatic Generation
2907 :    
2908 :     Since the primitives are implemented in a portable language, there is no
2909 :     longer any need to minimize the number of primitives. On the contrary,
2910 :     having many primitives is an advantage: speed. In order to reduce the
2911 :     number of errors in primitives and to make programming them easier, we
2912 :     provide a tool, the primitive generator (@file{prims2x.fs}), that
2913 :     automatically generates most (and sometimes all) of the C code for a
2914 :     primitive from the stack effect notation. The source for a primitive
2915 :     has the following form:
2916 :    
2917 :     @format
2918 :     @var{Forth-name} @var{stack-effect} @var{category} [@var{pronounc.}]
2919 :     [@code{""}@var{glossary entry}@code{""}]
2920 :     @var{C code}
2921 :     [@code{:}
2922 :     @var{Forth code}]
2923 :     @end format
2924 :    
2925 :     The items in brackets are optional. The category and glossary fields
2926 :     are there for generating the documentation, the Forth code is there
2927 :     for manual implementations on machines without GNU C. E.g., the source
2928 :     for the primitive @code{+} is:
2929 :     @example
2930 :     + n1 n2 -- n core plus
2931 :     n = n1+n2;
2932 :     @end example
2933 :    
2934 :     This looks like a specification, but in fact @code{n = n1+n2} is C
2935 :     code. Our primitive generation tool extracts a lot of information from
2936 :     the stack effect notations@footnote{We use a one-stack notation, even
2937 :     though we have separate data and floating-point stacks; The separate
2938 :     notation can be generated easily from the unified notation.}: The number
2939 :     of items popped from and pushed on the stack, their type, and by what
2940 :     name they are referred to in the C code. It then generates a C code
2941 :     prelude and postlude for each primitive. The final C code for @code{+}
2942 :     looks like this:
2943 :    
2944 :     @example
2945 :     I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
2946 :     /* */ /* documentation */
2947 : anton 1.4 @{
2948 : anton 1.3 DEF_CA /* definition of variable ca (indirect threading) */
2949 :     Cell n1; /* definitions of variables */
2950 :     Cell n2;
2951 :     Cell n;
2952 :     n1 = (Cell) sp[1]; /* input */
2953 :     n2 = (Cell) TOS;
2954 :     sp += 1; /* stack adjustment */
2955 :     NAME("+") /* debugging output (with -DDEBUG) */
2956 : anton 1.4 @{
2957 : anton 1.3 n = n1+n2; /* C code taken from the source */
2958 : anton 1.4 @}
2959 : anton 1.3 NEXT_P1; /* NEXT part 1 */
2960 :     TOS = (Cell)n; /* output */
2961 :     NEXT_P2; /* NEXT part 2 */
2962 : anton 1.4 @}
2963 : anton 1.3 @end example
2964 :    
2965 :     This looks long and inefficient, but the GNU C compiler optimizes quite
2966 :     well and produces optimal code for @code{+} on, e.g., the R3000 and the
2967 :     HP RISC machines: Defining the @code{n}s does not produce any code, and
2968 :     using them as intermediate storage also adds no cost.
2969 :    
2970 :     There are also other optimizations, that are not illustrated by this
2971 :     example: Assignments between simple variables are usually for free (copy
2972 :     propagation). If one of the stack items is not used by the primitive
2973 :     (e.g. in @code{drop}), the compiler eliminates the load from the stack
2974 :     (dead code elimination). On the other hand, there are some things that
2975 :     the compiler does not do, therefore they are performed by
2976 :     @file{prims2x.fs}: The compiler does not optimize code away that stores
2977 :     a stack item to the place where it just came from (e.g., @code{over}).
2978 :    
2979 :     While programming a primitive is usually easy, there are a few cases
2980 :     where the programmer has to take the actions of the generator into
2981 :     account, most notably @code{?dup}, but also words that do not (always)
2982 :     fall through to NEXT.
2983 :    
2984 : anton 1.4 @node TOS Optimization, Produced code, Automatic Generation, Primitives
2985 : anton 1.3 @subsection TOS Optimization
2986 :    
2987 :     An important optimization for stack machine emulators, e.g., Forth
2988 :     engines, is keeping one or more of the top stack items in
2989 : anton 1.4 registers. If a word has the stack effect @var{in1}...@var{inx} @code{--}
2990 :     @var{out1}...@var{outy}, keeping the top @var{n} items in registers
2991 : anton 1.3 @itemize
2992 :     @item
2993 :     is better than keeping @var{n-1} items, if @var{x>=n} and @var{y>=n},
2994 :     due to fewer loads from and stores to the stack.
2995 :     @item is slower than keeping @var{n-1} items, if @var{x<>y} and @var{x<n} and
2996 :     @var{y<n}, due to additional moves between registers.
2997 :     @end itemize
2998 :    
2999 :     In particular, keeping one item in a register is never a disadvantage,
3000 :     if there are enough registers. Keeping two items in registers is a
3001 :     disadvantage for frequent words like @code{?branch}, constants,
3002 :     variables, literals and @code{i}. Therefore our generator only produces
3003 :     code that keeps zero or one items in registers. The generated C code
3004 :     covers both cases; the selection between these alternatives is made at
3005 :     C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
3006 :     code for @code{+} is just a simple variable name in the one-item case,
3007 :     otherwise it is a macro that expands into @code{sp[0]}. Note that the
3008 :     GNU C compiler tries to keep simple variables like @code{TOS} in
3009 :     registers, and it usually succeeds, if there are enough registers.
3010 :    
3011 :     The primitive generator performs the TOS optimization for the
3012 :     floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
3013 :     operations the benefit of this optimization is even larger:
3014 :     floating-point operations take quite long on most processors, but can be
3015 :     performed in parallel with other operations as long as their results are
3016 :     not used. If the FP-TOS is kept in a register, this works. If
3017 :     it is kept on the stack, i.e., in memory, the store into memory has to
3018 :     wait for the result of the floating-point operation, lengthening the
3019 :     execution time of the primitive considerably.
3020 :    
3021 :     The TOS optimization makes the automatic generation of primitives a
3022 :     bit more complicated. Just replacing all occurrences of @code{sp[0]} by
3023 :     @code{TOS} is not sufficient. There are some special cases to
3024 :     consider:
3025 :     @itemize
3026 :     @item In the case of @code{dup ( w -- w w )} the generator must not
3027 :     eliminate the store to the original location of the item on the stack,
3028 :     if the TOS optimization is turned on.
3029 : anton 1.4 @item Primitives with stack effects of the form @code{--}
3030 :     @var{out1}...@var{outy} must store the TOS to the stack at the start.
3031 :     Likewise, primitives with the stack effect @var{in1}...@var{inx} @code{--}
3032 : anton 1.3 must load the TOS from the stack at the end. But for the null stack
3033 :     effect @code{--} no stores or loads should be generated.
3034 :     @end itemize
3035 :    
3036 : anton 1.4 @node Produced code, , TOS Optimization, Primitives
3037 : anton 1.3 @subsection Produced code
3038 :    
3039 :     To see what assembly code is produced for the primitives on your machine
3040 :     with your compiler and your flag settings, type @code{make engine.s} and
3041 : anton 1.4 look at the resulting file @file{engine.s}.
3042 : anton 1.3
3043 : anton 1.17 @node System Architecture, Performance, Primitives, Internals
3044 : anton 1.3 @section System Architecture
3045 :    
3046 :     Our Forth system consists not only of primitives, but also of
3047 :     definitions written in Forth. Since the Forth compiler itself belongs
3048 :     to those definitions, it is not possible to start the system with the
3049 :     primitives and the Forth source alone. Therefore we provide the Forth
3050 :     code as an image file in nearly executable form. At the start of the
3051 :     system a C routine loads the image file into memory, sets up the
3052 :     memory (stacks etc.) according to information in the image file, and
3053 :     starts executing Forth code.
3054 :    
3055 :     The image file format is a compromise between the goals of making it
3056 :     easy to generate image files and making them portable. The easiest way
3057 :     to generate an image file is to just generate a memory dump. However,
3058 :     this kind of image file cannot be used on a different machine, or on
3059 :     the next version of the engine on the same machine, it even might not
3060 :     work with the same engine compiled by a different version of the C
3061 :     compiler. We would like to have as few versions of the image file as
3062 :     possible, because we do not want to distribute many versions of the
3063 :     same image file, and to make it easy for the users to use their image
3064 :     files on many machines. We currently need to create a different image
3065 :     file for machines with different cell sizes and different byte order
3066 : anton 1.17 (little- or big-endian)@footnote{We are considering adding information to the
3067 : anton 1.3 image file that enables the loader to change the byte order.}.
3068 :    
3069 :     Forth code that is going to end up in a portable image file has to
3070 : anton 1.4 comply to some restrictions: addresses have to be stored in memory with
3071 :     special words (@code{A!}, @code{A,}, etc.) in order to make the code
3072 :     relocatable. Cells, floats, etc., have to be stored at the natural
3073 :     alignment boundaries@footnote{E.g., store floats (8 bytes) at an address
3074 :     dividable by~8. This happens automatically in our system when you use
3075 :     the ANS Forth alignment words.}, in order to avoid alignment faults on
3076 :     machines with stricter alignment. The image file is produced by a
3077 :     metacompiler (@file{cross.fs}).
3078 : anton 1.3
3079 :     So, unlike the image file of Mitch Bradleys @code{cforth}, our image
3080 :     file is not directly executable, but has to undergo some manipulations
3081 :     during loading. Address relocation is performed at image load-time, not
3082 :     at run-time. The loader also has to replace tokens standing for
3083 :     primitive calls with the appropriate code-field addresses (or code
3084 :     addresses in the case of direct threading).
3085 : anton 1.4
3086 : anton 1.17 @node Performance, , System Architecture, Internals
3087 :     @section Performance
3088 :    
3089 :     On RISCs the Gforth engine is very close to optimal; i.e., it is usually
3090 :     impossible to write a significantly faster engine.
3091 :    
3092 :     On register-starved machines like the 386 architecture processors
3093 :     improvements are possible, because @code{gcc} does not utilize the
3094 :     registers as well as a human, even with explicit register declarations;
3095 :     e.g., Bernd Beuster wrote a Forth system fragment in assembly language
3096 :     and hand-tuned it for the 486; this system is 1.19 times faster on the
3097 :     Sieve benchmark on a 486DX2/66 than Gforth compiled with
3098 :     @code{gcc-2.6.3} with @code{-DFORCE_REG}.
3099 :    
3100 :     However, this potential advantage of assembly language implementations
3101 :     is not necessarily realized in complete Forth systems: We compared
3102 :     Gforth (compiled with @code{gcc-2.6.3} and @code{-DFORCE_REG}) with
3103 :     Win32Forth and LMI's NT Forth, two systems written in assembly, and with
3104 :     two systems written in C: PFE-0.9.11 (compiled with @code{gcc-2.6.3}
3105 :     with the default configuration for Linux: @code{-O2 -fomit-frame-pointer
3106 :     -DUSE_REGS}) and ThisForth Beta (compiled with gcc-2.6.3 -O3
3107 :     -fomit-frame-pointer). We benchmarked Gforth, PFE and ThisForth on a
3108 :     486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results for
3109 :     Win32Forth and NT Forth on a 486DX2/66 with similar memory performance
3110 :     under Windows NT.
3111 :    
3112 :     We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
3113 :     matrix multiplication come from the Stanford integer benchmarks and have
3114 :     been translated into Forth by Martin Fraeman; we used the versions
3115 :     included in the TILE Forth package; and a recursive Fibonacci number
3116 :     computation for benchmark calling performance. The following table shows
3117 :     the time taken for the benchmarks scaled by the time taken by Gforth (in
3118 :     other words, it shows the speedup factor that Gforth achieved over the
3119 :     other systems).
3120 :    
3121 :     @example
3122 :     relative Win32- NT This-
3123 :     time Gforth Forth Forth PFE Forth
3124 :     sieve 1.00 1.30 1.07 1.67 2.98
3125 :     bubble 1.00 1.30 1.40 1.66
3126 :     matmul 1.00 1.40 1.29 2.24
3127 :     fib 1.00 1.44 1.26 1.82 2.82
3128 :     @end example
3129 :    
3130 :     You may find the good performance of Gforth compared with the systems
3131 :     written in assembly language quite surprising. One important reason for
3132 :     the disappointing performance of these systems is probably that they are
3133 :     not written optimally for the 486 (e.g., they use the @code{lods}
3134 :     instruction). In addition, Win32Forth uses a comfortable, but costly
3135 :     method for relocating the Forth image: like @code{cforth}, it computes
3136 :     the actual addresses at run time, resulting in two address computations
3137 :     per NEXT (@pxref{System Architecture}).
3138 :    
3139 :     The speedup of Gforth over PFE and ThisForth can be easily explained
3140 :     with the self-imposed restriction to standard C (although the measured
3141 :     implementation of PFE uses a GNU C extension: global register
3142 :     variables), which makes efficient threading impossible. Moreover,
3143 :     current C compilers have a hard time optimizing other aspects of the
3144 :     ThisForth source.
3145 :    
3146 :     Note that the performance of Gforth on 386 architecture processors
3147 :     varies widely with the version of @code{gcc} used. E.g., @code{gcc-2.5.8}
3148 :     failed to allocate any of the virtual machine registers into real
3149 :     machine registers by itself and would not work correctly with explicit
3150 :     register declarations, giving a 1.3 times slower engine (on a 486DX2/66
3151 :     running the Sieve) than the one measured above.
3152 :    
3153 : anton 1.4 @node Bugs, Pedigree, Internals, Top
3154 :     @chapter Bugs
3155 :    
3156 : anton 1.17 Known bugs are described in the file BUGS in the Gforth distribution.
3157 :    
3158 :     If you find a bug, please send a bug report to !!. A bug report should
3159 :     describe the Gforth version used (it is announced at the start of an
3160 :     interactive Gforth session), the machine and operating system (on Unix
3161 :     systems you can use @code{uname -a} to produce this information), the
3162 :     installation options (!! a way to find them out), and a complete list of
3163 :     changes you (or your installer) have made to the Gforth sources (if
3164 :     any); it should contain a program (or a sequence of keyboard commands)
3165 :     that reproduces the bug and a description of what you think constitutes
3166 :     the buggy behaviour.
3167 :    
3168 :     For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
3169 :     to Report Bugs, gcc.info, GNU C Manual}.
3170 :    
3171 :    
3172 : anton 1.4 @node Pedigree, Word Index, Bugs, Top
3173 :     @chapter Pedigree
3174 :    
3175 : anton 1.17 Gforth descends from BigForth (1993) and fig-Forth. Gforth and PFE (by
3176 :     Dirk Zoller) will cross-fertilize each other. Of course, a significant part of the design of Gforth was prescribed by ANS Forth.
3177 :    
3178 :     Bernd Paysan wrote BigForth, a child of VolksForth.
3179 :    
3180 :     VolksForth descends from F83. !! Authors? When?
3181 :    
3182 :     Laxen and Perry wrote F83 as a model implementation of the
3183 :     Forth-83 standard. !! Pedigree? When?
3184 :    
3185 :     A team led by Bill Ragsdale implemented fig-Forth on many processors in
3186 :     1979. Dean Sanderson and Bill Ragsdale developed the original
3187 :     implementation of fig-Forth based on microForth.
3188 :    
3189 :     !! microForth pedigree
3190 :    
3191 :     A part of the information in this section comes from @cite{The Evolution
3192 :     of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
3193 :     H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
3194 :     Notices 28(3), 1993. You can find more historical and genealogical
3195 :     information about Forth there.
3196 :    
3197 : anton 1.4 @node Word Index, Node Index, Pedigree, Top
3198 :     @chapter Word Index
3199 :    
3200 : anton 1.17 This index is as incomplete as the manual.
3201 :    
3202 :     @printindex fn
3203 :    
3204 : anton 1.4 @node Node Index, , Word Index, Top
3205 :     @chapter Node Index
3206 : anton 1.17
3207 :     This index is even less complete than the manual.
3208 : anton 1.1
3209 :     @contents
3210 :     @bye
3211 :    

CVS Admin

Powered by ViewCVS 1.0-dev
(Powered by ViewCVS)

ViewCVS and CVS Help