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