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