Annotation of gforth/doc/gforth.ds, revision 1.28
1.1 anton 1: \input texinfo @c -*-texinfo-*-
2: @comment The source is gforth.ds, from which gforth.texi is generated
1.28 ! crook 3:
1.21 crook 4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
1.28 ! crook 5: @comment 1. x-ref all ambiguous or implementation-defined features?
! 6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
! 7: @comment 3. words in miscellaneous section need a home.
! 8: @comment 4. search for TODO for other minor and major works required.
! 9: @comment 5. [rats] change all @var to @i in Forth source so that info
! 10: @comment file looks decent.
! 11:
1.1 anton 12: @comment %**start of header (This is for running Texinfo on a region.)
13: @setfilename gforth.info
14: @settitle Gforth Manual
15: @dircategory GNU programming tools
16: @direntry
17: * Gforth: (gforth). A fast interpreter for the Forth language.
18: @end direntry
19: @comment @setchapternewpage odd
1.12 anton 20: @macro progstyle {}
21: Programming style note:
1.3 anton 22: @end macro
1.1 anton 23: @comment %**end of header (This is for running Texinfo on a region.)
24:
1.10 anton 25: @include version.texi
26:
1.1 anton 27: @ifinfo
1.11 anton 28: This file documents Gforth @value{VERSION}
1.1 anton 29:
1.26 crook 30: Copyright @copyright{} 1995-1999 Free Software Foundation, Inc.
1.1 anton 31:
32: Permission is granted to make and distribute verbatim copies of
33: this manual provided the copyright notice and this permission notice
34: are preserved on all copies.
35:
36: @ignore
37: Permission is granted to process this file through TeX and print the
38: results, provided the printed document carries a copying permission
39: notice identical to this one except for the removal of this paragraph
40: (this paragraph not being relevant to the printed manual).
41:
42: @end ignore
43: Permission is granted to copy and distribute modified versions of this
44: manual under the conditions for verbatim copying, provided also that the
45: sections entitled "Distribution" and "General Public License" are
46: included exactly as in the original, and provided that the entire
47: resulting derived work is distributed under the terms of a permission
48: notice identical to this one.
49:
50: Permission is granted to copy and distribute translations of this manual
51: into another language, under the above conditions for modified versions,
52: except that the sections entitled "Distribution" and "General Public
53: License" may be included in a translation approved by the author instead
54: of in the original English.
55: @end ifinfo
56:
57: @finalout
58: @titlepage
59: @sp 10
60: @center @titlefont{Gforth Manual}
61: @sp 2
1.11 anton 62: @center for version @value{VERSION}
1.1 anton 63: @sp 2
64: @center Anton Ertl
1.6 pazsan 65: @center Bernd Paysan
1.5 anton 66: @center Jens Wilke
1.23 crook 67: @center Neal Crook
1.1 anton 68: @sp 3
1.28 ! crook 69: @center This manual is permanently under construction and was last updated on 16-Apr-1999
1.1 anton 70:
71: @comment The following two commands start the copyright page.
72: @page
73: @vskip 0pt plus 1filll
1.13 pazsan 74: Copyright @copyright{} 1995--1998 Free Software Foundation, Inc.
1.1 anton 75:
76: @comment !! Published by ... or You can get a copy of this manual ...
77:
78: Permission is granted to make and distribute verbatim copies of
79: this manual provided the copyright notice and this permission notice
80: are preserved on all copies.
81:
82: Permission is granted to copy and distribute modified versions of this
83: manual under the conditions for verbatim copying, provided also that the
84: sections entitled "Distribution" and "General Public License" are
85: included exactly as in the original, and provided that the entire
86: resulting derived work is distributed under the terms of a permission
87: notice identical to this one.
88:
89: Permission is granted to copy and distribute translations of this manual
90: into another language, under the above conditions for modified versions,
91: except that the sections entitled "Distribution" and "General Public
92: License" may be included in a translation approved by the author instead
93: of in the original English.
94: @end titlepage
95:
96:
97: @node Top, License, (dir), (dir)
98: @ifinfo
99: Gforth is a free implementation of ANS Forth available on many
1.11 anton 100: personal machines. This manual corresponds to version @value{VERSION}.
1.1 anton 101: @end ifinfo
102:
103: @menu
1.21 crook 104: * License:: The GPL
1.26 crook 105: * Goals:: About the Gforth Project
1.21 crook 106: * Introduction:: An introduction to ANS Forth
1.28 ! crook 107: * Gforth Environment:: Starting (and exiting) Gforth
1.1 anton 108: * Words:: Forth words available in Gforth
1.24 anton 109: * Error messages:: How to interpret them
1.1 anton 110: * Tools:: Programming tools
111: * ANS conformance:: Implementation-defined options etc.
112: * Model:: The abstract machine of Gforth
113: * Integrating Gforth:: Forth as scripting language for applications
114: * Emacs and Gforth:: The Gforth Mode
115: * Image Files:: @code{.fi} files contain compiled code
116: * Engine:: The inner interpreter and the primitives
1.24 anton 117: * Binding to System Library::
1.13 pazsan 118: * Cross Compiler:: The Cross Compiler
1.1 anton 119: * Bugs:: How to report them
120: * Origin:: Authors and ancestors of Gforth
1.21 crook 121: * Forth-related information:: Books and places to look on the WWW
1.1 anton 122: * Word Index:: An item for each Forth word
123: * Concept Index:: A menu covering many topics
1.12 anton 124:
1.24 anton 125: @detailmenu --- The Detailed Node Listing ---
1.12 anton 126:
1.26 crook 127: Goals of Gforth
128:
129: * Gforth Extensions Sinful?::
130:
1.24 anton 131: An Introduction to ANS Forth
132:
133: * Introducing the Text Interpreter::
134: * Stacks and Postfix notation::
135: * Your first definition::
136: * How does that work?::
137: * Forth is written in Forth::
138: * Review - elements of a Forth system::
139: * Exercises::
140:
1.28 ! crook 141:
! 142: Gforth Environment
! 143:
! 144: * Invoking Gforth::
! 145: * Leaving Gforth::
! 146: * Command-line editing::
! 147: * Upper and lower case::
! 148: * Environment variables::
! 149: * Gforth Files::
! 150:
! 151:
1.12 anton 152: Forth Words
153:
154: * Notation::
1.21 crook 155: * Comments::
156: * Boolean Flags::
1.12 anton 157: * Arithmetic::
158: * Stack Manipulation::
159: * Memory::
160: * Control Structures::
161: * Defining Words::
1.21 crook 162: * The Text Interpreter::
1.12 anton 163: * Tokens for Words::
1.21 crook 164: * Word Lists::
165: * Environmental Queries::
1.12 anton 166: * Files::
167: * Blocks::
168: * Other I/O::
169: * Programming Tools::
170: * Assembler and Code Words::
171: * Threading Words::
1.26 crook 172: * Locals::
173: * Structures::
174: * Object-oriented Forth::
1.21 crook 175: * Passing Commands to the OS::
176: * Miscellaneous Words::
1.12 anton 177:
178: Arithmetic
179:
180: * Single precision::
181: * Bitwise operations::
1.21 crook 182: * Double precision:: Double-cell integer arithmetic
183: * Numeric comparison::
1.12 anton 184: * Mixed precision:: operations with single and double-cell integers
185: * Floating Point::
186:
187: Stack Manipulation
188:
189: * Data stack::
190: * Floating point stack::
191: * Return stack::
192: * Locals stack::
193: * Stack pointer manipulation::
194:
195: Memory
196:
1.27 crook 197: * Reserving Data Space::
1.12 anton 198: * Memory Access::
1.27 crook 199: * Address Arithmetic::
200: * Memory Blocks::
201: * Dynamic Allocation::
1.12 anton 202:
203: Control Structures
204:
205: * Selection::
206: * Simple Loops::
207: * Counted Loops::
208: * Arbitrary control structures::
209: * Calls and returns::
210: * Exception Handling::
211:
212: Defining Words
213:
214: * Simple Defining Words::
215: * Colon Definitions::
216: * User-defined Defining Words::
217: * Supplying names::
218: * Interpretation and Compilation Semantics::
219:
1.21 crook 220: The Text Interpreter
221:
222: * Number Conversion::
223: * Interpret/Compile states::
224: * Literals::
225: * Interpreter Directives::
1.27 crook 226: * Input Sources::
1.21 crook 227:
1.26 crook 228: Word Lists
229:
230: * Why use word lists?::
231: * Word list examples::
232:
233: Files
234:
235: * Forth source files::
236: * General files::
237: * Search Paths::
238: * Forth Search Paths::
239: * General Search Paths::
240:
241: Other I/O
242:
243: * Simple numeric output::
244: * Formatted numeric output::
245: * String Formats::
246: * Displaying characters and strings::
247: * Input::
248:
249: Programming Tools
250:
251: * Debugging:: Simple and quick.
252: * Assertions:: Making your programs self-checking.
253: * Singlestep Debugger:: Executing your program word by word.
254:
255: Locals
256:
257: * Gforth locals::
258: * ANS Forth locals::
259:
260: Gforth locals
261:
262: * Where are locals visible by name?::
263: * How long do locals live?::
264: * Programming Style::
265: * Implementation::
266:
1.12 anton 267: Structures
268:
269: * Why explicit structure support?::
270: * Structure Usage::
271: * Structure Naming Convention::
272: * Structure Implementation::
273: * Structure Glossary::
274:
275: Object-oriented Forth
276:
1.24 anton 277: * Why object-oriented programming?::
278: * Object-Oriented Terminology::
279: * Objects::
280: * OOF::
281: * Mini-OOF::
1.23 crook 282: * Comparison with other object models::
1.12 anton 283:
1.24 anton 284: The @file{objects.fs} model
1.12 anton 285:
286: * Properties of the Objects model::
287: * Basic Objects Usage::
1.23 crook 288: * The Objects base class::
1.12 anton 289: * Creating objects::
290: * Object-Oriented Programming Style::
291: * Class Binding::
292: * Method conveniences::
293: * Classes and Scoping::
294: * Object Interfaces::
295: * Objects Implementation::
296: * Objects Glossary::
297:
1.24 anton 298: The @file{oof.fs} model
1.12 anton 299:
300: * Properties of the OOF model::
301: * Basic OOF Usage::
1.23 crook 302: * The OOF base class::
1.12 anton 303: * Class Declaration::
304: * Class Implementation::
305:
1.24 anton 306: The @file{mini-oof.fs} model
1.23 crook 307:
308: * Basic Mini-OOF Usage::
309: * Mini-OOF Example::
310: * Mini-OOF Implementation::
311:
1.12 anton 312: Tools
313:
314: * ANS Report:: Report the words used, sorted by wordset.
315:
316: ANS conformance
317:
318: * The Core Words::
319: * The optional Block word set::
320: * The optional Double Number word set::
321: * The optional Exception word set::
322: * The optional Facility word set::
323: * The optional File-Access word set::
324: * The optional Floating-Point word set::
325: * The optional Locals word set::
326: * The optional Memory-Allocation word set::
327: * The optional Programming-Tools word set::
328: * The optional Search-Order word set::
329:
330: The Core Words
331:
332: * core-idef:: Implementation Defined Options
333: * core-ambcond:: Ambiguous Conditions
334: * core-other:: Other System Documentation
335:
336: The optional Block word set
337:
338: * block-idef:: Implementation Defined Options
339: * block-ambcond:: Ambiguous Conditions
340: * block-other:: Other System Documentation
341:
342: The optional Double Number word set
343:
344: * double-ambcond:: Ambiguous Conditions
345:
346: The optional Exception word set
347:
348: * exception-idef:: Implementation Defined Options
349:
350: The optional Facility word set
351:
352: * facility-idef:: Implementation Defined Options
353: * facility-ambcond:: Ambiguous Conditions
354:
355: The optional File-Access word set
356:
357: * file-idef:: Implementation Defined Options
358: * file-ambcond:: Ambiguous Conditions
359:
360: The optional Floating-Point word set
361:
362: * floating-idef:: Implementation Defined Options
363: * floating-ambcond:: Ambiguous Conditions
364:
365: The optional Locals word set
366:
367: * locals-idef:: Implementation Defined Options
368: * locals-ambcond:: Ambiguous Conditions
369:
370: The optional Memory-Allocation word set
371:
372: * memory-idef:: Implementation Defined Options
373:
374: The optional Programming-Tools word set
375:
376: * programming-idef:: Implementation Defined Options
377: * programming-ambcond:: Ambiguous Conditions
378:
379: The optional Search-Order word set
380:
381: * search-idef:: Implementation Defined Options
382: * search-ambcond:: Ambiguous Conditions
383:
384: Image Files
385:
1.24 anton 386: * Image Licensing Issues:: Distribution terms for images.
387: * Image File Background:: Why have image files?
388: * Non-Relocatable Image Files:: don't always work.
389: * Data-Relocatable Image Files:: are better.
1.12 anton 390: * Fully Relocatable Image Files:: better yet.
1.24 anton 391: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
392: * Running Image Files:: @code{gforth -i @var{file}} or @var{file}.
393: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 394:
395: Fully Relocatable Image Files
396:
1.27 crook 397: * gforthmi:: The normal way
1.12 anton 398: * cross.fs:: The hard way
399:
400: Engine
401:
402: * Portability::
403: * Threading::
404: * Primitives::
405: * Performance::
406:
407: Threading
408:
409: * Scheduling::
410: * Direct or Indirect Threaded?::
411: * DOES>::
412:
413: Primitives
414:
415: * Automatic Generation::
416: * TOS Optimization::
417: * Produced code::
1.13 pazsan 418:
419: Cross Compiler
420:
421: * Using the Cross Compiler::
422: * How the Cross Compiler Works::
423:
1.24 anton 424: Other Forth-related information
1.21 crook 425:
426: * Internet resources::
427: * Books::
428: * The Forth Interest Group::
429: * Conferences::
430:
1.24 anton 431: @end detailmenu
1.1 anton 432: @end menu
433:
1.26 crook 434: @node License, Goals, Top, Top
1.1 anton 435: @unnumbered GNU GENERAL PUBLIC LICENSE
436: @center Version 2, June 1991
437:
438: @display
439: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
440: 675 Mass Ave, Cambridge, MA 02139, USA
441:
442: Everyone is permitted to copy and distribute verbatim copies
443: of this license document, but changing it is not allowed.
444: @end display
445:
446: @unnumberedsec Preamble
447:
448: The licenses for most software are designed to take away your
449: freedom to share and change it. By contrast, the GNU General Public
450: License is intended to guarantee your freedom to share and change free
451: software---to make sure the software is free for all its users. This
452: General Public License applies to most of the Free Software
453: Foundation's software and to any other program whose authors commit to
454: using it. (Some other Free Software Foundation software is covered by
455: the GNU Library General Public License instead.) You can apply it to
456: your programs, too.
457:
458: When we speak of free software, we are referring to freedom, not
459: price. Our General Public Licenses are designed to make sure that you
460: have the freedom to distribute copies of free software (and charge for
461: this service if you wish), that you receive source code or can get it
462: if you want it, that you can change the software or use pieces of it
463: in new free programs; and that you know you can do these things.
464:
465: To protect your rights, we need to make restrictions that forbid
466: anyone to deny you these rights or to ask you to surrender the rights.
467: These restrictions translate to certain responsibilities for you if you
468: distribute copies of the software, or if you modify it.
469:
470: For example, if you distribute copies of such a program, whether
471: gratis or for a fee, you must give the recipients all the rights that
472: you have. You must make sure that they, too, receive or can get the
473: source code. And you must show them these terms so they know their
474: rights.
475:
476: We protect your rights with two steps: (1) copyright the software, and
477: (2) offer you this license which gives you legal permission to copy,
478: distribute and/or modify the software.
479:
480: Also, for each author's protection and ours, we want to make certain
481: that everyone understands that there is no warranty for this free
482: software. If the software is modified by someone else and passed on, we
483: want its recipients to know that what they have is not the original, so
484: that any problems introduced by others will not reflect on the original
485: authors' reputations.
486:
487: Finally, any free program is threatened constantly by software
488: patents. We wish to avoid the danger that redistributors of a free
489: program will individually obtain patent licenses, in effect making the
490: program proprietary. To prevent this, we have made it clear that any
491: patent must be licensed for everyone's free use or not licensed at all.
492:
493: The precise terms and conditions for copying, distribution and
494: modification follow.
495:
496: @iftex
497: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
498: @end iftex
499: @ifinfo
500: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
501: @end ifinfo
502:
503: @enumerate 0
504: @item
505: This License applies to any program or other work which contains
506: a notice placed by the copyright holder saying it may be distributed
507: under the terms of this General Public License. The ``Program'', below,
508: refers to any such program or work, and a ``work based on the Program''
509: means either the Program or any derivative work under copyright law:
510: that is to say, a work containing the Program or a portion of it,
511: either verbatim or with modifications and/or translated into another
512: language. (Hereinafter, translation is included without limitation in
513: the term ``modification''.) Each licensee is addressed as ``you''.
514:
515: Activities other than copying, distribution and modification are not
516: covered by this License; they are outside its scope. The act of
517: running the Program is not restricted, and the output from the Program
518: is covered only if its contents constitute a work based on the
519: Program (independent of having been made by running the Program).
520: Whether that is true depends on what the Program does.
521:
522: @item
523: You may copy and distribute verbatim copies of the Program's
524: source code as you receive it, in any medium, provided that you
525: conspicuously and appropriately publish on each copy an appropriate
526: copyright notice and disclaimer of warranty; keep intact all the
527: notices that refer to this License and to the absence of any warranty;
528: and give any other recipients of the Program a copy of this License
529: along with the Program.
530:
531: You may charge a fee for the physical act of transferring a copy, and
532: you may at your option offer warranty protection in exchange for a fee.
533:
534: @item
535: You may modify your copy or copies of the Program or any portion
536: of it, thus forming a work based on the Program, and copy and
537: distribute such modifications or work under the terms of Section 1
538: above, provided that you also meet all of these conditions:
539:
540: @enumerate a
541: @item
542: You must cause the modified files to carry prominent notices
543: stating that you changed the files and the date of any change.
544:
545: @item
546: You must cause any work that you distribute or publish, that in
547: whole or in part contains or is derived from the Program or any
548: part thereof, to be licensed as a whole at no charge to all third
549: parties under the terms of this License.
550:
551: @item
552: If the modified program normally reads commands interactively
553: when run, you must cause it, when started running for such
554: interactive use in the most ordinary way, to print or display an
555: announcement including an appropriate copyright notice and a
556: notice that there is no warranty (or else, saying that you provide
557: a warranty) and that users may redistribute the program under
558: these conditions, and telling the user how to view a copy of this
559: License. (Exception: if the Program itself is interactive but
560: does not normally print such an announcement, your work based on
561: the Program is not required to print an announcement.)
562: @end enumerate
563:
564: These requirements apply to the modified work as a whole. If
565: identifiable sections of that work are not derived from the Program,
566: and can be reasonably considered independent and separate works in
567: themselves, then this License, and its terms, do not apply to those
568: sections when you distribute them as separate works. But when you
569: distribute the same sections as part of a whole which is a work based
570: on the Program, the distribution of the whole must be on the terms of
571: this License, whose permissions for other licensees extend to the
572: entire whole, and thus to each and every part regardless of who wrote it.
573:
574: Thus, it is not the intent of this section to claim rights or contest
575: your rights to work written entirely by you; rather, the intent is to
576: exercise the right to control the distribution of derivative or
577: collective works based on the Program.
578:
579: In addition, mere aggregation of another work not based on the Program
580: with the Program (or with a work based on the Program) on a volume of
581: a storage or distribution medium does not bring the other work under
582: the scope of this License.
583:
584: @item
585: You may copy and distribute the Program (or a work based on it,
586: under Section 2) in object code or executable form under the terms of
587: Sections 1 and 2 above provided that you also do one of the following:
588:
589: @enumerate a
590: @item
591: Accompany it with the complete corresponding machine-readable
592: source code, which must be distributed under the terms of Sections
593: 1 and 2 above on a medium customarily used for software interchange; or,
594:
595: @item
596: Accompany it with a written offer, valid for at least three
597: years, to give any third party, for a charge no more than your
598: cost of physically performing source distribution, a complete
599: machine-readable copy of the corresponding source code, to be
600: distributed under the terms of Sections 1 and 2 above on a medium
601: customarily used for software interchange; or,
602:
603: @item
604: Accompany it with the information you received as to the offer
605: to distribute corresponding source code. (This alternative is
606: allowed only for noncommercial distribution and only if you
607: received the program in object code or executable form with such
608: an offer, in accord with Subsection b above.)
609: @end enumerate
610:
611: The source code for a work means the preferred form of the work for
612: making modifications to it. For an executable work, complete source
613: code means all the source code for all modules it contains, plus any
614: associated interface definition files, plus the scripts used to
615: control compilation and installation of the executable. However, as a
616: special exception, the source code distributed need not include
617: anything that is normally distributed (in either source or binary
618: form) with the major components (compiler, kernel, and so on) of the
619: operating system on which the executable runs, unless that component
620: itself accompanies the executable.
621:
622: If distribution of executable or object code is made by offering
623: access to copy from a designated place, then offering equivalent
624: access to copy the source code from the same place counts as
625: distribution of the source code, even though third parties are not
626: compelled to copy the source along with the object code.
627:
628: @item
629: You may not copy, modify, sublicense, or distribute the Program
630: except as expressly provided under this License. Any attempt
631: otherwise to copy, modify, sublicense or distribute the Program is
632: void, and will automatically terminate your rights under this License.
633: However, parties who have received copies, or rights, from you under
634: this License will not have their licenses terminated so long as such
635: parties remain in full compliance.
636:
637: @item
638: You are not required to accept this License, since you have not
639: signed it. However, nothing else grants you permission to modify or
640: distribute the Program or its derivative works. These actions are
641: prohibited by law if you do not accept this License. Therefore, by
642: modifying or distributing the Program (or any work based on the
643: Program), you indicate your acceptance of this License to do so, and
644: all its terms and conditions for copying, distributing or modifying
645: the Program or works based on it.
646:
647: @item
648: Each time you redistribute the Program (or any work based on the
649: Program), the recipient automatically receives a license from the
650: original licensor to copy, distribute or modify the Program subject to
651: these terms and conditions. You may not impose any further
652: restrictions on the recipients' exercise of the rights granted herein.
653: You are not responsible for enforcing compliance by third parties to
654: this License.
655:
656: @item
657: If, as a consequence of a court judgment or allegation of patent
658: infringement or for any other reason (not limited to patent issues),
659: conditions are imposed on you (whether by court order, agreement or
660: otherwise) that contradict the conditions of this License, they do not
661: excuse you from the conditions of this License. If you cannot
662: distribute so as to satisfy simultaneously your obligations under this
663: License and any other pertinent obligations, then as a consequence you
664: may not distribute the Program at all. For example, if a patent
665: license would not permit royalty-free redistribution of the Program by
666: all those who receive copies directly or indirectly through you, then
667: the only way you could satisfy both it and this License would be to
668: refrain entirely from distribution of the Program.
669:
670: If any portion of this section is held invalid or unenforceable under
671: any particular circumstance, the balance of the section is intended to
672: apply and the section as a whole is intended to apply in other
673: circumstances.
674:
675: It is not the purpose of this section to induce you to infringe any
676: patents or other property right claims or to contest validity of any
677: such claims; this section has the sole purpose of protecting the
678: integrity of the free software distribution system, which is
679: implemented by public license practices. Many people have made
680: generous contributions to the wide range of software distributed
681: through that system in reliance on consistent application of that
682: system; it is up to the author/donor to decide if he or she is willing
683: to distribute software through any other system and a licensee cannot
684: impose that choice.
685:
686: This section is intended to make thoroughly clear what is believed to
687: be a consequence of the rest of this License.
688:
689: @item
690: If the distribution and/or use of the Program is restricted in
691: certain countries either by patents or by copyrighted interfaces, the
692: original copyright holder who places the Program under this License
693: may add an explicit geographical distribution limitation excluding
694: those countries, so that distribution is permitted only in or among
695: countries not thus excluded. In such case, this License incorporates
696: the limitation as if written in the body of this License.
697:
698: @item
699: The Free Software Foundation may publish revised and/or new versions
700: of the General Public License from time to time. Such new versions will
701: be similar in spirit to the present version, but may differ in detail to
702: address new problems or concerns.
703:
704: Each version is given a distinguishing version number. If the Program
705: specifies a version number of this License which applies to it and ``any
706: later version'', you have the option of following the terms and conditions
707: either of that version or of any later version published by the Free
708: Software Foundation. If the Program does not specify a version number of
709: this License, you may choose any version ever published by the Free Software
710: Foundation.
711:
712: @item
713: If you wish to incorporate parts of the Program into other free
714: programs whose distribution conditions are different, write to the author
715: to ask for permission. For software which is copyrighted by the Free
716: Software Foundation, write to the Free Software Foundation; we sometimes
717: make exceptions for this. Our decision will be guided by the two goals
718: of preserving the free status of all derivatives of our free software and
719: of promoting the sharing and reuse of software generally.
720:
721: @iftex
722: @heading NO WARRANTY
723: @end iftex
724: @ifinfo
725: @center NO WARRANTY
726: @end ifinfo
727:
728: @item
729: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
730: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
731: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
732: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
733: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
734: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
735: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
736: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
737: REPAIR OR CORRECTION.
738:
739: @item
740: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
741: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
742: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
743: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
744: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
745: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
746: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
747: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
748: POSSIBILITY OF SUCH DAMAGES.
749: @end enumerate
750:
751: @iftex
752: @heading END OF TERMS AND CONDITIONS
753: @end iftex
754: @ifinfo
755: @center END OF TERMS AND CONDITIONS
756: @end ifinfo
757:
758: @page
759: @unnumberedsec How to Apply These Terms to Your New Programs
760:
761: If you develop a new program, and you want it to be of the greatest
762: possible use to the public, the best way to achieve this is to make it
763: free software which everyone can redistribute and change under these terms.
764:
765: To do so, attach the following notices to the program. It is safest
766: to attach them to the start of each source file to most effectively
767: convey the exclusion of warranty; and each file should have at least
768: the ``copyright'' line and a pointer to where the full notice is found.
769:
770: @smallexample
771: @var{one line to give the program's name and a brief idea of what it does.}
772: Copyright (C) 19@var{yy} @var{name of author}
773:
774: This program is free software; you can redistribute it and/or modify
775: it under the terms of the GNU General Public License as published by
776: the Free Software Foundation; either version 2 of the License, or
777: (at your option) any later version.
778:
779: This program is distributed in the hope that it will be useful,
780: but WITHOUT ANY WARRANTY; without even the implied warranty of
781: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
782: GNU General Public License for more details.
783:
784: You should have received a copy of the GNU General Public License
785: along with this program; if not, write to the Free Software
786: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
787: @end smallexample
788:
789: Also add information on how to contact you by electronic and paper mail.
790:
791: If the program is interactive, make it output a short notice like this
792: when it starts in an interactive mode:
793:
794: @smallexample
795: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
796: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
797: type `show w'.
798: This is free software, and you are welcome to redistribute it
799: under certain conditions; type `show c' for details.
800: @end smallexample
801:
802: The hypothetical commands @samp{show w} and @samp{show c} should show
803: the appropriate parts of the General Public License. Of course, the
804: commands you use may be called something other than @samp{show w} and
805: @samp{show c}; they could even be mouse-clicks or menu items---whatever
806: suits your program.
807:
808: You should also get your employer (if you work as a programmer) or your
809: school, if any, to sign a ``copyright disclaimer'' for the program, if
810: necessary. Here is a sample; alter the names:
811:
812: @smallexample
813: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
814: `Gnomovision' (which makes passes at compilers) written by James Hacker.
815:
816: @var{signature of Ty Coon}, 1 April 1989
817: Ty Coon, President of Vice
818: @end smallexample
819:
820: This General Public License does not permit incorporating your program into
821: proprietary programs. If your program is a subroutine library, you may
822: consider it more useful to permit linking proprietary applications with the
823: library. If this is what you want to do, use the GNU Library General
824: Public License instead of this License.
825:
826: @iftex
827: @unnumbered Preface
828: @cindex Preface
1.21 crook 829: This manual documents Gforth. Some introductory material is provided for
830: readers who are unfamiliar with Forth or who are migrating to Gforth
831: from other Forth compilers. However, this manual is primarily a
832: reference manual.
1.1 anton 833: @end iftex
834:
1.28 ! crook 835: @comment TODO much more blurb here.
1.26 crook 836:
837: @c ******************************************************************
838: @node Goals, Introduction, License, Top
839: @comment node-name, next, previous, up
840: @chapter Goals of Gforth
841: @cindex goals of the Gforth project
842: The goal of the Gforth Project is to develop a standard model for
843: ANS Forth. This can be split into several subgoals:
844:
845: @itemize @bullet
846: @item
847: Gforth should conform to the ANS Forth Standard.
848: @item
849: It should be a model, i.e. it should define all the
850: implementation-dependent things.
851: @item
852: It should become standard, i.e. widely accepted and used. This goal
853: is the most difficult one.
854: @end itemize
855:
856: To achieve these goals Gforth should be
857: @itemize @bullet
858: @item
859: Similar to previous models (fig-Forth, F83)
860: @item
861: Powerful. It should provide for all the things that are considered
862: necessary today and even some that are not yet considered necessary.
863: @item
864: Efficient. It should not get the reputation of being exceptionally
865: slow.
866: @item
867: Free.
868: @item
869: Available on many machines/easy to port.
870: @end itemize
871:
872: Have we achieved these goals? Gforth conforms to the ANS Forth
873: standard. It may be considered a model, but we have not yet documented
874: which parts of the model are stable and which parts we are likely to
875: change. It certainly has not yet become a de facto standard, but it
876: appears to be quite popular. It has some similarities to and some
877: differences from previous models. It has some powerful features, but not
878: yet everything that we envisioned. We certainly have achieved our
879: execution speed goals (@pxref{Performance}). It is free and available
880: on many machines.
881:
882: @menu
883: * Gforth Extensions Sinful?::
884: @end menu
885:
886: @node Gforth Extensions Sinful?, , Goals, Goals
887: @comment node-name, next, previous, up
888: @section Is it a Sin to use Gforth Extensions?
889: @cindex Gforth extensions
890:
891: If you've been paying attention, you will have realised that there is an
892: ANS (American National Standard) for Forth. As you read through the rest
893: of this manual, you will see documentation for @var{Standard} words, and
894: documentation for some appealing Gforth @var{extensions}. You might ask
895: yourself the question: @var{``Given that there is a standard, would I be
896: committing a sin to use (non-Standard) Gforth extensions?''}
897:
898: The answer to that question is somewhat pragmatic and somewhat
899: philosophical. Consider these points:
900:
901: @itemize @bullet
902: @item
903: A number of the Gforth extensions can be implemented in ANS Forth using
904: files provided in the @file{compat/} directory. These are mentioned in
905: the text in passing.
906: @item
907: Forth has a rich historical precedent for programmers taking advantage
908: of implementation-dependent features of their tools (for example,
909: relying on a knowledge of the dictionary structure). Sometimes these
910: techniques are necessary to extract every last bit of performance from
911: the hardware, sometimes they are just a programming shorthand.
912: @item
913: The best way to break the rules is to know what the rules are. To learn
914: the rules, there is no substitute for studying the text of the Standard
915: itself. In particular, Appendix A of the Standard (@var{Rationale})
916: provides a valuable insight into the thought processes of the technical
917: committee.
918: @item
919: The best reason to break a rule is because you have to; because it's
920: more productive to do that, because it makes your code run fast enough
921: or because you can see no Standard way to achieve what you want to
922: achieve.
923: @end itemize
924:
925: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
926: analyse your program and determine what non-Standard definitions it
927: relies upon.
928:
929: @c ******************************************************************
1.28 ! crook 930: @node Introduction, Gforth Environment, Goals, Top
1.21 crook 931: @comment node-name, next, previous, up
932: @chapter An Introduction to ANS Forth
933: @cindex Forth - an introduction
934:
935: The primary purpose of this manual is to document Gforth. However, since
936: Forth is not a widely-known language and there is a lack of up-to-date
937: teaching material, it seems worthwhile to provide some introductory
938: material. @xref{Forth-related information} for other sources of Forth-related
939: information.
940:
1.26 crook 941: The examples in this section should work on any ANS Forth; the
942: output shown was produced using Gforth. Each example attempts to
1.21 crook 943: reproduce the exact output that Gforth produces. If you try out the
944: examples (and you should), what you should type is shown @kbd{like this}
945: and Gforth's response is shown @code{like this}. The single exception is
946: that, where the example shows @kbd{<return>} it means that you should
1.26 crook 947: press the ``carriage return'' key. Unfortunately, some output formats for
1.21 crook 948: this manual cannot show the difference between @kbd{this} and
949: @code{this} which will make trying out the examples harder (but not
950: impossible).
951:
952: Forth is an unusual language. It provides an interactive development
953: environment which includes both an interpreter and compiler. Forth
954: programming style encourages you to break a problem down into many
955: @cindex factoring
956: small fragments (@var{factoring}), and then to develop and test each
957: fragment interactively. Forth advocates assert that breaking the
958: edit-compile-test cycle used by conventional programming languages can
959: lead to great productivity improvements.
960:
961: @menu
962: * Introducing the Text Interpreter::
963: * Stacks and Postfix notation::
964: * Your first definition::
965: * How does that work?::
966: * Forth is written in Forth::
967: * Review - elements of a Forth system::
968: * Exercises::
969: @end menu
970:
971: @comment ----------------------------------------------
972: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
973: @section Introducing the Text Interpreter
974: @cindex text interpreter
975: @cindex outer interpreter
976:
977: When you invoke the Forth image, you will see a startup banner printed
978: and nothing else (if you have Gforth installed on your system, try
979: invoking it now, by typing @kbd{gforth<return>}). Forth is now running
980: its command line interpreter, which is called the @var{Text Interpreter}
1.26 crook 981: (also known as the @var{Outer Interpreter}). (You will learn a lot
982: about the text interpreter as you read through this chapter,
983: but @pxref{The Text Interpreter} for more detail).
1.21 crook 984:
1.26 crook 985: Although it's not obvious, Forth is actually waiting for your
1.21 crook 986: input. Type a number and press the <return> key:
987:
988: @example
989: @kbd{45<return>} ok
990: @end example
991:
992: Rather than give you a prompt to invite you to input something, the text
993: interpreter prints a status message @var{after} it has processed a line
1.26 crook 994: of input. The status message in this case (``@code{ ok}'' followed by
1.21 crook 995: carriage-return) indicates that the text interpreter was able to process
996: all of your input successfully. Now type something illegal:
997:
998: @example
999: @kbd{qwer341<return>}
1.26 crook 1000: :1: Undefined word
1001: qwer341
1.21 crook 1002: ^^^^^^^
1.26 crook 1003: $400D2BA8 Bounce
1004: $400DBDA8 no.extensions
1.21 crook 1005: @end example
1006:
1.26 crook 1007: The exact text, other than the ``Undefined word'' may differ slightly on
1008: your system, but the effect is the same; when the text interpreter
1009: detects an error, it discards any remaining text on a line, resets
1010: certain internal state and prints an error message.
1011:
1.27 crook 1012: The text interpreter waits for you to press carriage-return, and then
1.26 crook 1013: processes your input line. Starting at the beginning of the line, it
1014: breaks the line into groups of characters separated by spaces. For each
1015: group of characters in turn, it makes two attempts to do something:
1.21 crook 1016:
1017: @itemize @bullet
1018: @item
1019: It tries to treat it as a command. It does this by searching a @var{name
1020: dictionary}. If the group of characters matches an entry in the name
1021: dictionary, the name dictionary provides the text interpreter with
1022: information that allows the text interpreter perform some actions. In
1023: Forth jargon, we say that the group
1024: @cindex word
1025: @cindex definition
1026: @cindex execution token
1027: @cindex xt
1028: of characters names a @var{word}, that the dictionary search returns an
1029: @var{execution token (xt)} corresponding to the @var{definition} of the
1030: word, and that the text interpreter executes the xt. Often, the terms
1031: @var{word} and @var{definition} are used interchangeably.
1032: @item
1033: If the text interpreter fails to find a match in the name dictionary, it
1034: tries to treat the group of characters as a number in the current number
1035: base (when you start up Forth, the current number base is base 10). If
1036: the group of characters legitimately represents a number, the text
1037: interpreter pushes the number onto a stack (we'll learn more about that
1038: in the next section).
1039: @end itemize
1040:
1041: If the text interpreter is unable to do either of these things with any
1.26 crook 1042: group of characters, it discards the group of characters and the rest of
1043: the line, then prints an error message. If the text interpreter reaches
1044: the end of the line without error, it prints the status message ``@code{ ok}''
1045: followed by carriage-return.
1.21 crook 1046:
1047: This is the simplest command we can give to the text interpreter:
1048:
1049: @example
1050: @kbd{<return>} ok
1051: @end example
1052:
1053: The text interpreter did everything we asked it to do (nothing) without
1.26 crook 1054: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
1.21 crook 1055: command:
1056:
1057: @example
1058: @kbd{12 dup fred dup<return>}
1.26 crook 1059: :1: Undefined word
1060: 12 dup fred dup
1.21 crook 1061: ^^^^
1.26 crook 1062: $400D2BA8 Bounce
1063: $400DBDA8 no.extensions
1.21 crook 1064: @end example
1065:
1.26 crook 1066: When you press the carriage-return key, the text interpreter starts to
1067: work its way along the line:
1.21 crook 1068:
1069: @itemize @bullet
1070: @item
1071: When it gets to the space after the @code{2}, it takes the group of
1072: characters @code{12} and looks them up in the name
1073: dictionary@footnote{We can't tell if it found them or not, but assume
1074: for now that it did not}. There is no match for this group of characters
1075: in the name dictionary, so it tries to treat them as a number. It is
1.26 crook 1076: able to do this successfully, so it puts the number, 12, ``on the stack''
1.21 crook 1077: (whatever that means).
1078: @item
1079: The text interpreter resumes scanning the line and gets the next group
1.26 crook 1080: of characters, @code{dup}. It looks it up in the name dictionary and
1081: (you'll have to take my word for this) finds it, and executes the word
1.21 crook 1082: @code{dup} (whatever that means).
1083: @item
1084: Once again, the text interpreter resumes scanning the line and gets the
1085: group of characters @code{fred}. It looks them up in the name
1086: dictionary, but can't find them. It tries to treat them as a number, but
1087: they don't represent any legal number.
1088: @end itemize
1089:
1090: At this point, the text interpreter gives up and prints an error
1091: message. The error message shows exactly how far the text interpreter
1092: got in processing the line. In particular, it shows that the text
1093: interpreter made no attempt to do anything with the final character
1094: group, @code{dup}, even though we have good reason to believe that the
1095: text interpreter would have had no problems with looking that word up
1096: and executing it a second time.
1097:
1098:
1099: @comment ----------------------------------------------
1100: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
1101: @section Stacks, postfix notation and parameter passing
1102: @cindex text interpreter
1103: @cindex outer interpreter
1104:
1105: In procedural programming languages (like C and Pascal), the
1.26 crook 1106: building-block of programs is the @var{function} or @var{procedure}. These
1107: functions or procedures are called with @var{explicit parameters}. For
1.21 crook 1108: example, in C we might write:
1109:
1110: @example
1111: total = total + new_volume(length,height,depth);
1112: @end example
1113:
1.26 crook 1114: @noindent
1115: where new_volume is a function-call to another piece of code, and total,
1116: length, height and depth are all variables. length, height and depth are
1117: parameters to the function-call.
1.21 crook 1118:
1.26 crook 1119: In Forth, the equivalent of the function or procedure is the
1.21 crook 1120: @var{definition} and parameters are implicitly passed between
1121: definitions using a shared stack that is visible to the
1122: programmer. Although Forth does support variables, the existence of the
1123: stack means that they are used far less often than in most other
1124: programming languages. When the text interpreter encounters a number, it
1125: will place (@var{push}) it on the stack. There are several stacks (the
1126: actual number is implementation-dependent ..) and the particular stack
1127: used for any operation is implied unambiguously by the operation being
1128: performed. The stack used for all integer operations is called the @var{data
1129: stack} and, since this is the stack used most commonly, references to
1.26 crook 1130: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 1131:
1132: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1133:
1134: @example
1135: @kbd{1 2 3<return>} ok
1136: @end example
1137:
1.26 crook 1138: Then this instructs the text interpreter to placed three numbers on the
1139: (data) stack. An analogy for the behaviour of the stack is to take a
1140: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
1141: the table. The 3 was the last card onto the pile (``last-in'') and if
1142: you take a card off the pile then, unless you're prepared to fiddle a
1143: bit, the card that you take off will be the 3 (``first-out''). The
1144: number that will be first-out of the stack is called the @var{top of
1145: stack}, which
1146: @cindex TOS definition
1.21 crook 1147: is often abbreviated to @var{TOS}.
1148:
1.26 crook 1149: To understand how parameters are passed in Forth, consider the
1150: behaviour of the definition @code{+} (pronounced ``plus''). You will not
1151: be surprised to learn that this definition performs addition. More
1.21 crook 1152: precisely, it adds two number together and produces a result. Where does
1.26 crook 1153: it get the two numbers from? It takes the top two numbers off the
1.21 crook 1154: stack. Where does it place the result? On the stack. You can act-out the
1155: behaviour of @code{+} with your playing cards like this:
1156:
1157: @itemize @bullet
1158: @item
1.26 crook 1159: Pick up two cards from the stack on the table
1.21 crook 1160: @item
1.26 crook 1161: Stare at them intently and ask yourself ``what @var{is} the sum of these two
1162: numbers''
1.21 crook 1163: @item
1164: Decide that the answer is 5
1165: @item
1166: Shuffle the two cards back into the pack and find a 5
1167: @item
1168: Put a 5 on the remaining ace that's on the table.
1169: @end itemize
1170:
1171: If you don't have a pack of cards handy but you do have Forth running,
1.26 crook 1172: you can use the definition @code{.s} to show the current state of the stack,
1.21 crook 1173: without affecting the stack. Type:
1174:
1175: @example
1176: @kbd{clearstack 1 2 3<return>} ok
1.26 crook 1177: @kbd{.s<return>} <3> 1 2 3 ok
1.21 crook 1178: @end example
1179:
1180: The text interpreter looks up the word @code{clearstack} and executes
1181: it; it tidies up the stack and removes any entries that may have been
1182: left on it by earlier examples. The text interpreter pushes each of the
1183: three numbers in turn onto the stack. Finally, the text interpreter
1184: looks up the word @code{.s} and executes it. The effect of executing
1.26 crook 1185: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
1186: followed by a list of all the items on the stack; the item on the far
1187: right-hand side is the TOS.
1.21 crook 1188:
1189: You can now type:
1190:
1.26 crook 1191: @example
1192: @kbd{+ .s<return>} <2> 1 5 ok
1193: @end example
1.21 crook 1194:
1.26 crook 1195: @noindent
1.21 crook 1196: which is correct; there are now 2 items on the stack and the result of
1197: the addition is 5.
1198:
1.26 crook 1199: If you're playing with cards, try doing a second addition: pick up the
1.21 crook 1200: two cards, work out that their sum is 6, shuffle them into the pack,
1.26 crook 1201: look for a 6 and place that on the table. You now have just one item on
1202: the stack. What happens if you try to do a third addition? Pick up the
1203: first card, pick up the second card -- ah! There is no second card. This
1204: is called a @var{stack underflow} and consitutes an error. If you try to
1205: do the same thing with Forth it will report an error (probably a Stack
1206: Underflow or an Invalid Memory Address error).
1207:
1208: The opposite situation to a stack underflow is a @var{stack overflow},
1209: which simply accepts that there is a finite amount of storage space
1210: reserved for the stack. To stretch the playing card analogy, if you had
1211: enough packs of cards and you piled the cards up on the table, you would
1212: eventually be unable to add another card; you'd hit the ceiling. Gforth
1213: allows you to set the maximum size of the stacks. In general, the only
1214: time that you will get a stack overflow is because a definition has a
1215: bug in it and is generating data on the stack uncontrollably.
1.21 crook 1216:
1217: There's one final use for the playing card analogy. If you model your
1218: stack using a pack of playing cards, the maximum number of items on
1219: your stack will be 52 (I assume you didn't use the Joker). The maximum
1.26 crook 1220: @var{value} of any item on the stack is 13 (the King). In fact, the only
1.21 crook 1221: possible numbers are positive integer numbers 1 through 13; you can't
1222: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
1223: think about some of the cards, you can accommodate different
1224: numbers. For example, you could think of the Jack as representing 0,
1225: the Queen as representing -1 and the King as representing -2. Your
1226: *range* remains unchanged (you can still only represent a total of 13
1227: numbers) but the numbers that you can represent are -2 through 10.
1228:
1229: In that analogy, the limit was the amount of information that a single
1230: stack entry could hold, and Forth has a similar limit. In Forth, the
1.26 crook 1231: size of a stack entry is called a @var{cell}. The actual size of a cell is
1.21 crook 1232: implementation dependent and affects the maximum value that a stack
1233: entry can hold. A Standard Forth provides a cell size of at least
1234: 16-bits, and most desktop systems use a cell size of 32-bits.
1235:
1236: Forth does not do any type checking for you, so you are free to
1237: manipulate and combine stack items in any way you wish. A convenient
1238: ways of treating stack items is as 2's complement signed integers, and
1.26 crook 1239: that is what Standard words like ``+'' do. Therefore you can type:
1.21 crook 1240:
1.26 crook 1241: @example
1242: @kbd{-5 12 + .s<return>} <1> 7 ok
1243: @end example
1.21 crook 1244:
1.26 crook 1245: If you use numbers and definitions like ``+'' in order to turn Forth
1.21 crook 1246: into a great big pocket calculator, you will realise that it's rather
1247: different from a normal calculator. Rather than typing 2 + 3 = you had
1.26 crook 1248: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
1.21 crook 1249: result). The terminology used to describe this difference is to say
1.26 crook 1250: that your calculator uses @var{Infix Notation} (parameters and operators
1251: are mixed) whilst Forth uses @var{Postfix Notation} (parameters and
1252: operators are separate), also called @var{Reverse Polish Notation}.
1.21 crook 1253:
1254: Whilst postfix notation might look confusing to begin with, it has
1255: several important advantages:
1256:
1.26 crook 1257: @itemize @bullet
1258: @item
1259: it is unambiguous
1260: @item
1261: it is more concise
1262: @item
1263: it fits naturally with a stack-based system
1264: @end itemize
1.21 crook 1265:
1266: To examine these claims in more detail, consider these sums:
1267:
1.26 crook 1268: @example
1.21 crook 1269: 6 + 5 * 4 =
1270: 4 * 5 + 6 =
1.26 crook 1271: @end example
1.21 crook 1272:
1273: If you're just learning maths or your maths is very rusty, you will
1274: probably come up with the answer 44 for the first and 26 for the
1275: second. If you are a bit of a whizz at maths you will remember the
1.26 crook 1276: @var{convention} that multiplication takes precendence over addition, and
1.21 crook 1277: you'd come up with the answer 26 both times. To explain the answer 26
1278: to someone who got the answer 44, you'd probably rewrite the first sum
1279: like this:
1280:
1.26 crook 1281: @example
1.21 crook 1282: 6 + (5 * 4) =
1.26 crook 1283: @end example
1.21 crook 1284:
1285: If what you really wanted was to perform the addition before the
1286: multiplication, you would have to use parentheses to force it.
1287:
1288: If you did the first two sums on a pocket calculator you would probably
1289: get the right answers, unless you were very cautious and entered them using
1290: these keystroke sequences:
1291:
1292: 6 + 5 = * 4 =
1293: 4 * 5 = + 6 =
1294:
1295: Postfix notation is unambiguous because the order that the operators
1296: are applied is always explicit; that also means that parentheses are
1.26 crook 1297: never required. The operators are @var{active} (the act of quoting the
1298: operator makes the operation occur) which removes the need for ``=''.
1.21 crook 1299:
1300: The sum 6 + 5 * 4 can be written (in postfix notation) in two
1301: equivalent ways:
1302:
1.26 crook 1303: @example
1.21 crook 1304: 6 5 4 * + or:
1305: 5 4 * 6 +
1.26 crook 1306: @end example
1.21 crook 1307:
1.23 crook 1308: An important thing that you should notice about this notation is that
1309: the @var{order} of the numbers does not change; if you want to subtract
1310: 2 from 10 you type @code{10 2 -}.
1311:
1.26 crook 1312: The reason that Forth uses postfix notation is very simple to explain: it
1.23 crook 1313: makes the implementation extremely simple, and it follows naturally from
1314: using the stack as a mechanism for passing parameters. Another way of
1315: thinking about this is to realise that all Forth definitions are
1316: @var{active}; they execute as they are encountered by the text
1.26 crook 1317: interpreter. The result of this is that the syntax of Forth is trivially
1318: simple.
1.23 crook 1319:
1320:
1321:
1322: @comment ----------------------------------------------
1323: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
1324: @section Your first Forth definition
1325: @cindex first definition
1.21 crook 1326:
1.23 crook 1327: Until now, the examples we've seen have been trivial; we've just been
1328: using Forth an a bigger-than-pocket calculator. Also, each calculation
1.26 crook 1329: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
1.23 crook 1330: again@footnote{That's not quite true. If you press the up-arrow key on
1331: your keyboard you should be able to scroll back to any earlier command,
1332: edit it and re-enter it.} In this section we'll see how to add new
1333: word to Forth's vocabulary.
1334:
1.26 crook 1335: The easiest way to create a new word is to use a @var{colon
1336: definition}. We'll define a few and try them out before we worry too
1.23 crook 1337: much about how they work. Try typing in these examples; be careful to
1338: copy the spaces accurately:
1339:
1340: @example
1341: : add-two 2 + . ;
1342: : greet ." Hello and welcome" ;
1343: : demo 5 add-two ;
1344: @end example
1.21 crook 1345:
1.23 crook 1346: @noindent
1347: Now try them out:
1.21 crook 1348:
1.23 crook 1349: @example
1350: @kbd{greet<return>} Hello and welcome ok
1351: @kbd{greet greet<return>} Hello and welcomeHello and welcome ok
1352: @kbd{4 add-two<return>} 6 ok
1353: @kbd{demo<return>} 7 ok
1354: @kbd{9 greet demo add-two<return>} Hello and welcome7 11 ok
1355: @end example
1.21 crook 1356:
1.23 crook 1357: The first new thing that we've introduced here is the pair of words
1358: @code{:} and @code{;}. These are used to start and terminate a new
1359: definition, respectively. The first word after the @code{:} is the name
1360: for the new definition.
1.21 crook 1361:
1.23 crook 1362: As you can see from the examples, a definition is built up of words that
1363: have already been defined; Forth makes no distinction between
1364: definitions that existed when you started the system up, and those that
1365: you define yourself.
1.21 crook 1366:
1.23 crook 1367: The examples also introduce the words @code{.} (dot), @code{."} (dot-quote)
1368: and @code{dup} (dewp). Dot takes the value from the top of the stack and
1369: displays it. It's like @code{.s} except that it only displays the top
1370: item of the stack and it is destructive; after it has executed the
1371: number is no longer on the top of the stack. There is always one space
1372: printed after the number, and no spaces before it. Dot-quote defines a
1373: string (a sequence of characters) that will be printed when the word is
1374: executed. The string can contain any printable characters except
1375: @code{"}. A @code{"} has a special function; it is not itself a Forth
1376: word but it acts as a delimiter. The way that it works is described in
1377: the next section. Finally, @code{dup} duplicates the value at the top of
1378: the stack. Try typing @code{5 dup .s} to see what it does.
1.21 crook 1379:
1.23 crook 1380: We already know that the text interpreter searches through the
1381: dictionary to locate names. If you've followed the examples earlier, you
1382: will already have a definition called @code{add-two}. Lets try modifying
1383: it by typing in a new definition:
1.21 crook 1384:
1.23 crook 1385: @example
1386: @kbd{: add-two dup . ." + 2 =" 2 + . ;<return>} redefined add-two ok
1387: @end example
1.21 crook 1388:
1.23 crook 1389: Forth recognised that we were defining a word that already exists, and
1390: printed a message to warn us of that fact. Let's try out the new
1391: definition:
1.21 crook 1392:
1.23 crook 1393: @example
1394: @kbd{9 add-two<return>} 9 + 2 =11 ok
1395: @end example
1.21 crook 1396:
1.23 crook 1397: @noindent
1398: All that we've actually done here, though, is to create a new
1399: definition, with a particular name. The fact that there was already a
1400: definition with the same name did not make any difference to the way
1401: that the new definition was created (except that Forth printed a warning
1402: message). The old definition of add-two still exists (try @code{demo}
1403: again to see that this is true). Any new definition will use the new
1404: definition of @code{add-two}, but old definitions continue to use the
1405: version that already existed at the time that they were @code{compiled}.
1.21 crook 1406:
1.23 crook 1407: Before you go on to the next section, try defining and redefining some
1408: words of your own.
1.21 crook 1409:
1410: @comment ----------------------------------------------
1411: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
1412: @section How does that work?
1413: @cindex parsing words
1414:
1.23 crook 1415: Now we're going to take another look at the definition of @code{add-two}
1416: from the previous section. From our knowledge of the way that the text
1417: interpreter works, we would have expected this result when we tried to
1418: define @code{add-two}:
1.21 crook 1419:
1.23 crook 1420: @example
1421: @kbd{: add-two 2 + . " ;<return>}
1422: ^^^^^^^
1423: Error: Undefined word
1424: @end example
1.21 crook 1425:
1.23 crook 1426: The reason that this didn't happen is bound up in the way that @code{:}
1427: works. The word @code{:} does two special things. The first special
1428: thing that it does prevents the text interpreter from ever seeing the
1429: characters @code{add-two}. The text interpreter uses a variable called
1430: @cindex modifying >IN
1431: @code{>IN} (pronounced ''to-in'') to keep track of where it is in the
1432: input line. When it encounters the word @code{:} it behaves in exactly
1433: the same way as it does for any other word; it looks it up in the name
1434: dictionary, finds its xt and executes it. When @code{:} executes, it
1435: looks at the input buffer, finds the word @code{add-two} and advances the
1436: value of @code{>IN} to point past it. It then does some other stuff
1437: associated with creating the new definition (including creating an entry
1438: for @code{add-two} in the name dictionary). When the execution of @code{:}
1439: completes, control returns to the text interpreter, which is oblivious
1440: to the fact that it has been tricked into ignoring part of the input
1441: line.
1.21 crook 1442:
1.23 crook 1443: @cindex parsing words
1444: Words like @code{:} -- words that advance the value of @code{>IN} and so
1445: prevent the text interpreter from acting on the whole of the input line
1446: -- are called @var{parsing words}.
1447:
1.28 ! crook 1448: @cindex @code{state} - effect on the text interpreter
1.23 crook 1449: @cindex text interpreter - effect of state
1450: The second special thing that @code{:} does is to change the value of a
1451: variable called @code{state}, which affects the way that the text
1452: interpreter behaves. When Gforth starts up, @code{state} has the value
1453: 0, and the text interpreter is said to be in @var{interpret}
1454: mode. During a colon definition (started with @code{:}), @code{state} is
1455: set to -1 and the text interpreter is said to be in @var{compile}
1456: mode. The word @code{;} ends the definition -- one of the things that it
1457: does is to change the value of @code{state} back to 0.
1458:
1459: When the text interpreter is in @var{interpret} mode, we already know
1460: how it behaves; it looks for each character sequence in the dictionary,
1461: finds its xt and executes it, or it converts it to a number and pushes
1462: it onto the stack, or it fails to do either and generates an error.
1463:
1464: When the text interpreter is in @var{compile} mode, its behaviour is
1465: slightly different; it still looks for each character sequence in the
1466: dictionary and finds its xt, or converts it to a number, or fails to do
1467: either and generates an error. However, instead of executing the xt or
1468: pushing the number onto the stack it lays down (@var{compiles}) some
1469: magic to make that xt or number get executed or pushed at a later time;
1470: at the time that @code{add-two} is @var{executed}. Therefore, when you
1471: execute @code{add-two} its @var{run-time effect} is exactly the same as
1472: if you had typed @code{2 + .} outside of a definition, and pressed
1.26 crook 1473: carriage-return.
1.21 crook 1474:
1.23 crook 1475: In Forth, every word or number can be described in terms of three
1476: properties:
1.21 crook 1477:
1478: @itemize @bullet
1479: @item
1.23 crook 1480: Its behaviour at @var{compile} time
1.21 crook 1481: @item
1.23 crook 1482: Its behaviour at @var{interpret} time
1.21 crook 1483: @item
1.23 crook 1484: Its behaviour at @var{execution} time.
1.21 crook 1485: @end itemize
1486:
1.23 crook 1487: These behaviours are called the @var{semantics} of the word or
1488: number. The value of @var{state} determines whether the text
1489: interpreter will use the compile or interpret semantics of a word or
1490: number that it encounters.
1.21 crook 1491:
1492: @itemize @bullet
1493: @item
1.23 crook 1494: @cindex interpretation semantics
1495: When the text interpreter encounters a word or number in @var{interpret}
1496: state, it performs the @var{interpretation semantics} of the word or
1497: number.
1.21 crook 1498: @item
1.23 crook 1499: @cindex compilation semantics
1500: When the text interpreter encounters a word or number in @var{compile}
1501: state, it performs the @var{compilation semantics} of the word or
1502: number.
1.21 crook 1503: @end itemize
1504:
1.23 crook 1505: The behaviour of numbers is always the same:
1.21 crook 1506:
1507: @itemize @bullet
1508: @item
1.23 crook 1509: When the number is @var{compiled}, it is appended to the current
1510: definition so that its run-time behaviour is to execute. (In other
1511: words, the compilation semantics of a number are to postpone its
1512: execution semantics until the run-time of the definition that it is
1513: being compiled into.)
1514: @item
1515: When the number is @var{interpreted}, its behaviour is to execute. (In
1516: other words, the interpretation semantics of a number are to perform its
1517: execution semantics.)
1.21 crook 1518: @item
1.23 crook 1519: @cindex execution semantics
1520: When the number is @var{executed}, its behaviour is to push its value
1521: onto the stack. (In other words, the execution semantics of a number are
1522: to push its value onto the stack.)
1.21 crook 1523: @end itemize
1524:
1.23 crook 1525: The behaviour of a word is not so regular, but the vast majority behave
1526: like this:
1.21 crook 1527:
1528: @itemize @bullet
1529: @item
1.23 crook 1530: The @var{compilation semantics} of the word are to append its
1531: @var{execution semantics} to the current definition (so that its
1532: run-time behaviour is to execute).
1.21 crook 1533: @item
1.23 crook 1534: The @var{interpretation semantics} of the word are to execute.
1535: @item
1536: The @var{execution semantics} of the word are to do something useful.
1.21 crook 1537: @end itemize
1538:
1539:
1.23 crook 1540: The actual behaviour of any particular word depends upon the way in
1541: which it was defined. In all cases, the text interpreter decides what to
1542: do with the word; when it searches the name dictionary for a definition,
1543: it not only retrieves the xt for the word, it also retrieves a flag
1544: called the @var{immediate flag}. If the flag is set, the text
1545: interpreter will @var{execute} the word rather than @var{compiling}
1546: @cindex immediate words
1547: it. In other words, these so-called @var{immediate} words behave like
1548: this:
1.21 crook 1549:
1550: @itemize @bullet
1551: @item
1.23 crook 1552: The @var{compilation semantics} of the word are to perform its
1553: @var{execution semantics} (so that its compile-time behaviour is to
1554: execute).
1.21 crook 1555: @item
1.23 crook 1556: The @var{interpretation semantics} of the word are to execute.
1557: @item
1558: The @var{execution semantics} of the word are to do something useful.
1.21 crook 1559: @end itemize
1560:
1.23 crook 1561: This example shows the difference between an immediate and a
1562: non-immediate word:
1.21 crook 1563:
1564: @example
1.23 crook 1565: : show-state state @ . ;
1566: : show-state-now show-state ; immediate
1567: : word1 show-state ;
1568: : word2 show-state-now ;
1569: @end example
1570:
1571: The word @code{immediate} after the definition of @code{show-state-now}
1572: makes that word an immediate word. These definitions introduce a new
1.27 crook 1573: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
1.23 crook 1574: variable, and leaves it on the stack. Therefore, the behaviour of
1575: @code{show-state} is to print a number that represents the current value
1576: of @code{state}.
1577:
1578: When you execute @code{word1}, it prints the number 0, indicating
1579: that the system is in interpret state. When the text interpreter
1580: compiled the definition of @code{word1}, it encountered
1581: @code{show-state} whose compilation semantics are to append its
1582: execution semantics to the current definition. When you execute
1583: @code{word1}, it performs the execution semantics of @code{show-state}.
1584: At the time that @code{word1} (and therefore @code{show-state}) are
1585: executed, the system is in interpret state.
1586:
1587: When you pressed <return> after entering the definition of @code{word2},
1588: you should have seen the number -1 printed, followed by @code{ ok}. When
1589: the text interpreter compiled the definition of @code{word2}, it
1590: encountered @code{show-state-now}, an immediate word, whose compilation
1591: semantics are therefore to perform its execution semantics. It is
1592: executed straight away (even before the text interpreter has moved on
1593: to process another group of characters; the @code{;} in this
1594: example). The effect of executing it are to display the value of
1595: @code{state} @var{at the time that the definition of} @code{word2}
1596: @var{is being defined}. Printing -1 demonstrates that the system is in
1597: compilation state at this time. If you execute @code{word2} it does
1598: nothing at all.
1599:
1.26 crook 1600: @cindex @code{."}, how it works
1.23 crook 1601: Before leaving the subject of immediate words, consider the behaviour of
1602: @code{."} in the definition of @code{greet}, in the previous
1603: section. This word is both a parsing word and an immediate word. Notice
1604: that there is a space between @code{."} and the start of the text
1605: @code{Hello and welcome}, but that there is no space between the last
1606: letter of @code{welcome} and the @code{"} character. The reason for this
1607: is that @code{."} is a Forth word; it must have a space after it so that
1608: the text interpreter can identify it. The @code{"} is not a Forth word;
1609: it is a @var{delimiter}. The examples earlier show that, when the string
1610: is displayed, there is neither a space before the @code{H} nor after the
1611: @code{e}. Since @code{."} is an immediate word, it executes at the time
1.26 crook 1612: that @code{greet} is defined. When it executes, it searches forward in
1.23 crook 1613: the input line looking for the delimiter. When it finds the delimiter,
1614: it updates @code{>in} to point past the delimiter. It also compiles some
1615: magic code into the definition of @code{greet}; the xt of a run-time
1616: routine that prints a text string. It compiles the string @code{Hello
1617: and welcome} into memory so that it is available to be printed
1618: later. When the text interpreter gains control, the next word it finds
1619: in the input stream is @code{;} and so it terminates the definition of
1620: @code{greet}.
1.21 crook 1621:
1622:
1.23 crook 1623: @comment ----------------------------------------------
1624: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
1625: @section Forth is written in Forth
1626: @cindex structure of Forth programs
1.21 crook 1627:
1.23 crook 1628: When you start up a Forth compiler, a large number of definitions
1629: already exist. In Forth, you develop a new application using bottom-up
1630: programming techniques to create new definitions that are defined in
1631: terms of existing definitions. As you create each definition you can
1632: test and debug it interactively.
1633:
1634: If you have tried out the examples in this section, you will probably
1635: have typed them in by hand; when you leave Gforth, your definitions will
1636: be deleted. You can avoid this by using a text editor to enter Forth
1637: source code into a file, and then load all of the code from the file
1.26 crook 1638: using @code{include} (@xref{Forth source files}). A Forth source
1.23 crook 1639: file is processed by the text interpreter, just as though you had typed
1640: it in by hand@footnote{Actually, there are some subtle differences, like
1641: the fact that it doesn't print @code{ ok} at the end of each line}.
1642:
1643: Gforth also supports the traditional Forth alternative to using text
1644: files for program entry (@xref{Blocks}).
1645:
1646: In common with many, if not most, Forth compilers, most of Gforth is
1.28 ! crook 1647: actually written in Forth. All of the @file{.fs} files in the
! 1648: installation directory@footnote{For example,
! 1649: @file{/usr/local/share/gforth..}} are Forth source files, which you can
! 1650: study to see examples of Forth programming.
! 1651:
! 1652: Gforth maintains a history file that records every line that you type to
! 1653: the text interpreter. This file is preserved between sessions, and is
! 1654: used to provide a command-line recall facility. If you enter long
! 1655: definitions by hand, you can use a text editor to paste them out of the
! 1656: history file into a Forth source file for reuse at a later time
! 1657: (@pxref{Command-line editing} for more information).
1.21 crook 1658:
1659:
1.23 crook 1660: @comment ----------------------------------------------
1661: @node Review - elements of a Forth system, Exercises, Forth is written in Forth, Introduction
1662: @section Review - elements of a Forth system
1663: @cindex elements of a Forth system
1.21 crook 1664:
1.23 crook 1665: To summarise this chapter:
1.21 crook 1666:
1667:
1.23 crook 1668: @itemize @bullet
1669: @item
1670: Forth programs use @var{factoring} to break a problem down into small
1671: fragments called @var{words} or @var{definitions}.
1672: @item
1673: Forth program development is an interactive process.
1674: @item
1675: The main command loop that accepts input, and controls both
1676: interpretation and compilation, is called the @var{text interpreter}
1.26 crook 1677: (also known as the @var{outer interpreter}).
1.23 crook 1678: @item
1679: Forth has a very simple syntax, consisting of words and numbers
1680: separated by spaces or carriage-return characters. Any additional syntax
1681: is imposed by @var{parsing words}.
1682: @item
1683: Forth uses a stack to pass parameters between words. As a result, it
1684: uses postfix notation.
1685: @item
1686: To use a word that has previously been defined, the text interpreter
1687: searches for the word in the @var{name dictionary}.
1688: @item
1689: Words have @var{interpretation semantics}, @var{compilation semantics}
1690: and @var{execution semantics}.
1691: @item
1692: The text interpreter uses the value of @code{state} to select between
1693: the use of the @var{interpretation semantics} and the @var{compilation
1694: semantics} of a word that it encounters.
1695: @item
1696: The relationship between the @var{interpretation semantics}, @var{compilation semantics}
1697: and @var{execution semantics} for a word depend upon the way in which
1.26 crook 1698: the word was defined (for example, whether it is an @var{immediate} word).
1.23 crook 1699: @item
1700: Forth definitions can be implemented in Forth (called @var{high-level
1701: definitions}) or in some other way (usually a lower-level language and
1702: as a result often called @var{low-level definitions}, @var{code
1703: definitions} or @var{primitives}).
1704: @item
1705: Many Forth systems are implemented mainly in Forth.
1706: @item
1707: You now know enough to read and understand the rest of this manual and
1.26 crook 1708: the ANS Forth document.
1.23 crook 1709: @end itemize
1.21 crook 1710:
1711:
1.23 crook 1712: @comment TODO - other defining words
1713: @comment other parsing words
1714: @comment Your first loop
1715: @comment syntax and semantics
1716: @comment DOES>
1717: @comment taste of other elements of Forth
1.21 crook 1718:
1719:
1720:
1721: @comment ----------------------------------------------
1.23 crook 1722: @node Exercises, ,Review - elements of a Forth system, Introduction
1723: @section Exercises
1.21 crook 1724: @cindex elements of a Forth system
1725:
1.23 crook 1726: Amazing as it may seem, if you have read (and understood) this far, you
1727: know almost all the fundamentals about the inner workings of a Forth
1728: system. You certainly know enough to be able to read and understand the
1729: rest of this manual, to learn more about the facilities that Gforth
1730: provides. Even scarier, you know almost enough to implement your own Forth
1731: system. However, that's not a good idea just yet.. better to try writing
1732: some programs in Gforth.
1733:
1.26 crook 1734: The large number of Forth words available in ANS Forth and
1.23 crook 1735: Gforth make learning Forth somewhat daunting. To make the problem
1736: easier, use the index of this manual to learn more about these words:
1.21 crook 1737:
1.23 crook 1738: ..levels of Forth words.
1.21 crook 1739:
1740:
1741: Ideally, provide a set of programming excercises linked into the stuff
1742: done already and into other sections of the manual. Provide solutions to
1743: all the exercises in a .fs file in the distribution. Get some
1744: inspiration from Starting Forth and Kelly&Spies.
1745:
1746:
1.28 ! crook 1747: @c excercises:
! 1748: @c 1. take inches and convert to feet and inches.
! 1749: @c 2. take temperature and convert from fahrenheight to celcius;
! 1750: @c may need to care about symmetric vs floored??
! 1751: @c 3. take input line and do character substitution
! 1752: @c to encipher or decipher
! 1753: @c 4. as above but work on a file for in and out
! 1754: @c 5. take input line and convert to pig-latin
! 1755: @c
! 1756: @c thing of sets of things to exercise then come up with
! 1757: @c problems that need those things.
! 1758:
1.26 crook 1759: @c ******************************************************************
1.28 ! crook 1760: @node Gforth Environment, Words, Introduction, Top
! 1761: @chapter Gforth Environment
! 1762: @cindex Gforth environment
! 1763:
! 1764: Note: ultimately, the gforth man page will be auto-geenrated from the
! 1765: material in this chapter.
! 1766:
! 1767: @menu
! 1768: * Invoking Gforth::
! 1769: * Leaving Gforth::
! 1770: * Command-line editing::
! 1771: * Upper and lower case::
! 1772: * Environment variables::
! 1773: * Gforth Files::
! 1774: @end menu
! 1775:
! 1776:
! 1777: @comment ----------------------------------------------
! 1778: @node Invoking Gforth, Leaving Gforth, ,Gforth Environment
! 1779: @section Invoking Gforth
1.26 crook 1780: @cindex invoking Gforth
1781: @cindex running Gforth
1782: @cindex command-line options
1783: @cindex options on the command line
1784: @cindex flags on the command line
1785:
1786: You will usually just say @code{gforth}. In many other cases the default
1787: Gforth image will be invoked like this:
1788: @example
1789: gforth [files] [-e forth-code]
1790: @end example
1791: This interprets the contents of the files and the Forth code in the order they
1792: are given.
1.23 crook 1793:
1.26 crook 1794: In general, the command line looks like this:
1.1 anton 1795:
1.26 crook 1796: @example
1797: gforth [initialization options] [image-specific options]
1798: @end example
1.1 anton 1799:
1.26 crook 1800: The initialization options must come before the rest of the command
1801: line. They are:
1.1 anton 1802:
1.26 crook 1803: @table @code
1804: @cindex -i, command-line option
1805: @cindex --image-file, command-line option
1806: @item --image-file @var{file}
1807: @itemx -i @var{file}
1808: Loads the Forth image @var{file} instead of the default
1809: @file{gforth.fi} (@pxref{Image Files}).
1.1 anton 1810:
1.26 crook 1811: @cindex --path, command-line option
1.1 anton 1812: @cindex -p, command-line option
1813: @item --path @var{path}
1814: @itemx -p @var{path}
1815: Uses @var{path} for searching the image file and Forth source code files
1816: instead of the default in the environment variable @code{GFORTHPATH} or
1817: the path specified at installation time (e.g.,
1818: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
1819: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1820:
1821: @cindex --dictionary-size, command-line option
1822: @cindex -m, command-line option
1823: @cindex @var{size} parameters for command-line options
1824: @cindex size of the dictionary and the stacks
1825: @item --dictionary-size @var{size}
1826: @itemx -m @var{size}
1827: Allocate @var{size} space for the Forth dictionary space instead of
1828: using the default specified in the image (typically 256K). The
1.21 crook 1829: @var{size} specification for this and subsequent options consists of
1830: an integer and a unit (e.g.,
1.1 anton 1831: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
1.12 anton 1832: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
1833: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
1834: @code{e} is used.
1.1 anton 1835:
1836: @cindex --data-stack-size, command-line option
1837: @cindex -d, command-line option
1838: @item --data-stack-size @var{size}
1839: @itemx -d @var{size}
1840: Allocate @var{size} space for the data stack instead of using the
1841: default specified in the image (typically 16K).
1842:
1843: @cindex --return-stack-size, command-line option
1844: @cindex -r, command-line option
1845: @item --return-stack-size @var{size}
1846: @itemx -r @var{size}
1847: Allocate @var{size} space for the return stack instead of using the
1848: default specified in the image (typically 15K).
1849:
1850: @cindex --fp-stack-size, command-line option
1851: @cindex -f, command-line option
1852: @item --fp-stack-size @var{size}
1853: @itemx -f @var{size}
1854: Allocate @var{size} space for the floating point stack instead of
1855: using the default specified in the image (typically 15.5K). In this case
1856: the unit specifier @code{e} refers to floating point numbers.
1857:
1858: @cindex --locals-stack-size, command-line option
1859: @cindex -l, command-line option
1860: @item --locals-stack-size @var{size}
1861: @itemx -l @var{size}
1862: Allocate @var{size} space for the locals stack instead of using the
1863: default specified in the image (typically 14.5K).
1864:
1865: @cindex -h, command-line option
1866: @cindex --help, command-line option
1867: @item --help
1868: @itemx -h
1869: Print a message about the command-line options
1870:
1871: @cindex -v, command-line option
1872: @cindex --version, command-line option
1873: @item --version
1874: @itemx -v
1875: Print version and exit
1876:
1877: @cindex --debug, command-line option
1878: @item --debug
1879: Print some information useful for debugging on startup.
1880:
1881: @cindex --offset-image, command-line option
1882: @item --offset-image
1883: Start the dictionary at a slightly different position than would be used
1884: otherwise (useful for creating data-relocatable images,
1885: @pxref{Data-Relocatable Image Files}).
1886:
1.5 anton 1887: @cindex --no-offset-im, command-line option
1888: @item --no-offset-im
1889: Start the dictionary at the normal position.
1890:
1.1 anton 1891: @cindex --clear-dictionary, command-line option
1892: @item --clear-dictionary
1893: Initialize all bytes in the dictionary to 0 before loading the image
1894: (@pxref{Data-Relocatable Image Files}).
1.5 anton 1895:
1896: @cindex --die-on-signal, command-line-option
1897: @item --die-on-signal
1898: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
1899: or the segmentation violation SIGSEGV) by translating it into a Forth
1900: @code{THROW}. With this option, Gforth exits if it receives such a
1901: signal. This option is useful when the engine and/or the image might be
1902: severely broken (such that it causes another signal before recovering
1903: from the first); this option avoids endless loops in such cases.
1.1 anton 1904: @end table
1905:
1906: @cindex loading files at startup
1907: @cindex executing code on startup
1908: @cindex batch processing with Gforth
1909: As explained above, the image-specific command-line arguments for the
1910: default image @file{gforth.fi} consist of a sequence of filenames and
1911: @code{-e @var{forth-code}} options that are interpreted in the sequence
1912: in which they are given. The @code{-e @var{forth-code}} or
1.21 crook 1913: @code{--evaluate @var{forth-code}} option evaluates the Forth
1.1 anton 1914: code. This option takes only one argument; if you want to evaluate more
1.26 crook 1915: Forth words, you have to quote them or use @code{-e} several times. To exit
1.1 anton 1916: after processing the command line (instead of entering interactive mode)
1917: append @code{-e bye} to the command line.
1918:
1919: @cindex versions, invoking other versions of Gforth
1920: If you have several versions of Gforth installed, @code{gforth} will
1921: invoke the version that was installed last. @code{gforth-@var{version}}
1922: invokes a specific version. You may want to use the option
1923: @code{--path}, if your environment contains the variable
1924: @code{GFORTHPATH}.
1925:
1926: Not yet implemented:
1927: On startup the system first executes the system initialization file
1928: (unless the option @code{--no-init-file} is given; note that the system
1929: resulting from using this option may not be ANS Forth conformant). Then
1930: the user initialization file @file{.gforth.fs} is executed, unless the
1931: option @code{--no-rc} is given; this file is first searched in @file{.},
1932: then in @file{~}, then in the normal path (see above).
1933:
1.21 crook 1934:
1.28 ! crook 1935:
! 1936: @comment ----------------------------------------------
! 1937: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
! 1938: @section Leaving Gforth
1.21 crook 1939: @cindex Gforth - leaving
1940: @cindex leaving Gforth
1941:
1.28 ! crook 1942: You can leave Gforth by typing @code{bye} or Ctrl-D or (if you invoked
! 1943: Gforth with the @code{--die-on-signal} option) Ctrl-C. When you leave
! 1944: Gforth, all of your definitions and data are discarded. @xref{Image
! 1945: Files} for ways of saving the state of the system before leaving Gforth.
1.21 crook 1946:
1947: doc-bye
1948:
1949:
1.28 ! crook 1950: @comment ----------------------------------------------
! 1951: @node Command-line editing, Upper and lower case,Leaving Gforth,Gforth Environment
! 1952: @section Command-line editing
! 1953: @cindex command-line editing
! 1954:
! 1955: Gforth maintains a history file that records every line that you type to
! 1956: the text interpreter. This file is preserved between sessions, and is
! 1957: used to provide a command-line recall facility; if you type ctrl-P
! 1958: repeatedly you can recall successively older command from this (or
! 1959: previous) session(s). The full list of command-line editing facilities is:
! 1960:
! 1961: @itemize @bullet
! 1962: @item
! 1963: ctrl-P (``previous'') (or up-arrow) to recall successively older
! 1964: commands from the history buffer.
! 1965: @item
! 1966: ctrl-N (``next'') (or down-arrow) to recall successively newer commands
! 1967: from the history buffer.
! 1968: @item
! 1969: ctrl-F (or right-arrow) to move the cursor right, non-destructively.
! 1970: @item
! 1971: ctrl-B (or left-arrow) to move the cursor left, non-destructively.
! 1972: @item
! 1973: ctrl-H (backspace) to delete the character to the left of the cursor,
! 1974: closing up the line.
! 1975: @item
! 1976: ctrl-K to delete (``kill'') from the cursor to the end of the line.
! 1977: @item
! 1978: ctrl-A to move the cursor to the start of the line.
! 1979: @item
! 1980: ctrl-E to move the cursor to the end of the line.
! 1981: @item
! 1982: carriage-return or line-feed (ctrl-J, ctrl-M) to submit the current
! 1983: line.
! 1984: @item
! 1985: tab to step through all possible full-word completions of the word
! 1986: currently being typed.
! 1987: @item
! 1988: ctrl-D to terminate Gforth (gracefully, using @code{bye}).
! 1989: @end itemize
! 1990:
! 1991: When editing, displayable characters are inserted to the left of the
! 1992: cursor position; the line is always in ``insert'' (as opposed to
! 1993: ``overstrike'') mode.
! 1994:
! 1995: @cindex history file
! 1996: @cindex @file{.gforth-history}
! 1997: On Unix systems, the history file is @file{~/.gforth-history} by
! 1998: default@footnote{i.e. it is stored in the user's home directory.}. You
! 1999: can find out the name and location of your history file using:
! 2000:
! 2001: @example
! 2002: history-file type \ Unix-class systems
! 2003:
! 2004: history-file type \ Other systems
! 2005: history-dir type
! 2006: @end example
1.23 crook 2007:
1.28 ! crook 2008: If you enter long definitions by hand, you can use a text editor to
! 2009: paste them out of the history file into a Forth source file for reuse at
! 2010: a later time.
! 2011:
! 2012: Gforth never trims the size of the history file, so you should do this
! 2013: periodically, if necessary.
! 2014:
! 2015: @comment this is all defined in history.fs
! 2016: @comment TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
! 2017: @comment chosen?
! 2018:
! 2019:
! 2020:
! 2021: @comment ----------------------------------------------
! 2022: @node Upper and lower case, Environment variables,Command-line editing,Gforth Environment
! 2023: @section Upper and lower case
! 2024: @cindex case-sensitivity
! 2025: @cindex upper and lower case
! 2026:
! 2027: Gforth is case-insensitive, so you can enter definitions and invoke
! 2028: Standard words using upper, lower or mixed case (however,
! 2029: @pxref{core-idef, Implementation-defined options, Implementation-defined
! 2030: options}).
! 2031:
! 2032: ANS Forth only @i{requires} implementations to recognise Standard words when
! 2033: they are typed entirely in upper case. Therefore, a Standard program
! 2034: must use upper case for all Standard words@footnote{You can use whatever
! 2035: case you like for words that you define.}.
! 2036:
! 2037:
! 2038: @comment ----------------------------------------------
! 2039: @node Environment variables, Gforth Files, Upper and lower case,Gforth Environment
! 2040: @section Environment variables
! 2041: @cindex environment variables
! 2042:
! 2043: Gforth uses these environment variables:
! 2044:
! 2045: @itemize @bullet
! 2046: @item
! 2047: @cindex GFORTHHIST - environment variable
! 2048: GFORTHHIST - (Unix systems only) specifies the directory in which to
! 2049: open/create the history file, @file{.gforth-history}. Default:
! 2050: @code{$HOME}.
! 2051:
! 2052: @item
! 2053: @cindex GFORTHPATH - environment variable
! 2054: GFORTHPATH - specifies the path used when searching for the gforth image file and
! 2055: for Forth source-code files.
! 2056:
! 2057: @item
! 2058: @cindex GFORTH - environment variable
! 2059: GFORTH - used by @file{gforthmi} @xref{gforthmi}.
! 2060:
! 2061: @item
! 2062: @cindex GFORTHD - environment variable
! 2063: GFORTHD - used by @file{gforthmi} @xref{gforthmi}.
! 2064:
! 2065: @item
! 2066: @cindex TMP, TEMP - environment variable
! 2067: TMP, TEMP - (non-Unix systems only) used as a potential location for the
! 2068: history file.
! 2069: @end itemize
! 2070:
! 2071: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
! 2072: @comment mentioning these.
! 2073:
! 2074: All the Gforth environment variables default to sensible values if they
! 2075: are not set.
! 2076:
! 2077:
! 2078: @comment ----------------------------------------------
! 2079: @node Gforth Files, ,Environment variables,Gforth Environment
! 2080: @section Gforth files
! 2081: @cindex Gforth files
! 2082:
! 2083: When Gforth is installed on a Unix system it installs files in these
! 2084: locations:
! 2085:
! 2086: @itemize @bullet
! 2087: @item
! 2088: @file{/usr/local/bin/gforth}
! 2089: @item
! 2090: @file{/usr/local/bin/gforthmi}
! 2091: @item
! 2092: @file{/usr/local/man/man1/gforth.1} - man page.
! 2093: @item
! 2094: @file{/usr/local/info} - the Info version of this manual.
! 2095: @item
! 2096: @file{/usr/local/lib/gforth/<version>/..} - Gforth @file{.fi} files.
! 2097: @item
! 2098: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
! 2099: @item
! 2100: @file{/usr/local/share/gforth/<version>/..} - Gforth source files.
! 2101: @item
! 2102: @file{../emacs/site-lisp/gforth.el} - Emacs gforth mode.
! 2103: @end itemize
1.23 crook 2104:
1.26 crook 2105: @c ******************************************************************
1.28 ! crook 2106: @node Words, Error messages, Gforth Environment, Top
1.1 anton 2107: @chapter Forth Words
1.26 crook 2108: @cindex words
1.1 anton 2109:
2110: @menu
2111: * Notation::
1.21 crook 2112: * Comments::
2113: * Boolean Flags::
1.1 anton 2114: * Arithmetic::
2115: * Stack Manipulation::
1.5 anton 2116: * Memory::
1.1 anton 2117: * Control Structures::
2118: * Defining Words::
1.21 crook 2119: * The Text Interpreter::
1.12 anton 2120: * Tokens for Words::
1.21 crook 2121: * Word Lists::
2122: * Environmental Queries::
1.12 anton 2123: * Files::
2124: * Blocks::
2125: * Other I/O::
2126: * Programming Tools::
2127: * Assembler and Code Words::
2128: * Threading Words::
1.26 crook 2129: * Locals::
2130: * Structures::
2131: * Object-oriented Forth::
1.21 crook 2132: * Passing Commands to the OS::
2133: * Miscellaneous Words::
1.1 anton 2134: @end menu
2135:
1.21 crook 2136: @node Notation, Comments, Words, Words
1.1 anton 2137: @section Notation
2138: @cindex notation of glossary entries
2139: @cindex format of glossary entries
2140: @cindex glossary notation format
2141: @cindex word glossary entry format
2142:
2143: The Forth words are described in this section in the glossary notation
2144: that has become a de-facto standard for Forth texts, i.e.,
2145:
2146: @format
2147: @var{word} @var{Stack effect} @var{wordset} @var{pronunciation}
2148: @end format
2149: @var{Description}
2150:
2151: @table @var
2152: @item word
1.28 ! crook 2153: The name of the word.
1.1 anton 2154:
2155: @item Stack effect
2156: @cindex stack effect
2157: The stack effect is written in the notation @code{@var{before} --
2158: @var{after}}, where @var{before} and @var{after} describe the top of
2159: stack entries before and after the execution of the word. The rest of
2160: the stack is not touched by the word. The top of stack is rightmost,
2161: i.e., a stack sequence is written as it is typed in. Note that Gforth
2162: uses a separate floating point stack, but a unified stack
2163: notation. Also, return stack effects are not shown in @var{stack
2164: effect}, but in @var{Description}. The name of a stack item describes
2165: the type and/or the function of the item. See below for a discussion of
2166: the types.
2167:
2168: All words have two stack effects: A compile-time stack effect and a
2169: run-time stack effect. The compile-time stack-effect of most words is
2170: @var{ -- }. If the compile-time stack-effect of a word deviates from
2171: this standard behaviour, or the word does other unusual things at
2172: compile time, both stack effects are shown; otherwise only the run-time
2173: stack effect is shown.
2174:
2175: @cindex pronounciation of words
2176: @item pronunciation
2177: How the word is pronounced.
2178:
2179: @cindex wordset
2180: @item wordset
1.21 crook 2181: The ANS Forth standard is divided into several word sets. A standard
2182: system need not support all of them. Therefore, in theory, the fewer
2183: word sets your program uses the more portable it will be. However, we
2184: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 2185: all word sets. Words that are not defined in ANS Forth have
1.21 crook 2186: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 2187: describes words that will work in future releases of Gforth;
2188: @code{gforth-internal} words are more volatile. Environmental query
2189: strings are also displayed like words; you can recognize them by the
1.21 crook 2190: @code{environment} in the word set field.
1.1 anton 2191:
2192: @item Description
2193: A description of the behaviour of the word.
2194: @end table
2195:
2196: @cindex types of stack items
2197: @cindex stack item types
2198: The type of a stack item is specified by the character(s) the name
2199: starts with:
2200:
2201: @table @code
2202: @item f
2203: @cindex @code{f}, stack item type
2204: Boolean flags, i.e. @code{false} or @code{true}.
2205: @item c
2206: @cindex @code{c}, stack item type
2207: Char
2208: @item w
2209: @cindex @code{w}, stack item type
2210: Cell, can contain an integer or an address
2211: @item n
2212: @cindex @code{n}, stack item type
2213: signed integer
2214: @item u
2215: @cindex @code{u}, stack item type
2216: unsigned integer
2217: @item d
2218: @cindex @code{d}, stack item type
2219: double sized signed integer
2220: @item ud
2221: @cindex @code{ud}, stack item type
2222: double sized unsigned integer
2223: @item r
2224: @cindex @code{r}, stack item type
2225: Float (on the FP stack)
1.21 crook 2226: @item a-
1.1 anton 2227: @cindex @code{a_}, stack item type
2228: Cell-aligned address
1.21 crook 2229: @item c-
1.1 anton 2230: @cindex @code{c_}, stack item type
2231: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 2232: @item f-
1.1 anton 2233: @cindex @code{f_}, stack item type
2234: Float-aligned address
1.21 crook 2235: @item df-
1.1 anton 2236: @cindex @code{df_}, stack item type
2237: Address aligned for IEEE double precision float
1.21 crook 2238: @item sf-
1.1 anton 2239: @cindex @code{sf_}, stack item type
2240: Address aligned for IEEE single precision float
2241: @item xt
2242: @cindex @code{xt}, stack item type
2243: Execution token, same size as Cell
2244: @item wid
2245: @cindex @code{wid}, stack item type
1.21 crook 2246: Word list ID, same size as Cell
1.1 anton 2247: @item f83name
2248: @cindex @code{f83name}, stack item type
2249: Pointer to a name structure
2250: @item "
2251: @cindex @code{"}, stack item type
1.12 anton 2252: string in the input stream (not on the stack). The terminating character
2253: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 2254: quotes.
2255: @end table
2256:
1.21 crook 2257: @node Comments, Boolean Flags, Notation, Words
2258: @section Comments
1.26 crook 2259: @cindex comments
1.21 crook 2260:
1.26 crook 2261: Forth supports two styles of comment; the traditional @var{in-line} comment,
2262: @code{(} and its modern cousin, the @var{comment to end of line}; @code{\}.
1.21 crook 2263:
1.23 crook 2264: doc-(
1.21 crook 2265: doc-\
1.23 crook 2266: doc-\G
1.21 crook 2267:
2268: @node Boolean Flags, Arithmetic, Comments, Words
2269: @section Boolean Flags
1.26 crook 2270: @cindex Boolean flags
1.21 crook 2271:
2272: A Boolean flag is cell-sized. A cell with all bits clear represents the
2273: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 2274: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.21 crook 2275: a cell that has @var{any} bit set as @code{true}.
2276:
2277: doc-true
2278: doc-false
2279:
2280:
2281: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 2282: @section Arithmetic
2283: @cindex arithmetic words
2284:
2285: @cindex division with potentially negative operands
2286: Forth arithmetic is not checked, i.e., you will not hear about integer
2287: overflow on addition or multiplication, you may hear about division by
2288: zero if you are lucky. The operator is written after the operands, but
2289: the operands are still in the original order. I.e., the infix @code{2-1}
2290: corresponds to @code{2 1 -}. Forth offers a variety of division
2291: operators. If you perform division with potentially negative operands,
2292: you do not want to use @code{/} or @code{/mod} with its undefined
2293: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
2294: former, @pxref{Mixed precision}).
1.26 crook 2295: @comment TODO discuss the different division forms and the std approach
1.1 anton 2296:
2297: @menu
2298: * Single precision::
2299: * Bitwise operations::
1.21 crook 2300: * Double precision:: Double-cell integer arithmetic
2301: * Numeric comparison::
1.1 anton 2302: * Mixed precision:: operations with single and double-cell integers
2303: * Floating Point::
2304: @end menu
2305:
2306: @node Single precision, Bitwise operations, Arithmetic, Arithmetic
2307: @subsection Single precision
2308: @cindex single precision arithmetic words
2309:
1.21 crook 2310: By default, numbers in Forth are single-precision integers that are 1
1.26 crook 2311: cell in size. They can be signed or unsigned, depending upon how you
1.21 crook 2312: treat them. @xref{Number Conversion} for the rules used by the text
2313: interpreter for recognising single-precision integers.
2314:
1.1 anton 2315: doc-+
1.21 crook 2316: doc-1+
1.1 anton 2317: doc--
1.21 crook 2318: doc-1-
1.1 anton 2319: doc-*
2320: doc-/
2321: doc-mod
2322: doc-/mod
2323: doc-negate
2324: doc-abs
2325: doc-min
2326: doc-max
1.21 crook 2327: doc-d>s
1.27 crook 2328: doc-floored
1.1 anton 2329:
1.21 crook 2330: @node Bitwise operations, Double precision, Single precision, Arithmetic
1.1 anton 2331: @subsection Bitwise operations
2332: @cindex bitwise operation words
2333:
2334: doc-and
2335: doc-or
2336: doc-xor
2337: doc-invert
1.21 crook 2338: doc-lshift
2339: doc-rshift
1.1 anton 2340: doc-2*
1.21 crook 2341: doc-d2*
1.1 anton 2342: doc-2/
1.21 crook 2343: doc-d2/
2344:
2345: @node Double precision, Numeric comparison, Bitwise operations, Arithmetic
2346: @subsection Double precision
2347: @cindex double precision arithmetic words
2348:
2349: @xref{Number Conversion} for the rules used by the text interpreter for
2350: recognising double-precision integers.
2351:
2352: A double precision number is represented by a cell pair, with the most
1.26 crook 2353: significant digit at the TOS. It is trivial to convert an unsigned
2354: single to an (unsigned) double; simply push a @code{0} onto the
2355: TOS. Since numbers are represented by Gforth using 2's complement
2356: arithmetic, converting a signed single to a (signed) double requires
2357: sign-extension across the most significant digit. This can be achieved
2358: using @code{s>d}. The moral of the story is that you cannot convert a
2359: number without knowing whether it represents an unsigned or a
2360: signed number.
1.21 crook 2361:
2362: doc-s>d
2363: doc-d+
2364: doc-d-
2365: doc-dnegate
2366: doc-dabs
2367: doc-dmin
2368: doc-dmax
2369:
2370: @node Numeric comparison, Mixed precision, Double precision, Arithmetic
2371: @subsection Numeric comparison
2372: @cindex numeric comparison words
2373:
1.28 ! crook 2374: doc-<
! 2375: doc-<=
! 2376: doc-<>
! 2377: doc-=
! 2378: doc->
! 2379: doc->=
! 2380:
1.21 crook 2381: doc-0<
1.23 crook 2382: doc-0<=
1.21 crook 2383: doc-0<>
2384: doc-0=
1.23 crook 2385: doc-0>
2386: doc-0>=
1.28 ! crook 2387:
! 2388: doc-u<
! 2389: doc-u<=
! 2390: @comment TODO why u<> and u= .. they are the same as <> and =
! 2391: doc-u<>
! 2392: doc-u=
! 2393: doc-u>
! 2394: doc-u>=
! 2395:
! 2396: doc-within
! 2397:
! 2398: doc-d<
! 2399: doc-d<=
! 2400: doc-d<>
! 2401: doc-d=
! 2402: doc-d>
! 2403: doc-d>=
1.23 crook 2404:
1.21 crook 2405: doc-d0<
1.23 crook 2406: doc-d0<=
2407: doc-d0<>
1.21 crook 2408: doc-d0=
1.23 crook 2409: doc-d0>
2410: doc-d0>=
2411:
1.21 crook 2412: doc-du<
1.28 ! crook 2413: doc-du<=
! 2414: doc-du<>
! 2415: doc-du=
! 2416: doc-du>
! 2417: doc-du>=
1.1 anton 2418:
1.21 crook 2419: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 2420: @subsection Mixed precision
2421: @cindex mixed precision arithmetic words
2422:
2423: doc-m+
2424: doc-*/
2425: doc-*/mod
2426: doc-m*
2427: doc-um*
2428: doc-m*/
2429: doc-um/mod
2430: doc-fm/mod
2431: doc-sm/rem
2432:
1.21 crook 2433: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 2434: @subsection Floating Point
2435: @cindex floating point arithmetic words
2436:
1.21 crook 2437: @xref{Number Conversion} for the rules used by the text interpreter for
2438: recognising floating-point numbers.
1.1 anton 2439:
2440: @cindex angles in trigonometric operations
2441: @cindex trigonometric operations
2442: Angles in floating point operations are given in radians (a full circle
1.26 crook 2443: has 2 pi radians). Gforth has a separate floating point
2444: stack, but the documentation uses the unified notation.
1.1 anton 2445:
2446: @cindex floating-point arithmetic, pitfalls
2447: Floating point numbers have a number of unpleasant surprises for the
2448: unwary (e.g., floating point addition is not associative) and even a few
2449: for the wary. You should not use them unless you know what you are doing
2450: or you don't care that the results you get are totally bogus. If you
2451: want to learn about the problems of floating point numbers (and how to
2452: avoid them), you might start with @cite{David Goldberg, What Every
2453: Computer Scientist Should Know About Floating-Point Arithmetic, ACM
1.17 anton 2454: Computing Surveys 23(1):5@minus{}48, March 1991}
2455: (@url{http://www.validgh.com/goldberg/paper.ps}).
1.1 anton 2456:
1.21 crook 2457: doc-d>f
2458: doc-f>d
1.1 anton 2459: doc-f+
2460: doc-f-
2461: doc-f*
2462: doc-f/
2463: doc-fnegate
2464: doc-fabs
2465: doc-fmax
2466: doc-fmin
2467: doc-floor
2468: doc-fround
2469: doc-f**
2470: doc-fsqrt
2471: doc-fexp
2472: doc-fexpm1
2473: doc-fln
2474: doc-flnp1
2475: doc-flog
2476: doc-falog
2477: doc-fsin
2478: doc-fcos
2479: doc-fsincos
2480: doc-ftan
2481: doc-fasin
2482: doc-facos
2483: doc-fatan
2484: doc-fatan2
2485: doc-fsinh
2486: doc-fcosh
2487: doc-ftanh
2488: doc-fasinh
2489: doc-facosh
2490: doc-fatanh
1.21 crook 2491: doc-pi
1.28 ! crook 2492:
1.21 crook 2493: doc-f0<
1.28 ! crook 2494: doc-f0<=
! 2495: doc-f0<>
1.21 crook 2496: doc-f0=
1.28 ! crook 2497: doc-f0>
! 2498: doc-f0>=
! 2499:
1.21 crook 2500: doc-f<
2501: doc-f<=
2502: doc-f<>
2503: doc-f=
2504: doc-f>
2505: doc-f>=
1.28 ! crook 2506:
1.21 crook 2507: doc-f2*
2508: doc-f2/
2509: doc-1/f
2510: doc-f~
2511: doc-precision
2512: doc-set-precision
1.1 anton 2513:
2514: @node Stack Manipulation, Memory, Arithmetic, Words
2515: @section Stack Manipulation
2516: @cindex stack manipulation words
2517:
2518: @cindex floating-point stack in the standard
1.21 crook 2519: Gforth maintains a number of separate stacks:
2520:
2521: @itemize @bullet
2522: @item
2523: A data stack (aka parameter stack) -- for characters, cells,
2524: addresses, and double cells.
2525:
2526: @item
2527: A floating point stack -- for floating point numbers.
2528:
2529: @item
2530: A return stack -- for storing the return addresses of colon
2531: definitions and other data.
2532:
2533: @item
2534: A locals stack for storing local variables.
2535: @end itemize
2536:
2537: Whilst every sane Forth has a separate floating-point stack, it is not
2538: strictly required; an ANS Forth system could theoretically keep
2539: floating-point numbers on the data stack. As an additional difficulty,
2540: you don't know how many cells a floating-point number takes. It is
2541: reportedly possible to write words in a way that they work also for a
2542: unified stack model, but we do not recommend trying it. Instead, just
2543: say that your program has an environmental dependency on a separate
2544: floating-point stack.
2545:
2546: doc-floating-stack
1.1 anton 2547:
2548: @cindex return stack and locals
2549: @cindex locals and return stack
1.21 crook 2550: A Forth system is allowed to keep local variables on the
1.1 anton 2551: return stack. This is reasonable, as local variables usually eliminate
2552: the need to use the return stack explicitly. So, if you want to produce
1.21 crook 2553: a standard compliant program and you are using local variables in a
2554: word, forget about return stack manipulations in that word (refer to the
1.1 anton 2555: standard document for the exact rules).
2556:
2557: @menu
2558: * Data stack::
2559: * Floating point stack::
2560: * Return stack::
2561: * Locals stack::
2562: * Stack pointer manipulation::
2563: @end menu
2564:
2565: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
2566: @subsection Data stack
2567: @cindex data stack manipulation words
2568: @cindex stack manipulations words, data stack
2569:
2570: doc-drop
2571: doc-nip
2572: doc-dup
2573: doc-over
2574: doc-tuck
2575: doc-swap
1.21 crook 2576: doc-pick
1.1 anton 2577: doc-rot
2578: doc--rot
2579: doc-?dup
2580: doc-roll
2581: doc-2drop
2582: doc-2nip
2583: doc-2dup
2584: doc-2over
2585: doc-2tuck
2586: doc-2swap
2587: doc-2rot
2588:
2589: @node Floating point stack, Return stack, Data stack, Stack Manipulation
2590: @subsection Floating point stack
2591: @cindex floating-point stack manipulation words
2592: @cindex stack manipulation words, floating-point stack
2593:
2594: doc-fdrop
2595: doc-fnip
2596: doc-fdup
2597: doc-fover
2598: doc-ftuck
2599: doc-fswap
1.21 crook 2600: doc-fpick
1.1 anton 2601: doc-frot
2602:
2603: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
2604: @subsection Return stack
2605: @cindex return stack manipulation words
2606: @cindex stack manipulation words, return stack
2607:
2608: doc->r
2609: doc-r>
2610: doc-r@
2611: doc-rdrop
2612: doc-2>r
2613: doc-2r>
2614: doc-2r@
2615: doc-2rdrop
2616:
2617: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
2618: @subsection Locals stack
2619:
1.26 crook 2620: @comment TODO
1.21 crook 2621:
1.1 anton 2622: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
2623: @subsection Stack pointer manipulation
2624: @cindex stack pointer manipulation words
2625:
1.21 crook 2626: doc-sp0
2627: doc-s0
1.1 anton 2628: doc-sp@
2629: doc-sp!
1.21 crook 2630: doc-fp0
1.1 anton 2631: doc-fp@
2632: doc-fp!
1.21 crook 2633: doc-rp0
2634: doc-r0
1.1 anton 2635: doc-rp@
2636: doc-rp!
1.21 crook 2637: doc-lp0
2638: doc-l0
1.1 anton 2639: doc-lp@
2640: doc-lp!
2641:
2642: @node Memory, Control Structures, Stack Manipulation, Words
2643: @section Memory
1.26 crook 2644: @cindex memory words
1.1 anton 2645:
1.27 crook 2646: @cindex dictionary
2647: Forth definitions are organised in memory structures that are
2648: collectively called the @var{dictionary}. The dictionary can be
2649: considered as three logical memory regions:
2650:
2651: @itemize @bullet
2652: @item
2653: @cindex code space
2654: @cindex code dictionary
2655: Code space, also known as the @var{code dictionary}.
2656: @item
2657: @cindex name space
2658: @cindex name dictionary
2659: Name space, also known as the @var{name dictionary}@footnote{Sometimes,
2660: people use the term @var{dictionary} to simply refer to the name
2661: dictionary, because it is the one region that is used for looking up
2662: names, just as you would in a conventional dictionary.}.
2663: @item
2664: @cindex data space
2665: Data space
2666: @end itemize
2667:
2668: When you create a colon definition, the text interpreter compiles
2669: the definition itself into the code dictionary and compiles the name
2670: of the definition into the name dictionary, together with other
2671: information about the definition (such as its execution token).
2672:
2673: When you create a variable, the execution of @code{variable} will
2674: compile some code, assign once cell in data space, and compile the name
2675: of the variable into the name dictionary.
2676:
2677: @cindex memory regions - relationship between them
2678: ANS Forth does not specify the relationship between the three memory
2679: regions, and specifies that a Standard program must not access code or
2680: data space directly -- it may only access data space directly. In
2681: addition, the Standard defines what relationships you may and may not
2682: rely on when allocating regions in data space. These constraints are
2683: simply a reflection of the many diverse techniques that are used to
2684: implement Forth systems; understanding and following the requirements of
2685: the Standard allows you to write portable programs -- programs that run
2686: in the same way on any of these diverse systems. Another way of looking
2687: at this is to say that ANS Forth was designed to permit compliant Forth
2688: systems to be implemented in many diverse ways.
2689:
2690: @cindex memory regions - how they are assigned
2691: Here are some examples of the way in which name, code and data spaces
2692: are assigned:
2693:
2694: @itemize @bullet
2695: @item
2696: For a Forth system that runs from RAM under a general-purpose operating
2697: system, it can be convenient to interleave name, code and data spaces in
2698: a single contiguous memory region. This organisation can be
2699: memory-efficient (for example, because the relationship between the name
2700: dictionary entry and the associated code dictionary entry can be
2701: implicit, rather than requiring an explicit memory pointer to reference
2702: from the name dictionary and the code dictionary). This is the
2703: organisation used by Gforth, as this example@footnote{The addresses
2704: in the example have been truncated to fit it onto the page, and the
2705: addresses and data shown will not match the output from your system} shows:
2706: @example
2707: hex
2708: variable fred 123456 fred !
2709: variable jim abcd jim !
2710: : foo + / - ;
2711: ' fred 10 - 50 dump
2712: ..80: 5C 46 0E 40 84 66 72 65 - 64 20 20 20 20 20 20 20 \F.@.fred
2713: ..90: D0 9B 04 08 00 00 00 00 - 56 34 12 00 80 46 0E 40 ........V4...F.@
2714: ..A0: 83 6A 69 6D 20 20 20 20 - D0 9B 04 08 00 00 00 00 .jim ........
2715: ..B0: CD AB 00 00 9C 46 0E 40 - 83 66 6F 6F 20 20 20 20 .....F.@.foo
2716: ..C0: 80 9B 04 08 00 00 00 00 - E4 2E 05 08 0C 2F 05 08 ............./..
2717: @end example
2718:
2719: @item
2720: For a high-performance system running on a modern RISC processor with a
2721: modified Harvard architecture (one that has a unified main memory but
2722: separate instruction and data caches), it is desirable to separate
2723: processor instructions from processor data. This encourages a high cache
2724: density and therefore a high cache hit rate. The Forth code dictionary
2725: is not necessarily made up entirely of processor instructions; its
2726: nature is dependent upon the Forth implementation.
2727:
2728: @item
2729: A Forth compiler that runs on a segmented 8086 processor could be
2730: designed to interleave the name, code and data spaces within a single
2731: 64Kbyte segment. A more common implementation choice is to use a
2732: separate 64Kbyte segment for each region, which provides more memory
2733: overall but provides an address map in which only the data space is
2734: accessible.
2735:
2736: @item
2737: Microprocessors exist that run Forth (or many of the primitives required
2738: to implement the Forth virtual machine efficiently) directly. On these
2739: processors, the relationship between name, code and data spaces may be
2740: imposed as a side-effect of the microarchitecture of the processor.
2741:
2742: @item
2743: A Forth compiler that executes from ROM on an embedded system needs its
2744: data space separated from the name and code spaces so that the data
2745: space can be mapped to a RAM area.
2746:
2747: @item
2748: A Forth compiler that runs on an embedded system may have a requirement
2749: for a small memory footprint. On such a system it can be useful to
2750: separate the name space from the data and code spaces; once the
2751: application has been compiled, the name dictionary is no longer
2752: required@footnote{more strictly speaking, most applications can be
2753: designed so that this is the case}. The name dictionary can be deleted
2754: entirely, or could be stored in memory on a remote @var{host} system for
2755: debug and development purposes. In the latter case, the compiler running
2756: on the @var{target} system could implement a protocol across a
2757: communication link that would allow it to interrogate the name dictionary.
2758: @end itemize
2759:
1.1 anton 2760: @menu
1.27 crook 2761: * Reserving Data Space::
2762: * Memory Access::
2763: * Address Arithmetic::
2764: * Memory Blocks::
2765: * Dynamic Allocation::
1.1 anton 2766: @end menu
2767:
1.27 crook 2768:
2769: @node Reserving Data Space, Memory Access, Memory, Memory
2770: @subsection Reserving Data Space
2771: @cindex reserving data space
2772: @cindex data space - reserving some
2773:
2774: @cindex data space pointer - alignment
2775: These factors affect the alignment of @code{here}, the data
2776: space pointer:
2777:
2778: @itemize @bullet
2779: @item
2780: If the data-space pointer is aligned@footnote{In ANS Forth-speak,
2781: @var{aligned} implictly means @code{CELL}-aligned} before an
2782: @code{allot}, and a whole number of characters are reserved or released, it
2783: will remain aligned after the @code{allot}.
2784:
2785: @item
2786: If the data-space pointer is character-aligned before an @code{allot},
2787: and a whole number of cells are reserved or released, it will remain
2788: character-aligned after the @code{allot}.
2789:
2790: @item
2791: The initial contents of data space reserved using @code{allot} is
2792: undefined.
2793:
2794: @item
2795: Definitions created by @code{create}, @code{variable}, @code{2variable}
2796: return aligned addresses.
2797:
2798: @item
2799: After a definition is compiled or @code{align} is executed, the data
2800: space pointer is guaranteed to be aligned.
2801: @end itemize
2802:
2803: @cindex data space pointer - contiguous regions
2804: Contiguous regions may be created in data space under these conditions:
2805: @itemize @bullet
2806: @item
2807: The value of the data-space pointer, @code{here}, always defines the
2808: beginning of a contiguous region of data space.
2809:
2810: @item
2811: @code{CREATE} establishes the beginning of a contiguous region of data
2812: space (the @code{CREATE}d definition returns the initial address of the
2813: region).
2814:
2815: @item
2816: @code{variable} does @var{not} establish the beginning of a contiguous
2817: region in data space; @code{variable} followed by @code{allot} is not
2818: guaranteed to allocate data space region that is contiguous with the
2819: storage allocated by @code{variable}. Instead, use @code{create} --
2820: @xref{Simple Defining Words} for examples.
2821:
2822: @item
2823: Successive calls to @code{allot}, @code{,} (comma), @code{2,} (2-comma),
2824: @code{c,} (c-comma) and @code{align} reserve a single contiguous region
2825: in data space. The contiguity of the region is interrupted by compiling
2826: (or removing) definitions from the dictionary.
2827:
2828: @item
2829: The most recently reserved contiguous region may be released by calling
2830: @code{allot} with a negative argument, provided that the region has not
2831: been interrupted by compiling (or removing) definitions from the
2832: dictionary.
2833: @end itemize
2834:
2835: doc-here
2836: doc-unused
2837: doc-allot
2838: doc-c,
2839: doc-,
2840: doc-2,
2841:
1.28 ! crook 2842: @comment TODO may want to add description of similar user-space words,
! 2843: @comment but only if its accompanied by clear description of what user
! 2844: @comment space is and when it is useful. Words are udp uallot
1.27 crook 2845:
2846: @node Memory Access, Address Arithmetic, Reserving Data Space, Memory
1.1 anton 2847: @subsection Memory Access
2848: @cindex memory access words
2849:
2850: doc-@
2851: doc-!
2852: doc-+!
2853: doc-c@
2854: doc-c!
2855: doc-2@
2856: doc-2!
2857: doc-f@
2858: doc-f!
2859: doc-sf@
2860: doc-sf!
2861: doc-df@
2862: doc-df!
2863:
1.27 crook 2864: @node Address Arithmetic, Memory Blocks, Memory Access, Memory
2865: @subsection Address Arithmetic
1.1 anton 2866: @cindex address arithmetic words
2867:
2868: ANS Forth does not specify the sizes of the data types. Instead, it
2869: offers a number of words for computing sizes and doing address
2870: arithmetic. Basically, address arithmetic is performed in terms of
2871: address units (aus); on most systems the address unit is one byte. Note
2872: that a character may have more than one au, so @code{chars} is no noop
2873: (on systems where it is a noop, it compiles to nothing).
2874:
2875: @cindex alignment of addresses for types
2876: ANS Forth also defines words for aligning addresses for specific
2877: types. Many computers require that accesses to specific data types
2878: must only occur at specific addresses; e.g., that cells may only be
2879: accessed at addresses divisible by 4. Even if a machine allows unaligned
2880: accesses, it can usually perform aligned accesses faster.
2881:
2882: For the performance-conscious: alignment operations are usually only
2883: necessary during the definition of a data structure, not during the
2884: (more frequent) accesses to it.
2885:
2886: ANS Forth defines no words for character-aligning addresses. This is not
2887: an oversight, but reflects the fact that addresses that are not
2888: char-aligned have no use in the standard and therefore will not be
2889: created.
2890:
2891: @cindex @code{CREATE} and alignment
1.26 crook 2892: AND Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 2893: are cell-aligned; in addition, Gforth guarantees that these addresses
2894: are aligned for all purposes.
2895:
1.26 crook 2896: Note that the ANS Forth word @code{char} has nothing to do with address
2897: arithmetic.
1.1 anton 2898:
2899: doc-chars
2900: doc-char+
2901: doc-cells
2902: doc-cell+
2903: doc-cell
2904: doc-align
2905: doc-aligned
2906: doc-floats
2907: doc-float+
2908: doc-float
2909: doc-falign
2910: doc-faligned
2911: doc-sfloats
2912: doc-sfloat+
2913: doc-sfalign
2914: doc-sfaligned
2915: doc-dfloats
2916: doc-dfloat+
2917: doc-dfalign
2918: doc-dfaligned
2919: doc-maxalign
2920: doc-maxaligned
2921: doc-cfalign
2922: doc-cfaligned
2923: doc-address-unit-bits
2924:
1.27 crook 2925: @node Memory Blocks, Dynamic Allocation, Address Arithmetic, Memory
1.1 anton 2926: @subsection Memory Blocks
2927: @cindex memory block words
1.27 crook 2928: @cindex character strings - moving and copying
2929:
2930: Memory blocks often represent character strings; @xref{String Formats}
2931: for ways of storing character strings in memory. @xref{Displaying
2932: characters and strings} for other string-processing words.
1.1 anton 2933:
1.21 crook 2934: Some of these words work on address units (increments of @code{CELL}),
2935: and expect a @code{CELL}-aligned address. Others work on character units
2936: (increments of @code{CHAR}), and expect a @code{CHAR}-aligned
2937: address. Choose the correct operation depending upon your data type. If
2938: you are moving a block of memory (for example, a region reserved by
2939: @code{allot}) it is safe to use @code{move}, and it should be faster
2940: than using @code{cmove}. If you are moving (for example) a string
2941: compiled using @code{S"}, it is not portable to use @code{move}; the
2942: alignment of the string in memory could change, and the relationship
2943: between @code{CELL} and @code{CHAR} could change.
2944:
2945: When copying characters between overlapping memory regions, choose
2946: carefully between @code{cmove} and @code{cmove>}.
2947:
2948: You can only use any of these words @var{portably} to access data space.
2949:
1.27 crook 2950: @comment TODO - think the naming of the arguments is wrong for move
1.1 anton 2951: doc-move
2952: doc-erase
1.27 crook 2953: @comment TODO - think the naming of the arguments is wrong for cmove
1.1 anton 2954: doc-cmove
1.27 crook 2955: @comment TODO - think the naming of the arguments is wrong for cmove>
1.1 anton 2956: doc-cmove>
2957: doc-fill
2958: doc-blank
1.21 crook 2959: doc-compare
2960: doc-search
1.27 crook 2961: doc--trailing
2962: doc-/string
2963:
2964: @comment TODO examples
2965:
2966: @node Dynamic Allocation, ,Memory Blocks, Memory
2967: @subsection Dynamic Allocation of Memory
2968: @cindex dynamic allocation of memory
2969: @cindex memory-allocation word set
2970:
2971: The ANS Forth memory-allocation word set allows memory regions to be
2972: dynamically assigned, resized and released without affecting the data
2973: space pointer. In Gforth, these words are implemented using
2974: the standard C library calls malloc(), free() and resize().
2975:
2976: doc-allocate
2977: doc-free
2978: doc-resize
2979:
1.1 anton 2980:
1.26 crook 2981: @node Control Structures, Defining Words, Memory, Words
1.1 anton 2982: @section Control Structures
2983: @cindex control structures
2984:
2985: Control structures in Forth cannot be used in interpret state, only in
2986: compile state@footnote{More precisely, they have no interpretation
2987: semantics (@pxref{Interpretation and Compilation Semantics})}, i.e., in
2988: a colon definition. We do not like this limitation, but have not seen a
2989: satisfying way around it yet, although many schemes have been proposed.
2990:
2991: @menu
2992: * Selection::
2993: * Simple Loops::
2994: * Counted Loops::
2995: * Arbitrary control structures::
2996: * Calls and returns::
2997: * Exception Handling::
2998: @end menu
2999:
3000: @node Selection, Simple Loops, Control Structures, Control Structures
3001: @subsection Selection
3002: @cindex selection control structures
3003: @cindex control structures for selection
3004:
3005: @cindex @code{IF} control structure
3006: @example
3007: @var{flag}
3008: IF
3009: @var{code}
3010: ENDIF
3011: @end example
1.21 crook 3012: @noindent
1.1 anton 3013: or
3014: @example
3015: @var{flag}
3016: IF
3017: @var{code1}
3018: ELSE
3019: @var{code2}
3020: ENDIF
3021: @end example
3022:
3023: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
3024: standard, and @code{ENDIF} is not, although it is quite popular. We
3025: recommend using @code{ENDIF}, because it is less confusing for people
3026: who also know other languages (and is not prone to reinforcing negative
3027: prejudices against Forth in these people). Adding @code{ENDIF} to a
3028: system that only supplies @code{THEN} is simple:
3029: @example
1.21 crook 3030: : ENDIF POSTPONE THEN ; immediate
1.1 anton 3031: @end example
3032:
3033: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
3034: (adv.)} has the following meanings:
3035: @quotation
3036: ... 2b: following next after in order ... 3d: as a necessary consequence
3037: (if you were there, then you saw them).
3038: @end quotation
3039: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
3040: and many other programming languages has the meaning 3d.]
3041:
1.21 crook 3042: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 3043: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 3044: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 3045: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
3046: @file{compat/control.fs}.
3047:
3048: @cindex @code{CASE} control structure
3049: @example
3050: @var{n}
3051: CASE
3052: @var{n1} OF @var{code1} ENDOF
3053: @var{n2} OF @var{code2} ENDOF
3054: @dots{}
3055: ENDCASE
3056: @end example
3057:
3058: Executes the first @var{codei}, where the @var{ni} is equal to
3059: @var{n}. A default case can be added by simply writing the code after
3060: the last @code{ENDOF}. It may use @var{n}, which is on top of the stack,
3061: but must not consume it.
3062:
3063: @node Simple Loops, Counted Loops, Selection, Control Structures
3064: @subsection Simple Loops
3065: @cindex simple loops
3066: @cindex loops without count
3067:
3068: @cindex @code{WHILE} loop
3069: @example
3070: BEGIN
3071: @var{code1}
3072: @var{flag}
3073: WHILE
3074: @var{code2}
3075: REPEAT
3076: @end example
3077:
3078: @var{code1} is executed and @var{flag} is computed. If it is true,
3079: @var{code2} is executed and the loop is restarted; If @var{flag} is
3080: false, execution continues after the @code{REPEAT}.
3081:
3082: @cindex @code{UNTIL} loop
3083: @example
3084: BEGIN
3085: @var{code}
3086: @var{flag}
3087: UNTIL
3088: @end example
3089:
3090: @var{code} is executed. The loop is restarted if @code{flag} is false.
3091:
3092: @cindex endless loop
3093: @cindex loops, endless
3094: @example
3095: BEGIN
3096: @var{code}
3097: AGAIN
3098: @end example
3099:
3100: This is an endless loop.
3101:
3102: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
3103: @subsection Counted Loops
3104: @cindex counted loops
3105: @cindex loops, counted
3106: @cindex @code{DO} loops
3107:
3108: The basic counted loop is:
3109: @example
3110: @var{limit} @var{start}
3111: ?DO
3112: @var{body}
3113: LOOP
3114: @end example
3115:
3116: This performs one iteration for every integer, starting from @var{start}
1.21 crook 3117: and up to, but excluding @var{limit}. The counter, or @var{index}, can be
3118: accessed with @code{i}. For example, the loop:
1.1 anton 3119: @example
3120: 10 0 ?DO
3121: i .
3122: LOOP
3123: @end example
1.21 crook 3124: @noindent
3125: prints @code{0 1 2 3 4 5 6 7 8 9}
3126:
1.1 anton 3127: The index of the innermost loop can be accessed with @code{i}, the index
3128: of the next loop with @code{j}, and the index of the third loop with
3129: @code{k}.
3130:
3131: doc-i
3132: doc-j
3133: doc-k
3134:
3135: The loop control data are kept on the return stack, so there are some
1.21 crook 3136: restrictions on mixing return stack accesses and counted loop words. In
3137: particuler, if you put values on the return stack outside the loop, you
3138: cannot read them inside the loop@footnote{well, not in a way that is
3139: portable.}. If you put values on the return stack within a loop, you
3140: have to remove them before the end of the loop and before accessing the
3141: index of the loop.
1.1 anton 3142:
3143: There are several variations on the counted loop:
3144:
1.21 crook 3145: @itemize @bullet
3146: @item
3147: @code{LEAVE} leaves the innermost counted loop immediately; execution
3148: continues after the associated @code{LOOP} or @code{NEXT}. For example:
3149:
3150: @example
3151: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
3152: @end example
3153: prints @code{0 1 2 3}
3154:
1.1 anton 3155:
1.21 crook 3156: @item
3157: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
3158: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
3159: return stack so @code{EXIT} can get to its return address. For example:
3160:
3161: @example
3162: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
3163: @end example
3164: prints @code{0 1 2 3}
3165:
3166:
3167: @item
1.1 anton 3168: If @var{start} is greater than @var{limit}, a @code{?DO} loop is entered
3169: (and @code{LOOP} iterates until they become equal by wrap-around
3170: arithmetic). This behaviour is usually not what you want. Therefore,
3171: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
3172: @code{?DO}), which do not enter the loop if @var{start} is greater than
3173: @var{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
3174: unsigned loop parameters.
3175:
1.21 crook 3176: @item
3177: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
3178: the loop, independent of the loop parameters. Do not use @code{DO}, even
3179: if you know that the loop is entered in any case. Such knowledge tends
3180: to become invalid during maintenance of a program, and then the
3181: @code{DO} will make trouble.
3182:
3183: @item
1.1 anton 3184: @code{LOOP} can be replaced with @code{@var{n} +LOOP}; this updates the
3185: index by @var{n} instead of by 1. The loop is terminated when the border
3186: between @var{limit-1} and @var{limit} is crossed. E.g.:
3187:
1.21 crook 3188: @example
3189: 4 0 +DO i . 2 +LOOP
3190: @end example
3191: @noindent
3192: prints @code{0 2}
3193:
3194: @example
3195: 4 1 +DO i . 2 +LOOP
3196: @end example
3197: @noindent
3198: prints @code{1 3}
1.1 anton 3199:
3200:
3201: @cindex negative increment for counted loops
3202: @cindex counted loops with negative increment
3203: The behaviour of @code{@var{n} +LOOP} is peculiar when @var{n} is negative:
3204:
1.21 crook 3205: @example
3206: -1 0 ?DO i . -1 +LOOP
3207: @end example
3208: @noindent
3209: prints @code{0 -1}
1.1 anton 3210:
1.21 crook 3211: @example
3212: 0 0 ?DO i . -1 +LOOP
3213: @end example
3214: prints nothing.
1.1 anton 3215:
3216: Therefore we recommend avoiding @code{@var{n} +LOOP} with negative
3217: @var{n}. One alternative is @code{@var{u} -LOOP}, which reduces the
3218: index by @var{u} each iteration. The loop is terminated when the border
3219: between @var{limit+1} and @var{limit} is crossed. Gforth also provides
3220: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
3221:
1.21 crook 3222: @example
3223: -2 0 -DO i . 1 -LOOP
3224: @end example
3225: @noindent
3226: prints @code{0 -1}
1.1 anton 3227:
1.21 crook 3228: @example
3229: -1 0 -DO i . 1 -LOOP
3230: @end example
3231: @noindent
3232: prints @code{0}
3233:
3234: @example
3235: 0 0 -DO i . 1 -LOOP
3236: @end example
3237: @noindent
3238: prints nothing.
1.1 anton 3239:
1.21 crook 3240: @end itemize
1.1 anton 3241:
3242: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 3243: @code{-LOOP} are not defined in ANS Forth. However, an implementation
3244: for these words that uses only standard words is provided in
3245: @file{compat/loops.fs}.
1.1 anton 3246:
3247:
3248: @cindex @code{FOR} loops
1.26 crook 3249: Another counted loop is:
1.1 anton 3250: @example
3251: @var{n}
3252: FOR
3253: @var{body}
3254: NEXT
3255: @end example
3256: This is the preferred loop of native code compiler writers who are too
1.26 crook 3257: lazy to optimize @code{?DO} loops properly. This loop structure is not
3258: defined in ANS Forth. In Gforth, this loop iterates @var{n+1} times;
3259: @code{i} produces values starting with @var{n} and ending with 0. Other
3260: Forth systems may behave differently, even if they support @code{FOR}
3261: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 3262:
3263: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
3264: @subsection Arbitrary control structures
3265: @cindex control structures, user-defined
3266:
3267: @cindex control-flow stack
3268: ANS Forth permits and supports using control structures in a non-nested
3269: way. Information about incomplete control structures is stored on the
3270: control-flow stack. This stack may be implemented on the Forth data
3271: stack, and this is what we have done in Gforth.
3272:
3273: @cindex @code{orig}, control-flow stack item
3274: @cindex @code{dest}, control-flow stack item
3275: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
3276: entry represents a backward branch target. A few words are the basis for
3277: building any control structure possible (except control structures that
3278: need storage, like calls, coroutines, and backtracking).
3279:
3280: doc-if
3281: doc-ahead
3282: doc-then
3283: doc-begin
3284: doc-until
3285: doc-again
3286: doc-cs-pick
3287: doc-cs-roll
3288:
1.21 crook 3289: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
3290: manipulate the control-flow stack in a portable way. Without them, you
3291: would need to know how many stack items are occupied by a control-flow
3292: entry (many systems use one cell. In Gforth they currently take three,
3293: but this may change in the future).
3294:
1.1 anton 3295: Some standard control structure words are built from these words:
3296:
3297: doc-else
3298: doc-while
3299: doc-repeat
3300:
3301: Gforth adds some more control-structure words:
3302:
3303: doc-endif
3304: doc-?dup-if
3305: doc-?dup-0=-if
3306:
3307: Counted loop words constitute a separate group of words:
3308:
3309: doc-?do
3310: doc-+do
3311: doc-u+do
3312: doc--do
3313: doc-u-do
3314: doc-do
3315: doc-for
3316: doc-loop
3317: doc-+loop
3318: doc--loop
3319: doc-next
3320: doc-leave
3321: doc-?leave
3322: doc-unloop
3323: doc-done
3324:
1.21 crook 3325: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
3326: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 3327: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
3328: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
3329: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
3330: resolved (by using one of the loop-ending words or @code{DONE}).
3331:
1.26 crook 3332: Another group of control structure words are:
1.1 anton 3333:
3334: doc-case
3335: doc-endcase
3336: doc-of
3337: doc-endof
3338:
1.21 crook 3339: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
3340: @code{CS-ROLL}.
1.1 anton 3341:
3342: @subsubsection Programming Style
3343:
3344: In order to ensure readability we recommend that you do not create
3345: arbitrary control structures directly, but define new control structure
3346: words for the control structure you want and use these words in your
1.26 crook 3347: program. For example, instead of writing:
1.1 anton 3348:
3349: @example
1.26 crook 3350: BEGIN
1.1 anton 3351: ...
1.26 crook 3352: IF [ 1 CS-ROLL ]
1.1 anton 3353: ...
1.26 crook 3354: AGAIN THEN
1.1 anton 3355: @end example
3356:
1.21 crook 3357: @noindent
1.1 anton 3358: we recommend defining control structure words, e.g.,
3359:
3360: @example
1.26 crook 3361: : WHILE ( DEST -- ORIG DEST )
3362: POSTPONE IF
3363: 1 CS-ROLL ; immediate
3364:
3365: : REPEAT ( orig dest -- )
3366: POSTPONE AGAIN
3367: POSTPONE THEN ; immediate
1.1 anton 3368: @end example
3369:
1.21 crook 3370: @noindent
1.1 anton 3371: and then using these to create the control structure:
3372:
3373: @example
1.26 crook 3374: BEGIN
1.1 anton 3375: ...
1.26 crook 3376: WHILE
1.1 anton 3377: ...
1.26 crook 3378: REPEAT
1.1 anton 3379: @end example
3380:
3381: That's much easier to read, isn't it? Of course, @code{REPEAT} and
3382: @code{WHILE} are predefined, so in this example it would not be
3383: necessary to define them.
3384:
3385: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
3386: @subsection Calls and returns
3387: @cindex calling a definition
3388: @cindex returning from a definition
3389:
1.3 anton 3390: @cindex recursive definitions
3391: A definition can be called simply be writing the name of the definition
1.26 crook 3392: to be called. Normally a definition is invisible during its own
1.3 anton 3393: definition. If you want to write a directly recursive definition, you
1.26 crook 3394: can use @code{recursive} to make the current definition visible, or
3395: @code{recurse} to call the current definition directly.
1.3 anton 3396:
3397: doc-recursive
3398: doc-recurse
3399:
1.21 crook 3400: @comment TODO add example of the two recursion methods
1.12 anton 3401: @quotation
3402: @progstyle
3403: I prefer using @code{recursive} to @code{recurse}, because calling the
3404: definition by name is more descriptive (if the name is well-chosen) than
3405: the somewhat cryptic @code{recurse}. E.g., in a quicksort
3406: implementation, it is much better to read (and think) ``now sort the
3407: partitions'' than to read ``now do a recursive call''.
3408: @end quotation
1.3 anton 3409:
1.21 crook 3410: @comment TODO maybe move deferred words to Defining Words section and x-ref
3411: @comment from here.. that is where these two are glossed.
3412:
1.3 anton 3413: For mutual recursion, use @code{defer}red words, like this:
3414:
3415: @example
1.28 ! crook 3416: Defer foo
1.3 anton 3417:
3418: : bar ( ... -- ... )
3419: ... foo ... ;
3420:
3421: :noname ( ... -- ... )
3422: ... bar ... ;
3423: IS foo
3424: @end example
3425:
1.26 crook 3426: The current definition returns control to the calling definition when
3427: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 3428:
3429: doc-exit
3430: doc-;s
3431:
3432: @node Exception Handling, , Calls and returns, Control Structures
3433: @subsection Exception Handling
1.26 crook 3434: @cindex exceptions
1.1 anton 3435:
1.26 crook 3436: If your program detects a fatal error condition, the simplest action
3437: that it can take is to @code{quit}. This resets the return stack and
3438: restarts the text interpreter, but does not print any error message.
1.21 crook 3439:
1.26 crook 3440: The next stage in severity is to execute @code{abort}, which has the
3441: same effect as @code{quit}, with the addition that it resets the data
3442: stack.
1.1 anton 3443:
1.26 crook 3444: A slightly more sophisticated approach is use use @code{abort"}, which
3445: compiles a string to be used as an error message and does a conditional
3446: @code{abort} at run-time. For example:
1.1 anton 3447:
1.26 crook 3448: @example
3449: @kbd{: checker abort" That flag was true" ." A false flag" ;<return>} ok
3450: @kbd{0 checker<return>} A false flag ok
3451: @kbd{1 checker<return>}
3452: :1: That flag was true
3453: 1 checker
3454: ^^^^^^^
3455: $400D1648 throw
3456: $400E4660
3457: @end example
1.1 anton 3458:
1.26 crook 3459: These simple techniques allow a program to react to a fatal error
3460: condition, but they are not exactly user-friendly. The ANS Forth
3461: Exception word set provides the pair of words @code{throw} and
3462: @code{catch}, which can be used to provide sophisticated error-handling.
1.1 anton 3463:
1.26 crook 3464: @code{catch} has a similar behaviour to @code{execute}, in that it takes
3465: an @var{xt} as a parameter and starts execution of the xt. However,
3466: before passing control to the xt, @code{catch} pushes an
3467: @var{exception frame} onto the @var{exception stack}. This exception
3468: frame is used to restore the system to a known state if a detected error
3469: occurs during the execution of the xt. A typical way to use @code{catch}
3470: would be:
1.1 anton 3471:
1.26 crook 3472: @example
3473: ... ['] foo catch IF ...
3474: @end example
1.1 anton 3475:
1.26 crook 3476: Whilst @code{foo} executes, it can call other words to any level of
3477: nesting, as usual. If @code{foo} (and all the words that it calls)
3478: execute successfully, control will ultimately passes to the word following
3479: the @code{catch}, and there will be a @code{true} flag (0) at
3480: TOS. However, if any word detects an error, it can terminate the
3481: execution of @code{foo} by pushing an error code onto the stack and then
3482: performing a @code{throw}. The execution of @code{throw} will pass
3483: control to the word following the @code{catch}, but this time the TOS
3484: will hold the error code. Therefore, the @code{IF} in the example
3485: can be used to determine whether @code{foo} executed successfully.
1.1 anton 3486:
1.26 crook 3487: This simple example shows how you can use @code{throw} and @code{catch}
3488: to ``take over'' exception handling from the system:
1.1 anton 3489: @example
1.26 crook 3490: : my-div ['] / catch if ." DIVIDE ERROR" else ." OK.. " . then ;
1.1 anton 3491: @end example
3492:
1.26 crook 3493: The next example is more sophisticated and shows a multi-level
3494: @code{throw} and @code{catch}. To understand this example, start at the
3495: definition of @code{top-level} and work backwards:
3496:
1.1 anton 3497: @example
1.26 crook 3498: : lowest-level ( -- c )
3499: key dup 27 = if
3500: 1 throw \ ESCAPE key pressed
3501: else
3502: ." lowest-level successfull" CR
3503: then
3504: ;
3505:
3506: : lower-level ( -- c )
3507: lowest-level
3508: \ at this level consider a CTRL-U to be a fatal error
3509: dup 21 = if \ CTRL-U
3510: 2 throw
3511: else
3512: ." lower-level successfull" CR
3513: then
3514: ;
3515:
3516: : low-level ( -- c )
3517: ['] lower-level catch
3518: ?dup if
3519: \ error occurred - do we recognise it?
3520: dup 1 = if
3521: \ ESCAPE key pressed.. pretend it was an E
3522: [char] E
3523: else throw \ propogate the error upwards
3524: then
3525: then
3526: ." low-level successfull" CR
3527: ;
3528:
3529: : top-level ( -- )
3530: CR ['] low-level catch \ CATCH is used like EXECUTE
3531: ?dup if \ error occurred..
3532: ." Error " . ." occurred - contact your supplier"
3533: else
3534: ." The '" emit ." ' key was pressed" CR
3535: then
3536: ;
1.1 anton 3537: @end example
3538:
1.26 crook 3539: The ANS Forth document assigns @code{throw} codes thus:
1.1 anton 3540:
1.26 crook 3541: @itemize @bullet
3542: @item
3543: codes in the range -1 -- -255 are reserved to be assigned by the
3544: Standard. Assignments for codes in the range -1 -- -58 are currently
3545: documented in the Standard. In particular, @code{-1 throw} is equivalent
3546: to @code{abort} and @code{-2 throw} is equivalent to @code{abort"}.
3547: @item
3548: codes in the range -256 -- -4095 are reserved to be assigned by the system.
3549: @item
3550: all other codes may be assigned by programs.
3551: @end itemize
1.1 anton 3552:
1.26 crook 3553: Gforth provides the word @code{exception} as a mechanism for assigning
3554: system throw codes to applications. This allows multiple applications to
3555: co-exist in memory without any clash of @code{throw} codes. A definition
3556: of @code{exception} in ANS Forth is provided in
3557: @file{compat/exception.fs}.
1.1 anton 3558:
1.26 crook 3559: doc-quit
3560: doc-abort
3561: doc-abort"
1.1 anton 3562:
1.26 crook 3563: doc-catch
3564: doc-throw
3565: doc---exception-exception
1.1 anton 3566:
3567:
1.26 crook 3568: @c -------------------------------------------------------------
3569: @node Defining Words, The Text Interpreter, Control Structures, Words
3570: @section Defining Words
3571: @cindex defining words
1.1 anton 3572:
1.26 crook 3573: @comment TODO much more intro material here. 3 classes: colon defn, variables/constants
3574: @comment values, user-defined defining words.
1.1 anton 3575:
3576: @menu
1.27 crook 3577: * Simple Defining Words::
3578: * Colon Definitions::
3579: * User-defined Defining Words::
3580: * Supplying names::
3581: * Interpretation and Compilation Semantics::
1.1 anton 3582: @end menu
3583:
1.26 crook 3584: @node Simple Defining Words, Colon Definitions, Defining Words, Defining Words
3585: @subsection Simple Defining Words
3586: @cindex simple defining words
3587: @cindex defining words, simple
3588:
1.27 crook 3589: @comment TODO include examples of reserving data space for buffers
3590: @comment etc. using variable, allot, create and build up to the point
3591: @comment where it is appropriate to x-ref to the "structures" section.
3592:
1.26 crook 3593: doc-constant
3594: doc-2constant
3595: doc-fconstant
3596: doc-variable
3597: doc-2variable
3598: doc-fvariable
3599: doc-create
3600: doc-user
3601: doc-value
3602: doc-to
3603: doc-defer
3604: doc-is
1.28 ! crook 3605: doc-defers
! 3606: doc-alias
1.26 crook 3607:
3608: Definitions in ANS Forth for @code{defer}, @code{<is>} and
3609: @code{[is]} are provided in @file{compat/defer.fs}.
3610: @comment TODO - what do the two "is" words do?
1.1 anton 3611:
1.26 crook 3612: @node Colon Definitions, User-defined Defining Words, Simple Defining Words, Defining Words
3613: @subsection Colon Definitions
3614: @cindex colon definitions
1.1 anton 3615:
1.26 crook 3616: @example
3617: : name ( ... -- ... )
3618: word1 word2 word3 ;
3619: @end example
1.1 anton 3620:
1.26 crook 3621: creates a word called @code{name}, that, upon execution, executes
3622: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.1 anton 3623:
1.26 crook 3624: The explanation above is somewhat superficial. @xref{Interpretation and
3625: Compilation Semantics} for an in-depth discussion of some of the issues
3626: involved.
3627:
3628: doc-:
3629: doc-;
1.1 anton 3630:
1.26 crook 3631: @node User-defined Defining Words, Supplying names, Colon Definitions, Defining Words
3632: @subsection User-defined Defining Words
3633: @cindex user-defined defining words
3634: @cindex defining words, user-defined
1.1 anton 3635:
1.26 crook 3636: You can create new defining words simply by wrapping defining-time code
3637: around existing defining words and putting the sequence in a colon
3638: definition.
1.1 anton 3639:
1.26 crook 3640: @comment TODO example
1.1 anton 3641:
1.26 crook 3642: @cindex @code{CREATE} ... @code{DOES>}
3643: If you want the words defined with your defining words to behave
3644: differently from words defined with standard defining words, you can
3645: write your defining word like this:
1.1 anton 3646:
3647: @example
1.26 crook 3648: : def-word ( "name" -- )
3649: Create @var{code1}
3650: DOES> ( ... -- ... )
3651: @var{code2} ;
3652:
3653: def-word name
1.1 anton 3654: @end example
3655:
1.26 crook 3656: Technically, this fragment defines a defining word @code{def-word}, and
3657: a word @code{name}; when you execute @code{name}, the address of the
3658: body of @code{name} is put on the data stack and @var{code2} is executed
3659: (the address of the body of @code{name} is the address @code{HERE}
3660: returns immediately after the @code{CREATE}). The word @code{name} is
3661: sometimes called a @var{child} of @code{def-word}.
1.1 anton 3662:
1.26 crook 3663: In other words, if you make the following definitions:
1.1 anton 3664:
3665: @example
1.26 crook 3666: : def-word1 ( "name" -- )
3667: Create @var{code1} ;
3668:
3669: : action1 ( ... -- ... )
3670: @var{code2} ;
3671:
3672: def-word name1
1.1 anton 3673: @end example
3674:
1.26 crook 3675: Using @code{name1 action1} is equivalent to using @code{name}.
3676:
3677: The classic example is that you can define @code{Constant} in this way:
3678:
1.1 anton 3679: @example
1.26 crook 3680: : constant ( w "name" -- )
3681: create ,
3682: DOES> ( -- w )
3683: @@ ;
1.1 anton 3684: @end example
3685:
1.26 crook 3686: @comment that is the classic example.. maybe it should be earlier. There
3687: @comment is a beautiful description of how this works and what it does in
3688: @comment the Forthwrite 100th edition.
3689:
3690: When you create a constant with @code{5 constant five}, first a new word
3691: @code{five} is created, then the value 5 is laid down in the body of
3692: @code{five} with @code{,}. When @code{five} is invoked, the address of
3693: the body is put on the stack, and @code{@@} retrieves the value 5.
3694:
3695: @cindex stack effect of @code{DOES>}-parts
3696: @cindex @code{DOES>}-parts, stack effect
3697: In the example above the stack comment after the @code{DOES>} specifies
3698: the stack effect of the defined words, not the stack effect of the
3699: following code (the following code expects the address of the body on
3700: the top of stack, which is not reflected in the stack comment). This is
3701: the convention that I use and recommend (it clashes a bit with using
3702: locals declarations for stack effect specification, though).
1.1 anton 3703:
1.26 crook 3704: @subsubsection Applications of @code{CREATE..DOES>}
3705: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 3706:
1.26 crook 3707: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 3708:
1.26 crook 3709: @cindex factoring similar colon definitions
3710: When you see a sequence of code occurring several times, and you can
3711: identify a meaning, you will factor it out as a colon definition. When
3712: you see similar colon definitions, you can factor them using
3713: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
3714: that look very similar:
1.1 anton 3715: @example
1.26 crook 3716: : ori, ( reg-target reg-source n -- )
3717: 0 asm-reg-reg-imm ;
3718: : andi, ( reg-target reg-source n -- )
3719: 1 asm-reg-reg-imm ;
1.1 anton 3720: @end example
3721:
1.26 crook 3722: @noindent
3723: This could be factored with:
3724: @example
3725: : reg-reg-imm ( op-code -- )
3726: CREATE ,
3727: DOES> ( reg-target reg-source n -- )
3728: @@ asm-reg-reg-imm ;
3729:
3730: 0 reg-reg-imm ori,
3731: 1 reg-reg-imm andi,
3732: @end example
1.1 anton 3733:
1.26 crook 3734: @cindex currying
3735: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
3736: supply a part of the parameters for a word (known as @dfn{currying} in
3737: the functional language community). E.g., @code{+} needs two
3738: parameters. Creating versions of @code{+} with one parameter fixed can
3739: be done like this:
1.1 anton 3740: @example
1.26 crook 3741: : curry+ ( n1 -- )
3742: CREATE ,
3743: DOES> ( n2 -- n1+n2 )
3744: @@ + ;
3745:
3746: 3 curry+ 3+
3747: -2 curry+ 2-
1.1 anton 3748: @end example
3749:
1.26 crook 3750: @subsubsection The gory details of @code{CREATE..DOES>}
3751: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 3752:
1.26 crook 3753: doc-does>
1.1 anton 3754:
1.26 crook 3755: @cindex @code{DOES>} in a separate definition
3756: This means that you need not use @code{CREATE} and @code{DOES>} in the
3757: same definition; you can put the @code{DOES>}-part in a separate
3758: definition. This allows us to, e.g., select among different DOES>-parts:
3759: @example
3760: : does1
3761: DOES> ( ... -- ... )
3762: ... ;
1.1 anton 3763:
1.26 crook 3764: : does2
3765: DOES> ( ... -- ... )
3766: ... ;
1.1 anton 3767:
1.26 crook 3768: : def-word ( ... -- ... )
3769: create ...
3770: IF
3771: does1
3772: ELSE
3773: does2
3774: ENDIF ;
3775: @end example
1.1 anton 3776:
1.26 crook 3777: In this example, the selection of whether to use @code{does1} or
3778: @code{does2} is made at compile-time; at the time that the child word is
3779: @code{Create}d.
1.1 anton 3780:
1.26 crook 3781: @cindex @code{DOES>} in interpretation state
3782: In a standard program you can apply a @code{DOES>}-part only if the last
3783: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
3784: will override the behaviour of the last word defined in any case. In a
3785: standard program, you can use @code{DOES>} only in a colon
3786: definition. In Gforth, you can also use it in interpretation state, in a
3787: kind of one-shot mode; for example:
1.1 anton 3788: @example
1.26 crook 3789: CREATE name ( ... -- ... )
3790: @var{initialization}
3791: DOES>
3792: @var{code} ;
1.1 anton 3793: @end example
3794:
1.26 crook 3795: @noindent
3796: is equivalent to the standard:
1.1 anton 3797: @example
1.26 crook 3798: :noname
3799: DOES>
3800: @var{code} ;
3801: CREATE name EXECUTE ( ... -- ... )
3802: @var{initialization}
1.1 anton 3803: @end example
3804:
1.26 crook 3805: You can get the address of the body of a word with:
3806:
3807: doc->body
1.1 anton 3808:
1.26 crook 3809: @node Supplying names, Interpretation and Compilation Semantics, User-defined Defining Words, Defining Words
3810: @subsection Supplying names for the defined words
3811: @cindex names for defined words
3812: @cindex defining words, name parameter
1.1 anton 3813:
1.26 crook 3814: @cindex defining words, name given in a string
3815: By default, defining words take the names for the defined words from the
3816: input stream. Sometimes you want to supply the name from a string. You
3817: can do this with:
1.1 anton 3818:
1.26 crook 3819: doc-nextname
1.1 anton 3820:
1.26 crook 3821: For example:
1.1 anton 3822:
1.26 crook 3823: @example
3824: s" foo" nextname create
3825: @end example
3826: @noindent
3827: is equivalent to:
3828: @example
3829: create foo
3830: @end example
1.1 anton 3831:
1.26 crook 3832: @cindex defining words without name
3833: Sometimes you want to define an @var{anonymous word}; a word without a
3834: name. You can do this with:
1.1 anton 3835:
1.26 crook 3836: doc-:noname
1.1 anton 3837:
1.26 crook 3838: This leaves the execution token for the word on the stack after the
3839: closing @code{;}. Here's an example in which a deferred word is
3840: initialised with an @code{xt} from an anonymous colon definition:
3841: @example
3842: Defer deferred
3843: :noname ( ... -- ... )
3844: ... ;
3845: IS deferred
3846: @end example
1.1 anton 3847:
1.26 crook 3848: Gforth provides an alternative way of doing this, using two separate
3849: words:
1.1 anton 3850:
1.26 crook 3851: doc-noname
3852: @cindex execution token of last defined word
3853: doc-lastxt
1.1 anton 3854:
1.26 crook 3855: The previous example can be rewritten using @code{noname} and
3856: @code{lastxt}:
1.1 anton 3857:
1.26 crook 3858: @example
3859: Defer deferred
3860: noname : ( ... -- ... )
3861: ... ;
3862: lastxt IS deferred
3863: @end example
1.1 anton 3864:
1.26 crook 3865: @code{lastxt} also works when the last word was not defined as
3866: @code{noname}.
1.1 anton 3867:
3868:
1.26 crook 3869: @node Interpretation and Compilation Semantics, , Supplying names, Defining Words
3870: @subsection Interpretation and Compilation Semantics
3871: @cindex semantics, interpretation and compilation
1.1 anton 3872:
1.26 crook 3873: @cindex interpretation semantics
3874: The @dfn{interpretation semantics} of a word are what the text
3875: interpreter does when it encounters the word in interpret state. It also
3876: appears in some other contexts, e.g., the execution token returned by
3877: @code{' @var{word}} identifies the interpretation semantics of
3878: @var{word} (in other words, @code{' @var{word} execute} is equivalent to
3879: interpret-state text interpretation of @code{@var{word}}).
1.1 anton 3880:
1.26 crook 3881: @cindex compilation semantics
3882: The @dfn{compilation semantics} of a word are what the text interpreter
3883: does when it encounters the word in compile state. It also appears in
3884: other contexts, e.g, @code{POSTPONE @var{word}} compiles@footnote{In
3885: standard terminology, ``appends to the current definition''.} the
3886: compilation semantics of @var{word}.
1.1 anton 3887:
1.26 crook 3888: @cindex execution semantics
3889: The standard also talks about @dfn{execution semantics}. They are used
3890: only for defining the interpretation and compilation semantics of many
3891: words. By default, the interpretation semantics of a word are to
3892: @code{execute} its execution semantics, and the compilation semantics of
3893: a word are to @code{compile,} its execution semantics.@footnote{In
3894: standard terminology: The default interpretation semantics are its
3895: execution semantics; the default compilation semantics are to append its
3896: execution semantics to the execution semantics of the current
3897: definition.}
3898:
3899: @comment TODO expand, make it co-operate with new sections on text interpreter.
3900:
3901: @cindex immediate words
3902: @cindex compile-only words
3903: You can change the semantics of the most-recently defined word:
3904:
3905: doc-immediate
3906: doc-compile-only
3907: doc-restrict
3908:
3909: Note that ticking (@code{'}) a compile-only word gives an error
3910: (``Interpreting a compile-only word'').
1.1 anton 3911:
1.26 crook 3912: Gforth also allows you to define words with arbitrary combinations of
3913: interpretation and compilation semantics.
1.1 anton 3914:
1.26 crook 3915: doc-interpret/compile:
1.1 anton 3916:
1.26 crook 3917: This feature was introduced for implementing @code{TO} and @code{S"}. I
3918: recommend that you do not define such words, as cute as they may be:
3919: they make it hard to get at both parts of the word in some contexts.
3920: E.g., assume you want to get an execution token for the compilation
3921: part. Instead, define two words, one that embodies the interpretation
3922: part, and one that embodies the compilation part. Once you have done
3923: that, you can define a combined word with @code{interpret/compile:} for
3924: the convenience of your users.
1.1 anton 3925:
1.26 crook 3926: You might try to use this feature to provide an optimizing
3927: implementation of the default compilation semantics of a word. For
3928: example, by defining:
1.1 anton 3929: @example
1.26 crook 3930: :noname
3931: foo bar ;
3932: :noname
3933: POSTPONE foo POSTPONE bar ;
3934: interpret/compile: foobar
1.1 anton 3935: @end example
1.26 crook 3936:
1.23 crook 3937: @noindent
1.26 crook 3938: as an optimizing version of:
3939:
1.1 anton 3940: @example
1.26 crook 3941: : foobar
3942: foo bar ;
1.1 anton 3943: @end example
3944:
1.26 crook 3945: Unfortunately, this does not work correctly with @code{[compile]},
3946: because @code{[compile]} assumes that the compilation semantics of all
3947: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
3948: foobar} would compile the compilation semantics for the optimizing
3949: @code{foobar}, whereas it would compile the interpretation semantics for
3950: the non-optimizing @code{foobar}.
1.1 anton 3951:
1.26 crook 3952: @cindex state-smart words (are a bad idea)
3953: Some people try to use @var{state-smart} words to emulate the feature provided
3954: by @code{interpret/compile:} (words are state-smart if they check
3955: @code{STATE} during execution). E.g., they would try to code
3956: @code{foobar} like this:
1.1 anton 3957:
1.26 crook 3958: @example
3959: : foobar
3960: STATE @@
3961: IF ( compilation state )
3962: POSTPONE foo POSTPONE bar
3963: ELSE
3964: foo bar
3965: ENDIF ; immediate
3966: @end example
1.1 anton 3967:
1.26 crook 3968: Although this works if @code{foobar} is only processed by the text
3969: interpreter, it does not work in other contexts (like @code{'} or
3970: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
3971: for a state-smart word, not for the interpretation semantics of the
3972: original @code{foobar}; when you execute this execution token (directly
3973: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
3974: state, the result will not be what you expected (i.e., it will not
3975: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
3976: write them@footnote{For a more detailed discussion of this topic, see
3977: @cite{@code{State}-smartness -- Why it is Evil and How to Exorcise it} by Anton
3978: Ertl; presented at EuroForth '98 and available from
3979: @url{http://www.complang.tuwien.ac.at/papers/}}!
1.1 anton 3980:
1.26 crook 3981: @cindex defining words with arbitrary semantics combinations
3982: It is also possible to write defining words that define words with
3983: arbitrary combinations of interpretation and compilation semantics. In
3984: general, they look like this:
1.1 anton 3985:
1.26 crook 3986: @example
3987: : def-word
3988: create-interpret/compile
3989: @var{code1}
3990: interpretation>
3991: @var{code2}
3992: <interpretation
3993: compilation>
3994: @var{code3}
3995: <compilation ;
3996: @end example
1.1 anton 3997:
1.26 crook 3998: For a @var{word} defined with @code{def-word}, the interpretation
3999: semantics are to push the address of the body of @var{word} and perform
4000: @var{code2}, and the compilation semantics are to push the address of
4001: the body of @var{word} and perform @var{code3}. E.g., @code{constant}
4002: can also be defined like this (except that the defined constants don't
4003: behave correctly when @code{[compile]}d):
1.1 anton 4004:
1.26 crook 4005: @example
4006: : constant ( n "name" -- )
4007: create-interpret/compile
4008: ,
4009: interpretation> ( -- n )
4010: @@
4011: <interpretation
4012: compilation> ( compilation. -- ; run-time. -- n )
4013: @@ postpone literal
4014: <compilation ;
4015: @end example
1.1 anton 4016:
1.26 crook 4017: doc-create-interpret/compile
4018: doc-interpretation>
4019: doc-<interpretation
4020: doc-compilation>
4021: doc-<compilation
1.1 anton 4022:
1.26 crook 4023: Note that words defined with @code{interpret/compile:} and
4024: @code{create-interpret/compile} have an extended header structure that
4025: differs from other words; however, unless you try to access them with
4026: plain address arithmetic, you should not notice this. Words for
4027: accessing the header structure usually know how to deal with this; e.g.,
4028: @code{' word >body} also gives you the body of a word created with
4029: @code{create-interpret/compile}.
1.1 anton 4030:
1.27 crook 4031: doc-postpone
4032:
4033:
4034:
1.26 crook 4035: @c ----------------------------------------------------------
4036: @node The Text Interpreter, Tokens for Words, Defining Words, Words
4037: @section The Text Interpreter
4038: @cindex interpreter - outer
4039: @cindex text interpreter
4040: @cindex outer interpreter
1.1 anton 4041:
1.27 crook 4042: @comment index..
1.1 anton 4043:
1.27 crook 4044: When a Forth system starts up, the final stages of initialisation are to
4045: set @code{state} to 0 (interperetation state) and execute @code{quit},
4046: to start the text interpreter.
4047:
4048: The text interpreter is an endless loop that accepts input from various
4049: devices (by default the user input device -- the keyboard). A popular
4050: implementation technique for Forth is to implement a @var{forth virtual
4051: machine} using a loop called the @var{inner interpreter}. Because of
4052: this naming, the text interpreter is also known as the @var{outer
4053: interpreter}.
4054:
4055: The text interpreter works on input one line at a time. Starting at the
4056: beginning of the line, it skips leading spaces (called @var{delimiters})
4057: then parses a string (a sequence of non-space characters) until it
4058: either reaches a space character or it reaches the end of the
4059: line. Having parsed a string, it then makes two attempts to do something
4060: with it:
4061:
4062: @itemize @bullet
4063: @item
4064: It looks the string up in a dictionary of definitions. If the string is
4065: found in the dictionary, the string names a @var{definition} (also known
4066: as a @var{word}) and the dictionary search will return an @var{execution
4067: token} (xt) for the definition and some flags that show when the
4068: definition can be used legally. If the definition can be legally
4069: executed in @var{interpret} mode then the text interpreter will use the
4070: xt to execute it, otherwise it will issue an error message. The
4071: dictionary is described in more detail in <TODO>.
4072: @item
4073: If the string is not found in the dictionary, the text interpreter
4074: attempts to treat it as a number in the current radix (base 10 after
4075: initial startup). If the string represents a legal number in the current
4076: radix, the number is pushed onto the appropriate parameter stack.
4077: See @ref{Number Conversion} for details.
4078: @end itemize
4079: If both of these attempts fail, the remainder of the input line is
4080: discarded and the text interpreter isses an error message. If one of
4081: these attempts succeeds, the text interpreter repeats the parsing
4082: process until the end of the line has been reached. At this point,
4083: it prints the status message `` ok'' and waits for more input.
4084:
4085: There are two important things to note about the behaviour of the text
4086: interpreter:
4087:
4088: @itemize @bullet
4089: @item
4090: It processes each input string to completion before parsing additional
4091: characters from the input line.
4092: @item
4093: It keeps track of its position in the input line using a variable
4094: (called @code{>IN}, pronounced ``to-in''). The value of @code{>IN} can
4095: be modified by the execution of definitions in the input line. This
4096: means that definitions can ``trick'' the text interpreter either into
4097: skipping sections of the input line or into parsing a section of the
4098: input line more than once.
4099: @end itemize
1.21 crook 4100:
1.26 crook 4101: doc->in
1.27 crook 4102: doc-source
4103:
1.26 crook 4104: doc-tib
4105: doc-#tib
1.1 anton 4106:
1.26 crook 4107: @menu
4108: * Number Conversion::
4109: * Interpret/Compile states::
4110: * Literals::
4111: * Interpreter Directives::
1.27 crook 4112: * Input Sources::
1.26 crook 4113: @end menu
1.1 anton 4114:
4115:
1.26 crook 4116: @node Number Conversion, Interpret/Compile states, The Text Interpreter, The Text Interpreter
4117: @subsection Number Conversion
4118: @cindex number conversion
4119: @cindex double-cell numbers, input format
4120: @cindex input format for double-cell numbers
4121: @cindex single-cell numbers, input format
4122: @cindex input format for single-cell numbers
4123: @cindex floating-point numbers, input format
4124: @cindex input format for floating-point numbers
1.1 anton 4125:
1.26 crook 4126: If the text interpreter fails to find a particular string in the name
4127: dictionary, it attempts to convert it to a number using a set of rules.
1.1 anton 4128:
1.26 crook 4129: Let <digit> represent any character that is a legal digit in the current
4130: number base (for example, 0-9 when the number base is decimal or 0-9, A-F
4131: when the number base is hexadecimal).
1.1 anton 4132:
1.26 crook 4133: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 4134:
1.26 crook 4135: @comment TODO need to extend the next defn to support fp format
4136: Let @{+ | -@} represent the optional presence of either a @code{+} or
4137: @code{-} character.
1.1 anton 4138:
1.26 crook 4139: Let * represent any number of instances of the previous character
4140: (including none).
1.1 anton 4141:
1.26 crook 4142: Let any other character represent itself.
1.1 anton 4143:
1.26 crook 4144: Now, the conversion rules are:
1.21 crook 4145:
1.26 crook 4146: @itemize @bullet
4147: @item
4148: A string of the form <digit><digit>* is treated as a single-precision
4149: (CELL-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
4150: @item
4151: A string of the form -<digit><digit>* is treated as a single-precision
4152: (CELL-sized) negative integer, and is represented using 2's-complement
4153: arithmetic. Examples are -45 -5681 -0
4154: @item
4155: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
4156: (double-CELL-sized) positive integer. Examples are 3465. 3.465 34.65
4157: (and note that these all represent the same number).
4158: @item
4159: A string of the form -<digit><digit>*.<digit>* is treated as a
4160: double-precision (double-CELL-sized) negative integer, and is
4161: represented using 2's-complement arithmetic. Examples are -3465. -3.465
4162: -34.65 (and note that these all represent the same number).
4163: @item
4164: A string of the form @{+ | -@}<decimal digit>@{.@}<decimal digit>*@{e | E@}@{+
4165: | -@}<decimal digit><decimal digit>* is treated as floating-point
4166: number. Examples are 1e0 1.e 1.e0 +1e+0 (which all represent the same
4167: number) +12.E-4
4168: @end itemize
1.1 anton 4169:
1.26 crook 4170: By default, the number base used for integer number conversion is given
4171: by the contents of a variable named @code{BASE}. Base 10 (decimal) is
4172: always used for floating-point number conversion.
1.1 anton 4173:
1.26 crook 4174: doc-base
4175: doc-hex
4176: doc-decimal
1.1 anton 4177:
1.26 crook 4178: @cindex '-prefix for character strings
4179: @cindex &-prefix for decimal numbers
4180: @cindex %-prefix for binary numbers
4181: @cindex $-prefix for hexadecimal numbers
4182: Gforth allows you to override the value of @code{BASE} by using a prefix
4183: before the first digit of an (integer) number. Four prefixes are
4184: supported:
1.1 anton 4185:
1.26 crook 4186: @itemize @bullet
4187: @item
4188: @code{&} -- decimal number
4189: @item
4190: @code{%} -- binary number
4191: @item
4192: @code{$} -- hexadecimal number
4193: @item
4194: @code{'} -- base 256 number
4195: @end itemize
1.1 anton 4196:
1.26 crook 4197: Here are some examples, with the equivalent decimal number shown after
4198: in braces:
1.1 anton 4199:
1.26 crook 4200: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
4201: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
4202: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
4203: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 4204:
1.26 crook 4205: @cindex number conversion - traps for the unwary
4206: Number conversion has a number of traps for the unwary:
1.1 anton 4207:
1.26 crook 4208: @itemize @bullet
4209: @item
4210: You cannot determine the current number base using the code sequence
4211: @code{BASE @@ .} -- the number base is always 10 in the current number
4212: base. Instead, use something like @code{BASE @@ DECIMAL DUP . BASE !}
4213: @item
4214: If the number base is set to a value greater than 14 (for example,
4215: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
4216: it to be intepreted as either a single-precision integer or a
4217: floating-point number (Gforth treats it as an integer). The ambiguity
4218: can be resolved by explicitly stating the sign of the mantissa and/or
4219: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
4220: ambiguity arises; either representation will be treated as a
4221: floating-point number.
4222: @item
4223: There is a word @code{bin} but it does @var{not} set the number base!
4224: It is used to specify file types.
4225: @item
4226: ANS Forth requires the @code{.} of a double-precision number to
4227: be the final character in the string. Allowing the @code{.} to be
4228: anywhere after the first digit is a Gforth extension.
4229: @item
4230: The number conversion process does not check for overflow.
4231: @item
4232: In Gforth, number conversion to floating-point numbers always use base
4233: 10, irrespective of the value of @code{BASE}. In ANS Forth,
4234: conversion to floating-point numbers whilst the value of
4235: @code{BASE} is not 10 is an ambiguous condition.
4236: @end itemize
1.1 anton 4237:
4238:
1.26 crook 4239: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
4240: @subsection Interpret/Compile states
4241: @cindex Interpret/Compile states
1.1 anton 4242:
1.26 crook 4243: @comment TODO Intro blah.
1.1 anton 4244:
1.26 crook 4245: doc-state
4246: doc-[
4247: doc-]
1.1 anton 4248:
4249:
1.26 crook 4250: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
4251: @subsection Literals
4252: @cindex Literals
1.21 crook 4253:
1.26 crook 4254: @comment TODO Intro blah.
1.23 crook 4255:
1.26 crook 4256: doc-literal
4257: doc-]L
4258: doc-2literal
4259: doc-fliteral
1.1 anton 4260:
1.27 crook 4261: @node Interpreter Directives, Input Sources, Literals, The Text Interpreter
1.26 crook 4262: @subsection Interpreter Directives
4263: @cindex interpreter directives
1.1 anton 4264:
1.26 crook 4265: These words are usually used outside of definitions; for example, to
4266: control which parts of a source file are processed by the text
4267: interpreter. There are only a few ANS Forth Standard words, but Gforth
4268: supplements these with a rich set of immediate control structure words
4269: to compensate for the fact that the non-immediate versions can only be
4270: used in compile state (@pxref{Control Structures}).
1.1 anton 4271:
1.26 crook 4272: doc-[IF]
4273: doc-[ELSE]
4274: doc-[THEN]
4275: doc-[ENDIF]
1.1 anton 4276:
1.26 crook 4277: doc-[IFDEF]
4278: doc-[IFUNDEF]
1.1 anton 4279:
1.26 crook 4280: doc-[?DO]
4281: doc-[DO]
4282: doc-[FOR]
4283: doc-[LOOP]
4284: doc-[+LOOP]
4285: doc-[NEXT]
1.1 anton 4286:
1.26 crook 4287: doc-[BEGIN]
4288: doc-[UNTIL]
4289: doc-[AGAIN]
4290: doc-[WHILE]
4291: doc-[REPEAT]
1.1 anton 4292:
1.27 crook 4293:
4294: @node Input Sources, , Interpreter Directives, The Text Interpreter
4295: @subsection Input Sources
4296: @cindex input sources
4297: @cindex text interpreter - input sources
4298:
4299: The text interpreter can process input from these sources:
4300:
4301: @itemize @bullet
4302: @item
4303: The user input device -- the keyboard. This is the default input for the
4304: text interpreter when Forth is started up.
4305: @item
4306: A file, using the words described in @ref{Forth source files}.
4307: @item
4308: A block, using the words described in @ref{Blocks}.
4309: @item
4310: A text string, using @code{evaluate}.
4311: @end itemize
4312:
4313: A program can determine the current input device by checking the values
4314: of @code{source-id} and @code{blk}.
4315:
4316: doc-source-id
4317: doc-blk
4318:
4319: doc-save-input
4320: doc-restore-input
4321:
4322: doc-evaluate
4323:
4324:
1.26 crook 4325: @c -------------------------------------------------------------
4326: @node Tokens for Words, Word Lists, The Text Interpreter, Words
4327: @section Tokens for Words
4328: @cindex tokens for words
1.1 anton 4329:
1.28 ! crook 4330: This section describes the creation and use of tokens that represent
1.26 crook 4331: words on the stack (and in data space).
1.21 crook 4332:
1.26 crook 4333: Named words have interpretation and compilation semantics. Unnamed words
4334: just have execution semantics.
1.21 crook 4335:
1.26 crook 4336: @comment TODO ?normally interpretation semantics are the execution semantics.
4337: @comment this should all be covered in earlier ss
1.21 crook 4338:
1.26 crook 4339: @cindex execution token
4340: An @dfn{execution token} represents the execution semantics of an
4341: unnamed word. An execution token occupies one cell. As explained in
4342: @ref{Supplying names}, the execution token of the last word
4343: defined can be produced with @code{lastxt}.
1.1 anton 4344:
1.26 crook 4345: doc-execute
4346: doc-compile,
1.1 anton 4347:
1.26 crook 4348: @cindex code field address
4349: @cindex CFA
4350: In Gforth, the abstract data type @emph{execution token} is implemented
4351: as a code field address (CFA).
4352: @comment TODO note that the standard does not say what it represents..
4353: @comment and you cannot necessarily compile it in all Forths (eg native
4354: @comment compilers?).
1.1 anton 4355:
1.26 crook 4356: The interpretation semantics of a named word are also represented by an
4357: execution token. You can get it with:
1.1 anton 4358:
1.26 crook 4359: doc-[']
4360: doc-'
1.1 anton 4361:
1.26 crook 4362: For literals, you use @code{'} in interpreted code and @code{[']} in
4363: compiled code. Gforth's @code{'} and @code{[']} behave somewhat unusually
4364: by complaining about compile-only words. To get an execution token for a
4365: compiling word @var{X}, use @code{COMP' @var{X} drop} or @code{[COMP']
4366: @var{X} drop}.
1.1 anton 4367:
1.26 crook 4368: @cindex compilation token
4369: The compilation semantics are represented by a @dfn{compilation token}
4370: consisting of two cells: @var{w xt}. The top cell @var{xt} is an
4371: execution token. The compilation semantics represented by the
4372: compilation token can be performed with @code{execute}, which consumes
4373: the whole compilation token, with an additional stack effect determined
4374: by the represented compilation semantics.
1.1 anton 4375:
1.26 crook 4376: doc-[comp']
4377: doc-comp'
1.1 anton 4378:
1.26 crook 4379: You can compile the compilation semantics with @code{postpone,}. I.e.,
4380: @code{COMP' @var{word} POSTPONE,} is equivalent to @code{POSTPONE
4381: @var{word}}.
1.1 anton 4382:
1.26 crook 4383: doc-postpone,
1.1 anton 4384:
1.26 crook 4385: At present, the @var{w} part of a compilation token is an execution
4386: token, and the @var{xt} part represents either @code{execute} or
4387: @code{compile,}. However, don't rely on that knowledge, unless necessary;
4388: we may introduce unusual compilation tokens in the future (e.g.,
4389: compilation tokens representing the compilation semantics of literals).
1.21 crook 4390:
1.26 crook 4391: @cindex name token
4392: @cindex name field address
4393: @cindex NFA
4394: Named words are also represented by the @dfn{name token}, (@var{nt}). The abstract
4395: data type @emph{name token} is implemented as a name field address (NFA).
1.1 anton 4396:
1.26 crook 4397: doc-find-name
4398: doc-name>int
4399: doc-name?int
4400: doc-name>comp
4401: doc-name>string
1.1 anton 4402:
1.26 crook 4403: @c -------------------------------------------------------------
4404: @node Word Lists, Environmental Queries, Tokens for Words, Words
4405: @section Word Lists
4406: @cindex word lists
4407: @cindex name dictionary
1.1 anton 4408:
1.26 crook 4409: @cindex wid
4410: All definitions other than those created by @code{:noname} have an entry
4411: in the name dictionary. The name dictionary is fragmented into a number
4412: of parts, called @var{word lists}. A word list is identified by a
4413: cell-sized word list identifier (@var{wid}) in much the same way as a
4414: file is identified by a file handle. The numerical value of the wid has
4415: no (portable) meaning, and might change from session to session.
1.1 anton 4416:
1.26 crook 4417: @cindex compilation word list
4418: At any one time, a single word list is defined as the word list to which
4419: all new definitions will be added -- this is called the @var{compilation
4420: word list}. When Gforth is started, the compilation word list is the
4421: word list called @code{FORTH-WORDLIST}.
1.1 anton 4422:
1.26 crook 4423: @cindex search order stack
4424: Forth maintains a stack of word lists, representing the @var{search
4425: order}. When the name dictionary is searched (for example, when
4426: attempting to find a word's execution token during compilation), only
4427: those word lists that are currently in the search order are
4428: searched. The most recently-defined word in the word list at the top of
4429: the word list stack is searched first, and the search proceeds until
4430: either the word is located or the oldest definition in the word list at
4431: the bottom of the stack is reached. Definitions of the word may exist in
4432: more than one word lists; the search order determines which version will
4433: be found.
1.1 anton 4434:
1.26 crook 4435: The ANS Forth Standard ``Search order'' word set is intended to provide a
4436: set of low-level tools that allow various different schemes to be
4437: implemented. Gforth provides @code{vocabulary}, a traditional Forth
4438: word. @file{compat/vocabulary.fs} provides an implementation in ANS
4439: Standard Forth.
1.1 anton 4440:
1.27 crook 4441: @comment TODO: locals section refers to here, saying that every word list (aka
4442: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.1 anton 4443:
1.27 crook 4444: @comment the thisone- prefix is used to pick out the true definition of a
4445: @comment word from the source files, rather than some alias.
1.26 crook 4446: doc-forth-wordlist
4447: doc-definitions
4448: doc-get-current
4449: doc-set-current
4450: doc-get-order
1.27 crook 4451: doc---thisone-set-order
1.26 crook 4452: doc-wordlist
4453: doc-also
1.27 crook 4454: doc---thisone-forth
1.26 crook 4455: doc-only
1.27 crook 4456: doc---thisone-order
1.26 crook 4457: doc-previous
1.15 anton 4458:
1.26 crook 4459: doc-find
4460: doc-search-wordlist
1.15 anton 4461:
1.26 crook 4462: doc-words
4463: doc-vlist
1.1 anton 4464:
1.26 crook 4465: doc-mappedwordlist
4466: doc-root
4467: doc-vocabulary
4468: doc-seal
4469: doc-vocs
4470: doc-current
4471: doc-context
1.1 anton 4472:
1.26 crook 4473: @menu
4474: * Why use word lists?::
4475: * Word list examples::
4476: @end menu
4477:
4478: @node Why use word lists?, Word list examples, Word Lists, Word Lists
4479: @subsection Why use word lists?
4480: @cindex word lists - why use them?
4481:
4482: There are several reasons for using multiple word lists:
4483:
4484: @itemize @bullet
4485: @item
4486: To improve compilation speed by reducing the number of name dictionary
4487: entries that must be searched. This is achieved by creating a new
4488: word list that contains all of the definitions that are used in the
4489: definition of a Forth system but which would not usually be used by
4490: programs running on that system. That word list would be on the search
4491: list when the Forth system was compiled but would be removed from the
4492: search list for normal operation. This can be a useful technique for
4493: low-performance systems (for example, 8-bit processors in embedded
4494: systems) but is unlikely to be necessary in high-performance desktop
4495: systems.
4496: @item
4497: To prevent a set of words from being used outside the context in which
4498: they are valid. Two classic examples of this are an integrated editor
4499: (all of the edit commands are defined in a separate word list; the
4500: search order is set to the editor word list when the editor is invoked;
4501: the old search order is restored when the editor is terminated) and an
4502: integrated assembler (the op-codes for the machine are defined in a
4503: separate word list which is used when a @code{CODE} word is defined).
4504: @item
4505: To prevent a name-space clash between multiple definitions with the same
4506: name. For example, when building a cross-compiler you might have a word
4507: @code{IF} that generates conditional code for your target system. By
4508: placing this definition in a different word list you can control whether
4509: the host system's @code{IF} or the target system's @code{IF} get used in
4510: any particular context by controlling the order of the word lists on the
4511: search order stack.
4512: @end itemize
1.1 anton 4513:
1.26 crook 4514: @node Word list examples, ,Why use word lists?, Word Lists
4515: @subsection Word list examples
4516: @cindex word lists - examples
1.1 anton 4517:
1.26 crook 4518: Here is an example of creating and using a new wordlist using ANS
4519: Forth Standard words:
1.1 anton 4520:
4521: @example
1.26 crook 4522: wordlist constant my-new-words-wordlist
4523: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
1.21 crook 4524:
1.26 crook 4525: \ add it to the search order
4526: also my-new-words
1.21 crook 4527:
1.26 crook 4528: \ alternatively, add it to the search order and make it
4529: \ the compilation word list
4530: also my-new-words definitions
4531: \ type "order" to see the problem
1.21 crook 4532: @end example
4533:
1.26 crook 4534: The problem with this example is that @code{order} has no way to
4535: associate the name @code{my-new-words} with the wid of the word list (in
4536: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
4537: that has no associated name). There is no Standard way of associating a
4538: name with a wid.
4539:
4540: In Gforth, this example can be re-coded using @code{vocabulary}, which
4541: associates a name with a wid:
1.21 crook 4542:
1.26 crook 4543: @example
4544: vocabulary my-new-words
1.21 crook 4545:
1.26 crook 4546: \ add it to the search order
4547: my-new-words
1.21 crook 4548:
1.26 crook 4549: \ alternatively, add it to the search order and make it
4550: \ the compilation word list
4551: my-new-words definitions
4552: \ type "order" to see that the problem is solved
4553: @end example
1.23 crook 4554:
1.26 crook 4555: @c -------------------------------------------------------------
4556: @node Environmental Queries, Files, Word Lists, Words
4557: @section Environmental Queries
4558: @cindex environmental queries
1.21 crook 4559:
1.26 crook 4560: ANS Forth introduced the idea of ``environmental queries'' as a way
4561: for a program running on a system to determine certain characteristics of the system.
4562: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 4563:
1.26 crook 4564: The Standard requires that the name space used for environmental queries
4565: be distinct from the name space used for definitions.
1.21 crook 4566:
1.26 crook 4567: Typically, environmental queries are supported by creating a set of
4568: definitions in a word list that is @var{only} used during environmental
4569: queries; that is what Gforth does. There is no Standard way of adding
4570: definitions to the set of recognised environmental queries, but any
4571: implementation that supports the loading of optional word sets must have
4572: some mechanism for doing this (after loading the word set, the
4573: associated environmental query string must return @code{true}). In
4574: Gforth, the word list used to honour environmental queries can be
4575: manipulated just like any other word list.
1.21 crook 4576:
1.26 crook 4577: doc-environment?
4578: doc-environment-wordlist
1.21 crook 4579:
1.26 crook 4580: doc-gforth
4581: doc-os-class
1.21 crook 4582:
1.26 crook 4583: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
4584: returning two items on the stack, querying it using @code{environment?}
4585: will return an additional item; the @code{true} flag that shows that the
4586: string was recognised.
1.21 crook 4587:
1.26 crook 4588: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 4589:
1.26 crook 4590: Here are some examples of using environmental queries:
1.21 crook 4591:
1.26 crook 4592: @example
4593: s" address-unit-bits" environment? 0=
4594: [IF]
4595: cr .( environmental attribute address-units-bits unknown... ) cr
4596: [THEN]
1.21 crook 4597:
1.26 crook 4598: s" block" environment? [IF] DROP include block.fs [THEN]
1.21 crook 4599:
1.26 crook 4600: s" gforth" environment? [IF] 2DROP include compat/vocabulary.fs [THEN]
1.21 crook 4601:
1.26 crook 4602: s" gforth" environment? [IF] .( Gforth version ) TYPE
4603: [ELSE] .( Not Gforth..) [THEN]
4604: @end example
1.21 crook 4605:
4606:
1.26 crook 4607: Here is an example of adding a definition to the environment word list:
1.21 crook 4608:
1.26 crook 4609: @example
4610: get-current environment-wordlist set-current
4611: true constant block
4612: true constant block-ext
4613: set-current
4614: @end example
1.21 crook 4615:
1.26 crook 4616: You can see what definitions are in the environment word list like this:
1.21 crook 4617:
1.26 crook 4618: @example
4619: get-order 1+ environment-wordlist swap set-order words previous
4620: @end example
1.21 crook 4621:
4622:
1.26 crook 4623: @c -------------------------------------------------------------
4624: @node Files, Blocks, Environmental Queries, Words
4625: @section Files
1.28 ! crook 4626: @cindex files
! 4627: @cindex I/O - file-handling
1.21 crook 4628:
1.26 crook 4629: Gforth provides facilities for accessing files that are stored in the
4630: host operating system's file-system. Files that are processed by Gforth
4631: can be divided into two categories:
1.21 crook 4632:
1.23 crook 4633: @itemize @bullet
4634: @item
1.26 crook 4635: Files that are processed by the Text Interpreter (@var{Forth source files}).
1.23 crook 4636: @item
1.26 crook 4637: Files that are processed by some other program (@var{general files}).
4638: @end itemize
4639:
4640: @menu
4641: * Forth source files::
4642: * General files::
4643: * Search Paths::
4644: * Forth Search Paths::
4645: * General Search Paths::
4646: @end menu
4647:
1.21 crook 4648:
1.26 crook 4649: @c -------------------------------------------------------------
4650: @node Forth source files, General files, Files, Files
4651: @subsection Forth source files
4652: @cindex including files
4653: @cindex Forth source files
1.21 crook 4654:
1.26 crook 4655: The simplest way to interpret the contents of a file is to use one of
4656: these two formats:
1.21 crook 4657:
1.26 crook 4658: @example
4659: include mysource.fs
4660: s" mysource.fs" included
4661: @end example
1.21 crook 4662:
1.26 crook 4663: Sometimes you want to include a file only if it is not included already
4664: (by, say, another source file). In that case, you can use one of these
4665: fomats:
1.21 crook 4666:
1.26 crook 4667: @example
4668: require mysource.fs
4669: needs mysource.fs
4670: s" mysource.fs" required
4671: @end example
1.21 crook 4672:
1.26 crook 4673: @cindex stack effect of included files
4674: @cindex including files, stack effect
4675: I recommend that you write your source files such that interpreting them
4676: does not change the stack. This allows using these files with
4677: @code{required} and friends without complications. For example:
1.21 crook 4678:
1.26 crook 4679: @example
4680: 1 require foo.fs drop
4681: @end example
1.21 crook 4682:
1.26 crook 4683: doc-include-file
4684: doc-included
1.28 ! crook 4685: doc-included?
1.26 crook 4686: doc-include
4687: @comment TODO describe what happens on error. Describes how the require
4688: @comment stuff works and describe how to clear/reset the history (eg
1.28 ! crook 4689: @comment for debug). Add examples. Describe the scope of the file
! 4690: @comment history.
1.26 crook 4691: doc-required
4692: doc-require
4693: doc-needs
1.28 ! crook 4694: doc-init-included-files
1.21 crook 4695:
1.26 crook 4696: A definition in ANS Forth for @code{required} is provided in
4697: @file{compat/required.fs}.
1.21 crook 4698:
1.26 crook 4699: @c -------------------------------------------------------------
4700: @node General files, Search Paths, Forth source files, Files
4701: @subsection General files
4702: @cindex general files
4703: @cindex file-handling
1.21 crook 4704:
1.26 crook 4705: Files are opened/created by name and type. The following types are
4706: recognised:
1.1 anton 4707:
1.26 crook 4708: doc-r/o
4709: doc-r/w
4710: doc-w/o
4711: doc-bin
1.1 anton 4712:
1.26 crook 4713: When a file is opened/created, it returns a file identifier,
4714: @var{wfileid} that is used for all other file commands. All file
4715: commands also return a status value, @var{wior}, that is 0 for a
4716: successful operation and an implementation-defined non-zero value in the
4717: case of an error.
1.21 crook 4718:
1.26 crook 4719: doc-open-file
4720: doc-create-file
1.21 crook 4721:
1.26 crook 4722: doc-close-file
4723: doc-delete-file
4724: doc-rename-file
4725: doc-read-file
4726: doc-read-line
4727: doc-write-file
4728: doc-write-line
4729: doc-emit-file
4730: doc-flush-file
1.21 crook 4731:
1.26 crook 4732: doc-file-status
4733: doc-file-position
4734: doc-reposition-file
4735: doc-file-size
4736: doc-resize-file
1.21 crook 4737:
1.26 crook 4738: @c ---------------------------------------------------------
4739: @node Search Paths, Forth Search Paths, General files, Files
4740: @subsection Search Paths
4741: @cindex path for @code{included}
4742: @cindex file search path
4743: @cindex @code{include} search path
4744: @cindex search path for files
1.21 crook 4745:
1.28 ! crook 4746: @comment TODO what uses these search paths.. just include and friends?
1.26 crook 4747: If you specify an absolute filename (i.e., a filename starting with
4748: @file{/} or @file{~}, or with @file{:} in the second position (as in
4749: @samp{C:...})) for @code{included} and friends, that file is included
4750: just as you would expect.
1.21 crook 4751:
1.26 crook 4752: For relative filenames, Gforth uses a search path similar to Forth's
4753: search order (@pxref{Word Lists}). It tries to find the given filename
4754: in the directories present in the path, and includes the first one it
4755: finds. There are separate search paths for Forth source files and
4756: general files.
1.21 crook 4757:
1.26 crook 4758: If the search path contains the directory @file{.} (as it should), this
4759: refers to the directory that the present file was @code{included}
4760: from. This allows files to include other files relative to their own
4761: position (irrespective of the current working directory or the absolute
4762: position). This feature is essential for libraries consisting of
4763: several files, where a file may include other files from the library.
4764: It corresponds to @code{#include "..."} in C. If the current input
4765: source is not a file, @file{.} refers to the directory of the innermost
4766: file being included, or, if there is no file being included, to the
4767: current working directory.
1.21 crook 4768:
1.26 crook 4769: Use @file{~+} to refer to the current working directory (as in the
4770: @code{bash}).
1.1 anton 4771:
1.26 crook 4772: If the filename starts with @file{./}, the search path is not searched
4773: (just as with absolute filenames), and the @file{.} has the same meaning
4774: as described above.
1.1 anton 4775:
1.26 crook 4776: @c ---------------------------------------------------------
4777: @node Forth Search Paths, General Search Paths, Search Paths, Files
4778: @subsubsection Forth Search Paths
1.28 ! crook 4779: @cindex search path control - Forth
1.5 anton 4780:
1.26 crook 4781: The search path is initialized when you start Gforth (@pxref{Invoking
4782: Gforth}). You can display it and change it using these words:
1.5 anton 4783:
1.26 crook 4784: doc-.fpath
4785: doc-fpath+
4786: doc-fpath=
4787: doc-open-fpath-file
1.5 anton 4788:
1.26 crook 4789: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 4790:
1.26 crook 4791: @example
4792: fpath= /usr/lib/forth/|./
4793: require timer.fs
4794: @end example
1.5 anton 4795:
1.26 crook 4796: @c ---------------------------------------------------------
4797: @node General Search Paths, , Forth Search Paths, Files
4798: @subsubsection General Search Paths
4799: @cindex search path control - for user applications
1.5 anton 4800:
1.26 crook 4801: Your application may need to search files in several directories, like
4802: @code{included} does. To facilitate this, Gforth allows you to define
4803: and use your own search paths, by providing generic equivalents of the
4804: Forth search path words:
1.5 anton 4805:
1.26 crook 4806: doc-.path
4807: doc-path+
4808: doc-path=
4809: doc-open-path-file
1.5 anton 4810:
1.26 crook 4811: Here's an example of creating a search path:
1.5 anton 4812:
1.26 crook 4813: @example
4814: \ Make a buffer for the path:
4815: create mypath 100 chars , \ maximum length (is checked)
4816: 0 , \ real len
4817: 100 chars allot \ space for path
4818: @end example
1.5 anton 4819:
1.26 crook 4820: @c -------------------------------------------------------------
4821: @node Blocks, Other I/O, Files, Words
4822: @section Blocks
1.28 ! crook 4823: @cindex I/O - blocks
! 4824: @cindex blocks
! 4825:
! 4826: @comment TODO finish the TODOs below and add more index entries
! 4827:
! 4828: When you run Gforth on a modern desk-top computer, it runs under the
! 4829: control of an operating system which provides certain services. One of
! 4830: these services is @var{file services}, which allows Forth source code
! 4831: and data to be stored in files and read into Gforth (@pxref{Files}).
! 4832:
! 4833: Traditionally, Forth has been an important programming language on
! 4834: systems where it has interfaced directly to the underlying hardware with
! 4835: no intervening operating system. Forth provides a mechanism, called
! 4836: @var{blocks}, for accessing mass storage on such systems.
! 4837:
! 4838: A block is a 1024-byte data area, which can be used to hold data or
! 4839: Forth source code. No structure is imposed on the contents of the
! 4840: block. A block is identified by its number; blocks are numbered
! 4841: contiguously from 1 to an implementation-defined maximum.
! 4842:
! 4843: A typical system that used blocks but no operating system might use a
! 4844: single floppy-disk drive for mass storage, with the disks formatted to
! 4845: provide 256-byte sectors. Blocks would be implemented by assigning the
! 4846: first four sectors of the disk to block 1, the second four sectors to
! 4847: block 2 and so on, up to the limit of the capacity of the disk. The disk
! 4848: would not contain any file system information, just the set of blocks.
! 4849:
! 4850: On systems that do provide file services, blocks are typically
! 4851: implemented by storing a sequence of blocks within a single @var{blocks
! 4852: file}. The size of the blocks file will be an exact multiple of 1024
! 4853: bytes, corresponding to the number of blocks it contains. This is the
! 4854: mechanism that Gforth uses.
! 4855:
! 4856: Only 1 blocks file can be open at a time. If you use block words without
! 4857: having specified a blocks file, Gforth defaults to the blocks file
! 4858: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
! 4859: locate a blocks file (@pxref{Forth Search Paths}).
! 4860:
! 4861: When you read and write blocks under program control, Gforth uses a
! 4862: number of @var{block buffers} as intermediate storage. These buffers are
! 4863: not used when you use @code{load} to interpret the contents of a block.
! 4864:
! 4865: The behaviour of the block buffers is directly analagous to that of a
! 4866: cache. Each block buffer has three states:
! 4867:
! 4868: @itemize @bullet
! 4869: @item
! 4870: Unassigned
! 4871: @item
! 4872: Assigned-clean
! 4873: @item
! 4874: Assigned-dirty
! 4875: @end itemize
! 4876:
! 4877: Initially, all block buffers are @var{unassigned}. In order to access a
! 4878: block, the block (specified by its block number) must be assigned to a
! 4879: block buffer.
! 4880:
! 4881: The assignment of a block to a block buffer is performed by @code{block}
! 4882: or @code{buffer}. Use @code{block} when you wish to modify the existing
! 4883: contents of a block. Use @code{buffer} when you don't care about the
! 4884: existing contents of the block@footnote{The ANS Forth definition of
! 4885: @code{block} is intended not to cause disk I/O; if the data associated
! 4886: with the particular block is already stored in a block buffer due to an
! 4887: earlier @code{block} command, @code{buffer} will return that block
! 4888: buffer and the existing contents of the block will be
! 4889: available. Otherwise, @code{buffer} will simply assign a new, empty
! 4890: block buffer for the block}.
! 4891:
! 4892: Once a block has been assigned to a block buffer, the block buffer state
! 4893: becomes @var{assigned-clean}. Data can now be manipulated within the
! 4894: block buffer.
! 4895:
! 4896: When the contents of a block buffer is changed it is necessary,
! 4897: @i{before calling} @code{block} @i{or} @code{buffer} @i{again}, to
! 4898: either abandon the changes (by doing nothing) or commit the changes,
! 4899: using @code{update}. Using @code{update} does not change the blocks
! 4900: file; it simply changes a block buffer's state to @var{assigned-dirty}.
! 4901:
! 4902: The word @code{flush} causes all @var{assigned-dirty} blocks to be
! 4903: written back to the blocks file on disk. Leaving Gforth using @code{bye}
! 4904: also causes a @code{flush} to be performed.
! 4905:
! 4906: In Gforth, @code{block} and @code{buffer} use a @var{direct-mapped}
! 4907: algorithm to assign a block buffer to a block. That means that any
! 4908: particular block can only be assigned to one specific block buffer,
! 4909: called (for the particular operation) the @var{victim buffer}. If the
! 4910: victim buffer is @var{unassigned} or @var{assigned-clean} it can be
! 4911: allocated to the new block immediately. If it is @var{assigned-dirty}
! 4912: its current contents must be written out to disk before it can be
! 4913: allocated to the new block.
! 4914:
! 4915: Although no structure is imposed on the contents of a block, it is
! 4916: traditional to display the contents as 16 lines each of 64 characters. A
! 4917: block provides a single, continuous stream of input (for example, it
! 4918: acts as a single parse area) -- there are no end-of-line characters
! 4919: within a block, and no end-of-file character at the end of a
! 4920: block. There are two consequences of this:
1.26 crook 4921:
1.28 ! crook 4922: @itemize @bullet
! 4923: @item
! 4924: The last character of one line wraps straight into the first character
! 4925: of the following line
! 4926: @item
! 4927: The word @code{\} -- comment to end of line -- requires special
! 4928: treatment; in the context of a block it causes all characters until the
! 4929: end of the current 64-character ``line'' to be ignored.
! 4930: @end itemize
! 4931:
! 4932: In Gforth, when you use @code{block} with a non-existent block number,
! 4933: the current block file will be extended to the appropriate size and the
! 4934: block buffer will be initialised with spaces.
! 4935:
! 4936: Gforth doesn't encourage the use of blocks@footnote{See Frank Sergeant's
! 4937: Pygmy Forth to see just how well blocks can be integrated into a Forth
! 4938: programming environment}; the mechanism is only provided for backward
! 4939: compatibility -- ANS Forth requires blocks to be available when files
! 4940: are.
! 4941:
! 4942: Common techniques that are used when working with blocks include:
! 4943:
! 4944: @itemize @bullet
! 4945: @item
! 4946: A screen editor that allows you to edit blocks without leaving the Forth
! 4947: environment.
! 4948: @item
! 4949: Shadow screens; where every code block has an associated block
! 4950: containing comments (for example: code in odd block numbers, comments in
! 4951: even block numbers). Typically, the block editor provides a convenient
! 4952: mechanism to toggle between code and comments.
! 4953: @item
! 4954: Load blocks; a single block (typically block 1) contains a number of
! 4955: @code{thru} commands which @code{load} the whole of the application.
! 4956: @item
! 4957: Chaining blocks; a block terminates with a @code{-->} so that a whole
! 4958: application can be @code{load}ed by @code{load}ing a single block.
! 4959: @end itemize
1.26 crook 4960:
4961:
4962: @comment TODO what about errors on open-blocks?
4963: doc-open-blocks
4964: doc-use
4965: doc-get-block-fid
4966: doc-block-position
1.28 ! crook 4967:
! 4968: doc-scr
! 4969: doc-list
! 4970:
! 4971: doc---block-block
! 4972: doc-buffer
! 4973:
1.26 crook 4974: doc-update
1.28 ! crook 4975: doc-updated?
1.26 crook 4976: doc-save-buffers
4977: doc-empty-buffers
4978: doc-empty-buffer
4979: doc-flush
1.28 ! crook 4980:
1.26 crook 4981: doc-load
4982: doc-thru
4983: doc-+load
4984: doc-+thru
4985: doc---block--->
4986: doc-block-included
4987:
4988: @c -------------------------------------------------------------
4989: @node Other I/O, Programming Tools, Blocks, Words
4990: @section Other I/O
1.28 ! crook 4991: @cindex I/O - keyboard and display
1.26 crook 4992:
4993: @menu
4994: * Simple numeric output:: Predefined formats
4995: * Formatted numeric output:: Formatted (pictured) output
4996: * String Formats:: How Forth stores strings in memory
4997: * Displaying characters and strings:: Other stuff
4998: * Input:: Input
4999: @end menu
5000:
5001: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
5002: @subsection Simple numeric output
1.28 ! crook 5003: @cindex numeric output - simple/free-format
1.5 anton 5004:
1.26 crook 5005: The simplest output functions are those that display numbers from the
5006: data or floating-point stacks. Floating-point output is always displayed
5007: using base 10. Numbers displayed from the data stack use the value stored
5008: in @code{base}.
1.5 anton 5009:
1.26 crook 5010: doc-.
5011: doc-dec.
5012: doc-hex.
5013: doc-u.
5014: doc-.r
5015: doc-u.r
5016: doc-d.
5017: doc-ud.
5018: doc-d.r
5019: doc-ud.r
5020: doc-f.
5021: doc-fe.
5022: doc-fs.
1.5 anton 5023:
1.26 crook 5024: Examples of printing the number 1234.5678E23 in the different floating-point output
5025: formats are shown below:
1.5 anton 5026:
5027: @example
1.26 crook 5028: f. 123456779999999000000000000.
5029: fe. 123.456779999999E24
5030: fs. 1.23456779999999E26
1.5 anton 5031: @end example
5032:
5033:
1.26 crook 5034: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
5035: @subsection Formatted numeric output
1.28 ! crook 5036: @cindex formatted numeric output
1.26 crook 5037: @cindex pictured numeric output
1.28 ! crook 5038: @cindex numeric output - formatted
1.26 crook 5039:
5040: Forth traditionally uses a technique called @var{pictured numeric
5041: output} for formatted printing of integers. In this technique, digits
5042: are extracted from the number (using the current output radix defined by
5043: @code{base}), converted to ASCII codes and appended to a string that is
5044: built in a scratch-pad area of memory (@pxref{core-idef,
5045: Implementation-defined options, Implementation-defined
5046: options}). Arbitrary characters can be appended to the string during the
5047: extraction process. The completed string is specified by an address
5048: and length and can be manipulated (@code{TYPE}ed, copied, modified)
5049: under program control.
1.5 anton 5050:
1.26 crook 5051: All of the words described in the previous section for simple numeric
5052: output are implemented in Gforth using pictured numeric output.
1.5 anton 5053:
1.26 crook 5054: Three important things to remember about Pictured Numeric Output:
1.5 anton 5055:
1.26 crook 5056: @itemize @bullet
5057: @item
1.28 ! crook 5058: It always operates on double-precision numbers; to display a
! 5059: single-precision number, convert it first (@pxref{Double precision} for
! 5060: ways of doing this).
1.26 crook 5061: @item
1.28 ! crook 5062: It always treats the double-precision number as though it were
! 5063: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 5064: @item
5065: The string is built up from right to left; least significant digit first.
5066: @end itemize
1.5 anton 5067:
1.26 crook 5068: doc-<#
5069: doc-#
5070: doc-#s
5071: doc-hold
5072: doc-sign
5073: doc-#>
1.5 anton 5074:
1.26 crook 5075: doc-represent
1.5 anton 5076:
1.26 crook 5077: Here are some examples of using pictured numeric output:
1.5 anton 5078:
5079: @example
1.26 crook 5080: : my-u. ( u -- )
5081: \ Simplest use of pns.. behaves like Standard u.
5082: 0 \ convert to unsigned double
5083: <# \ start conversion
5084: #s \ convert all digits
5085: #> \ complete conversion
5086: TYPE SPACE ; \ display, with trailing space
1.5 anton 5087:
1.26 crook 5088: : cents-only ( u -- )
5089: 0 \ convert to unsigned double
5090: <# \ start conversion
5091: # # \ convert two least-significant digits
5092: #> \ complete conversion, discard other digits
5093: TYPE SPACE ; \ display, with trailing space
1.5 anton 5094:
1.26 crook 5095: : dollars-and-cents ( u -- )
5096: 0 \ convert to unsigned double
5097: <# \ start conversion
5098: # # \ convert two least-significant digits
5099: [char] . hold \ insert decimal point
5100: #s \ convert remaining digits
5101: [char] $ hold \ append currency symbol
5102: #> \ complete conversion
5103: TYPE SPACE ; \ display, with trailing space
1.5 anton 5104:
1.26 crook 5105: : my-. ( n -- )
5106: \ handling negatives.. behaves like Standard .
5107: s>d \ convert to signed double
5108: swap over dabs \ leave sign byte followed by unsigned double
5109: <# \ start conversion
5110: #s \ convert all digits
5111: rot sign \ get at sign byte, append "-" if needed
5112: #> \ complete conversion
5113: TYPE SPACE ; \ display, with trailing space
1.5 anton 5114:
1.26 crook 5115: : account. ( n -- )
5116: \ accountants don't like minus signs, they use braces
5117: \ for negative numbers
5118: s>d \ convert to signed double
5119: swap over dabs \ leave sign byte followed by unsigned double
5120: <# \ start conversion
5121: 2 pick \ get copy of sign byte
5122: 0< IF [char] ) hold THEN \ right-most character of output
5123: #s \ convert all digits
5124: rot \ get at sign byte
5125: 0< IF [char] ( hold THEN
5126: #> \ complete conversion
5127: TYPE SPACE ; \ display, with trailing space
1.5 anton 5128: @end example
5129:
1.26 crook 5130: Here are some examples of using these words:
1.5 anton 5131:
5132: @example
1.26 crook 5133: 1 my-u. 1
5134: hex -1 my-u. decimal FFFFFFFF
5135: 1 cents-only 01
5136: 1234 cents-only 34
5137: 2 dollars-and-cents $0.02
5138: 1234 dollars-and-cents $12.34
5139: 123 my-. 123
5140: -123 my. -123
5141: 123 account. 123
5142: -456 account. (456)
1.5 anton 5143: @end example
5144:
5145:
1.26 crook 5146: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
5147: @subsection String Formats
1.27 crook 5148: @cindex strings - see character strings
5149: @cindex character strings - formats
1.28 ! crook 5150: @cindex I/O - see character strings
1.26 crook 5151:
1.27 crook 5152: Forth commonly uses two different methods for representing character
5153: strings:
1.26 crook 5154:
5155: @itemize @bullet
5156: @item
5157: @cindex address of counted string
5158: As a @var{counted string}, represented by a @var{c-addr}. The char
5159: addressed by @var{c-addr} contains a character-count, @var{n}, of the
5160: string and the string occupies the subsequent @var{n} char addresses in
5161: memory.
5162: @item
5163: As cell pair on the stack; @var{c-addr u}, where @var{u} is the length
5164: of the string in characters, and @var{c-addr} is the address of the
5165: first byte of the string.
5166: @end itemize
5167:
5168: ANS Forth encourages the use of the second format when representing
5169: strings on the stack, whilst conceeding that the counted string format
5170: remains useful as a way of storing strings in memory.
5171:
5172: doc-count
5173:
5174: @xref{Memory Blocks} for words that move, copy and search
5175: for strings. @xref{Displaying characters and strings,} for words that
5176: display characters and strings.
5177:
5178:
5179: @node Displaying characters and strings, Input, String Formats, Other I/O
5180: @subsection Displaying characters and strings
1.27 crook 5181: @cindex characters - compiling and displaying
5182: @cindex character strings - compiling and displaying
1.26 crook 5183:
5184: This section starts with a glossary of Forth words and ends with a set
5185: of examples.
5186:
5187: doc-bl
5188: doc-space
5189: doc-spaces
5190: doc-emit
5191: doc-toupper
5192: doc-."
5193: doc-.(
5194: doc-type
5195: doc-cr
1.27 crook 5196: @cindex cursor control
1.26 crook 5197: doc-at-xy
5198: doc-page
5199: doc-s"
5200: doc-c"
5201: doc-char
5202: doc-[char]
5203: doc-sliteral
5204:
5205: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 5206:
5207: @example
1.26 crook 5208: .( text-1)
5209: : my-word
5210: ." text-2" cr
5211: .( text-3)
5212: ;
5213:
5214: ." text-4"
5215:
5216: : my-char
5217: [char] ALPHABET emit
5218: char emit
5219: ;
1.5 anton 5220: @end example
5221:
1.26 crook 5222: When you load this code into Gforth, the following output is generated:
1.5 anton 5223:
1.26 crook 5224: @example
5225: @kbd{include test.fs <return>} text-1text-3text-4 ok
5226: @end example
1.5 anton 5227:
1.26 crook 5228: @itemize @bullet
5229: @item
5230: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
5231: is an immediate word; it behaves in the same way whether it is used inside
5232: or outside a colon definition.
5233: @item
5234: Message @code{text-4} is displayed because of Gforth's added interpretation
5235: semantics for @code{."}.
5236: @item
5237: Message @code{text-2} is @var{not} displayed, because the text interpreter
5238: performs the compilation semantics for @code{."} within the definition of
5239: @code{my-word}.
5240: @end itemize
1.5 anton 5241:
1.26 crook 5242: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 5243:
1.26 crook 5244: @example
5245: @kbd{my-word <return>} text-2
5246: ok
5247: @kbd{my-char fred <return>} Af ok
5248: @kbd{my-char jim <return>} Aj ok
5249: @end example
1.5 anton 5250:
5251: @itemize @bullet
5252: @item
1.26 crook 5253: Message @code{text-2} is displayed because of the run-time behaviour of
5254: @code{."}.
5255: @item
5256: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
5257: on the stack at run-time. @code{emit} always displays the character
5258: when @code{my-char} is executed.
5259: @item
5260: @code{char} parses a string at run-time and the second @code{emit} displays
5261: the first character of the string.
1.5 anton 5262: @item
1.26 crook 5263: If you type @code{see my-char} you can see that @code{[char]} discarded
5264: the text ``LPHABET'' and only compiled the display code for ``A'' into the
5265: definition of @code{my-char}.
1.5 anton 5266: @end itemize
5267:
5268:
5269:
1.26 crook 5270: @node Input, , Displaying characters and strings, Other I/O
5271: @subsection Input
5272: @cindex input
1.28 ! crook 5273: @cindex I/O - see input
! 5274: @cindex parsing a string
! 5275: @comment TODO more index entries.. particularly wrt parsing
1.5 anton 5276:
1.27 crook 5277: @xref{String Formats} for ways of storing character strings in memory.
1.5 anton 5278:
1.27 crook 5279: @comment TODO examples for >number >float accept key key? pad parse word refill
5280:
5281: doc-key
5282: doc-key?
1.26 crook 5283: doc->number
5284: doc->float
5285: doc-accept
1.27 crook 5286: doc-pad
5287: doc-parse
5288: doc-word
5289: doc-sword
5290: doc-refill
5291: @comment obsolescent words..
5292: doc-convert
1.26 crook 5293: doc-query
5294: doc-expect
1.27 crook 5295: doc-span
1.5 anton 5296:
5297:
5298:
5299: @c -------------------------------------------------------------
1.26 crook 5300: @node Programming Tools, Assembler and Code Words, Other I/O, Words
5301: @section Programming Tools
5302: @cindex programming tools
1.12 anton 5303:
5304: @menu
1.26 crook 5305: * Debugging:: Simple and quick.
5306: * Assertions:: Making your programs self-checking.
5307: * Singlestep Debugger:: Executing your program word by word.
1.5 anton 5308: @end menu
5309:
1.26 crook 5310: @node Debugging, Assertions, Programming Tools, Programming Tools
5311: @subsection Debugging
5312: @cindex debugging
1.5 anton 5313:
1.26 crook 5314: Languages with a slow edit/compile/link/test development loop tend to
5315: require sophisticated tracing/stepping debuggers to facilate
5316: productive debugging.
1.5 anton 5317:
1.26 crook 5318: A much better (faster) way in fast-compiling languages is to add
5319: printing code at well-selected places, let the program run, look at
5320: the output, see where things went wrong, add more printing code, etc.,
5321: until the bug is found.
1.5 anton 5322:
1.26 crook 5323: The simple debugging aids provided in @file{debugs.fs}
5324: are meant to support this style of debugging. In addition, there are
5325: words for non-destructively inspecting the stack and memory:
1.5 anton 5326:
1.26 crook 5327: doc-.s
5328: doc-f.s
1.5 anton 5329:
1.26 crook 5330: There is a word @code{.r} but it does @var{not} display the return
5331: stack! It is used for formatted numeric output.
1.5 anton 5332:
1.26 crook 5333: doc-depth
5334: doc-fdepth
5335: doc-clearstack
5336: doc-?
5337: doc-dump
1.5 anton 5338:
1.26 crook 5339: The word @code{~~} prints debugging information (by default the source
5340: location and the stack contents). It is easy to insert. If you use Emacs
5341: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
5342: query-replace them with nothing). The deferred words
5343: @code{printdebugdata} and @code{printdebugline} control the output of
5344: @code{~~}. The default source location output format works well with
5345: Emacs' compilation mode, so you can step through the program at the
5346: source level using @kbd{C-x `} (the advantage over a stepping debugger
5347: is that you can step in any direction and you know where the crash has
5348: happened or where the strange data has occurred).
1.5 anton 5349:
1.26 crook 5350: The default actions of @code{~~} clobber the contents of the pictured
5351: numeric output string, so you should not use @code{~~}, e.g., between
5352: @code{<#} and @code{#>}.
1.5 anton 5353:
1.26 crook 5354: doc-~~
5355: doc-printdebugdata
5356: doc-printdebugline
1.5 anton 5357:
1.26 crook 5358: doc-see
5359: doc-marker
1.5 anton 5360:
1.26 crook 5361: Here's an example of using @code{marker} at the start of a source file
5362: that you are debugging; it ensures that you only ever have one copy of
5363: the file's definitions compiled at any time:
1.5 anton 5364:
1.26 crook 5365: @example
5366: [IFDEF] my-code
5367: my-code
5368: [ENDIF]
1.5 anton 5369:
1.26 crook 5370: marker my-code
1.28 ! crook 5371: init-included-files
1.5 anton 5372:
1.26 crook 5373: \ .. definitions start here
5374: \ .
5375: \ .
5376: \ end
5377: @end example
1.5 anton 5378:
5379:
5380:
1.26 crook 5381: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
5382: @subsection Assertions
5383: @cindex assertions
1.5 anton 5384:
1.26 crook 5385: It is a good idea to make your programs self-checking, especially if you
5386: make an assumption that may become invalid during maintenance (for
5387: example, that a certain field of a data structure is never zero). Gforth
5388: supports @var{assertions} for this purpose. They are used like this:
1.23 crook 5389:
1.26 crook 5390: @example
5391: assert( @var{flag} )
5392: @end example
1.23 crook 5393:
1.26 crook 5394: The code between @code{assert(} and @code{)} should compute a flag, that
5395: should be true if everything is alright and false otherwise. It should
5396: not change anything else on the stack. The overall stack effect of the
5397: assertion is @code{( -- )}. E.g.
1.23 crook 5398:
1.26 crook 5399: @example
5400: assert( 1 1 + 2 = ) \ what we learn in school
5401: assert( dup 0<> ) \ assert that the top of stack is not zero
5402: assert( false ) \ this code should not be reached
5403: @end example
1.23 crook 5404:
1.26 crook 5405: The need for assertions is different at different times. During
5406: debugging, we want more checking, in production we sometimes care more
5407: for speed. Therefore, assertions can be turned off, i.e., the assertion
5408: becomes a comment. Depending on the importance of an assertion and the
5409: time it takes to check it, you may want to turn off some assertions and
5410: keep others turned on. Gforth provides several levels of assertions for
5411: this purpose:
1.23 crook 5412:
1.26 crook 5413: doc-assert0(
5414: doc-assert1(
5415: doc-assert2(
5416: doc-assert3(
5417: doc-assert(
5418: doc-)
1.23 crook 5419:
1.26 crook 5420: The variable @code{assert-level} specifies the highest assertions that
5421: are turned on. I.e., at the default @code{assert-level} of one,
5422: @code{assert0(} and @code{assert1(} assertions perform checking, while
5423: @code{assert2(} and @code{assert3(} assertions are treated as comments.
5424:
5425: The value of @code{assert-level} is evaluated at compile-time, not at
5426: run-time. Therefore you cannot turn assertions on or off at run-time;
5427: you have to set the @code{assert-level} appropriately before compiling a
5428: piece of code. You can compile different pieces of code at different
5429: @code{assert-level}s (e.g., a trusted library at level 1 and
5430: newly-written code at level 3).
1.23 crook 5431:
1.26 crook 5432: doc-assert-level
1.23 crook 5433:
1.26 crook 5434: If an assertion fails, a message compatible with Emacs' compilation mode
5435: is produced and the execution is aborted (currently with @code{ABORT"}.
5436: If there is interest, we will introduce a special throw code. But if you
5437: intend to @code{catch} a specific condition, using @code{throw} is
5438: probably more appropriate than an assertion).
1.23 crook 5439:
1.26 crook 5440: Definitions in ANS Forth for these assertion words are provided
5441: in @file{compat/assert.fs}.
1.23 crook 5442:
5443:
1.26 crook 5444: @node Singlestep Debugger, , Assertions, Programming Tools
5445: @subsection Singlestep Debugger
5446: @cindex singlestep Debugger
5447: @cindex debugging Singlestep
5448: @cindex @code{dbg}
5449: @cindex @code{BREAK:}
5450: @cindex @code{BREAK"}
1.23 crook 5451:
1.26 crook 5452: When you create a new word there's often the need to check whether it
5453: behaves correctly or not. You can do this by typing @code{dbg
5454: badword}. A debug session might look like this:
1.23 crook 5455:
1.26 crook 5456: @example
5457: : badword 0 DO i . LOOP ; ok
5458: 2 dbg badword
5459: : badword
5460: Scanning code...
1.23 crook 5461:
1.26 crook 5462: Nesting debugger ready!
1.23 crook 5463:
1.26 crook 5464: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
5465: 400D4740 8049F68 DO -> [ 0 ]
5466: 400D4744 804A0C8 i -> [ 1 ] 00000
5467: 400D4748 400C5E60 . -> 0 [ 0 ]
5468: 400D474C 8049D0C LOOP -> [ 0 ]
5469: 400D4744 804A0C8 i -> [ 1 ] 00001
5470: 400D4748 400C5E60 . -> 1 [ 0 ]
5471: 400D474C 8049D0C LOOP -> [ 0 ]
5472: 400D4758 804B384 ; -> ok
5473: @end example
1.23 crook 5474:
1.26 crook 5475: Each line displayed is one step. You always have to hit return to
5476: execute the next word that is displayed. If you don't want to execute
5477: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
5478: an overview what keys are available:
1.23 crook 5479:
1.26 crook 5480: @table @i
1.23 crook 5481:
1.26 crook 5482: @item <return>
5483: Next; Execute the next word.
1.23 crook 5484:
1.26 crook 5485: @item n
5486: Nest; Single step through next word.
1.5 anton 5487:
1.26 crook 5488: @item u
5489: Unnest; Stop debugging and execute rest of word. If we got to this word
5490: with nest, continue debugging with the calling word.
1.5 anton 5491:
1.26 crook 5492: @item d
5493: Done; Stop debugging and execute rest.
1.5 anton 5494:
1.26 crook 5495: @item s
5496: Stop; Abort immediately.
1.5 anton 5497:
1.26 crook 5498: @end table
1.5 anton 5499:
1.26 crook 5500: Debugging large application with this mechanism is very difficult, because
5501: you have to nest very deeply into the program before the interesting part
5502: begins. This takes a lot of time.
1.5 anton 5503:
1.26 crook 5504: To do it more directly put a @code{BREAK:} command into your source code.
5505: When program execution reaches @code{BREAK:} the single step debugger is
5506: invoked and you have all the features described above.
1.23 crook 5507:
1.26 crook 5508: If you have more than one part to debug it is useful to know where the
5509: program has stopped at the moment. You can do this by the
5510: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
5511: string is typed out when the ``breakpoint'' is reached.
5512:
5513: doc-dbg
5514: doc-BREAK:
5515: doc-BREAK"
5516:
5517:
5518: @c -------------------------------------------------------------
5519: @node Assembler and Code Words, Threading Words, Programming Tools, Words
5520: @section Assembler and Code Words
5521: @cindex assembler
5522: @cindex code words
1.5 anton 5523:
1.26 crook 5524: Gforth provides some words for defining primitives (words written in
5525: machine code), and for defining the the machine-code equivalent of
5526: @code{DOES>}-based defining words. However, the machine-independent
5527: nature of Gforth poses a few problems: First of all, Gforth runs on
5528: several architectures, so it can provide no standard assembler. What's
5529: worse is that the register allocation not only depends on the processor,
5530: but also on the @code{gcc} version and options used.
1.5 anton 5531:
1.26 crook 5532: The words that Gforth offers encapsulate some system dependences (e.g., the
5533: header structure), so a system-independent assembler may be used in
5534: Gforth. If you do not have an assembler, you can compile machine code
5535: directly with @code{,} and @code{c,}.
1.5 anton 5536:
1.26 crook 5537: doc-assembler
5538: doc-code
5539: doc-end-code
5540: doc-;code
5541: doc-flush-icache
1.5 anton 5542:
1.26 crook 5543: If @code{flush-icache} does not work correctly, @code{code} words
5544: etc. will not work (reliably), either.
1.5 anton 5545:
1.26 crook 5546: @code{flush-icache} is always present. The other words are rarely used
5547: and reside in @code{code.fs}, which is usually not loaded. You can load
5548: it with @code{require code.fs}.
1.5 anton 5549:
1.26 crook 5550: @cindex registers of the inner interpreter
5551: In the assembly code you will want to refer to the inner interpreter's
5552: registers (e.g., the data stack pointer) and you may want to use other
5553: registers for temporary storage. Unfortunately, the register allocation
5554: is installation-dependent.
1.5 anton 5555:
1.26 crook 5556: The easiest solution is to use explicit register declarations
5557: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
5558: GNU C Manual}) for all of the inner interpreter's registers: You have to
5559: compile Gforth with @code{-DFORCE_REG} (configure option
5560: @code{--enable-force-reg}) and the appropriate declarations must be
5561: present in the @code{machine.h} file (see @code{mips.h} for an example;
5562: you can find a full list of all declarable register symbols with
5563: @code{grep register engine.c}). If you give explicit registers to all
5564: variables that are declared at the beginning of @code{engine()}, you
5565: should be able to use the other caller-saved registers for temporary
5566: storage. Alternatively, you can use the @code{gcc} option
5567: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
5568: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
5569: (however, this restriction on register allocation may slow Gforth
5570: significantly).
1.5 anton 5571:
1.26 crook 5572: If this solution is not viable (e.g., because @code{gcc} does not allow
5573: you to explicitly declare all the registers you need), you have to find
5574: out by looking at the code where the inner interpreter's registers
5575: reside and which registers can be used for temporary storage. You can
5576: get an assembly listing of the engine's code with @code{make engine.s}.
1.5 anton 5577:
1.26 crook 5578: In any case, it is good practice to abstract your assembly code from the
5579: actual register allocation. E.g., if the data stack pointer resides in
5580: register @code{$17}, create an alias for this register called @code{sp},
5581: and use that in your assembly code.
1.5 anton 5582:
1.26 crook 5583: @cindex code words, portable
5584: Another option for implementing normal and defining words efficiently
5585: is to add the desired functionality to the source of Gforth. For normal
5586: words you just have to edit @file{primitives} (@pxref{Automatic
5587: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
5588: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
5589: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.5 anton 5590:
5591:
1.26 crook 5592: @c -------------------------------------------------------------
5593: @node Threading Words, Locals, Assembler and Code Words, Words
5594: @section Threading Words
5595: @cindex threading words
1.5 anton 5596:
1.26 crook 5597: @cindex code address
5598: These words provide access to code addresses and other threading stuff
5599: in Gforth (and, possibly, other interpretive Forths). It more or less
5600: abstracts away the differences between direct and indirect threading
5601: (and, for direct threading, the machine dependences). However, at
5602: present this wordset is still incomplete. It is also pretty low-level;
5603: some day it will hopefully be made unnecessary by an internals wordset
5604: that abstracts implementation details away completely.
1.5 anton 5605:
1.26 crook 5606: doc-threading-method
5607: doc->code-address
5608: doc->does-code
5609: doc-code-address!
5610: doc-does-code!
5611: doc-does-handler!
5612: doc-/does-handler
1.5 anton 5613:
1.26 crook 5614: The code addresses produced by various defining words are produced by
5615: the following words:
1.5 anton 5616:
1.26 crook 5617: doc-docol:
5618: doc-docon:
5619: doc-dovar:
5620: doc-douser:
5621: doc-dodefer:
5622: doc-dofield:
1.5 anton 5623:
1.26 crook 5624: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
5625: with @code{>does-code}. If the word was defined in that way, the value
5626: returned is non-zero and identifies the @code{DOES>} used by the
5627: defining word.
5628: @comment TODO should that be ``identifies the xt of the DOES> ??''
1.5 anton 5629:
1.26 crook 5630: @c -------------------------------------------------------------
5631: @node Locals, Structures, Threading Words, Words
5632: @section Locals
5633: @cindex locals
1.5 anton 5634:
1.26 crook 5635: Local variables can make Forth programming more enjoyable and Forth
5636: programs easier to read. Unfortunately, the locals of ANS Forth are
5637: laden with restrictions. Therefore, we provide not only the ANS Forth
5638: locals wordset, but also our own, more powerful locals wordset (we
5639: implemented the ANS Forth locals wordset through our locals wordset).
1.5 anton 5640:
1.26 crook 5641: The ideas in this section have also been published in the paper
5642: @cite{Automatic Scoping of Local Variables} by M. Anton Ertl, presented
5643: at EuroForth '94; it is available at
5644: @*@url{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz}.
1.5 anton 5645:
1.26 crook 5646: @menu
5647: * Gforth locals::
5648: * ANS Forth locals::
5649: @end menu
1.5 anton 5650:
1.26 crook 5651: @node Gforth locals, ANS Forth locals, Locals, Locals
5652: @subsection Gforth locals
5653: @cindex Gforth locals
5654: @cindex locals, Gforth style
1.5 anton 5655:
1.26 crook 5656: Locals can be defined with
1.5 anton 5657:
5658: @example
1.26 crook 5659: @{ local1 local2 ... -- comment @}
5660: @end example
5661: or
5662: @example
5663: @{ local1 local2 ... @}
1.5 anton 5664: @end example
5665:
1.26 crook 5666: E.g.,
1.5 anton 5667: @example
1.26 crook 5668: : max @{ n1 n2 -- n3 @}
5669: n1 n2 > if
5670: n1
5671: else
5672: n2
5673: endif ;
1.5 anton 5674: @end example
5675:
1.26 crook 5676: The similarity of locals definitions with stack comments is intended. A
5677: locals definition often replaces the stack comment of a word. The order
5678: of the locals corresponds to the order in a stack comment and everything
5679: after the @code{--} is really a comment.
1.5 anton 5680:
1.26 crook 5681: This similarity has one disadvantage: It is too easy to confuse locals
5682: declarations with stack comments, causing bugs and making them hard to
5683: find. However, this problem can be avoided by appropriate coding
5684: conventions: Do not use both notations in the same program. If you do,
5685: they should be distinguished using additional means, e.g. by position.
5686:
5687: @cindex types of locals
5688: @cindex locals types
5689: The name of the local may be preceded by a type specifier, e.g.,
5690: @code{F:} for a floating point value:
5691:
5692: @example
5693: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
5694: \ complex multiplication
5695: Ar Br f* Ai Bi f* f-
5696: Ar Bi f* Ai Br f* f+ ;
5697: @end example
5698:
5699: @cindex flavours of locals
5700: @cindex locals flavours
5701: @cindex value-flavoured locals
5702: @cindex variable-flavoured locals
5703: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
5704: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
5705: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
5706: with @code{W:}, @code{D:} etc.) produces its value and can be changed
5707: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
5708: produces its address (which becomes invalid when the variable's scope is
5709: left). E.g., the standard word @code{emit} can be defined in terms of
5710: @code{type} like this:
1.5 anton 5711:
5712: @example
1.26 crook 5713: : emit @{ C^ char* -- @}
5714: char* 1 type ;
1.5 anton 5715: @end example
5716:
1.26 crook 5717: @cindex default type of locals
5718: @cindex locals, default type
5719: A local without type specifier is a @code{W:} local. Both flavours of
5720: locals are initialized with values from the data or FP stack.
1.5 anton 5721:
1.26 crook 5722: Currently there is no way to define locals with user-defined data
5723: structures, but we are working on it.
1.5 anton 5724:
1.26 crook 5725: Gforth allows defining locals everywhere in a colon definition. This
5726: poses the following questions:
1.5 anton 5727:
1.26 crook 5728: @menu
5729: * Where are locals visible by name?::
5730: * How long do locals live?::
5731: * Programming Style::
5732: * Implementation::
5733: @end menu
1.5 anton 5734:
1.26 crook 5735: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
5736: @subsubsection Where are locals visible by name?
5737: @cindex locals visibility
5738: @cindex visibility of locals
5739: @cindex scope of locals
1.5 anton 5740:
1.26 crook 5741: Basically, the answer is that locals are visible where you would expect
5742: it in block-structured languages, and sometimes a little longer. If you
5743: want to restrict the scope of a local, enclose its definition in
5744: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 5745:
1.26 crook 5746: doc-scope
5747: doc-endscope
1.5 anton 5748:
1.26 crook 5749: These words behave like control structure words, so you can use them
5750: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
5751: arbitrary ways.
1.5 anton 5752:
1.26 crook 5753: If you want a more exact answer to the visibility question, here's the
5754: basic principle: A local is visible in all places that can only be
5755: reached through the definition of the local@footnote{In compiler
5756: construction terminology, all places dominated by the definition of the
5757: local.}. In other words, it is not visible in places that can be reached
5758: without going through the definition of the local. E.g., locals defined
5759: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
5760: defined in @code{BEGIN}...@code{UNTIL} are visible after the
5761: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.5 anton 5762:
1.26 crook 5763: The reasoning behind this solution is: We want to have the locals
5764: visible as long as it is meaningful. The user can always make the
5765: visibility shorter by using explicit scoping. In a place that can
5766: only be reached through the definition of a local, the meaning of a
5767: local name is clear. In other places it is not: How is the local
5768: initialized at the control flow path that does not contain the
5769: definition? Which local is meant, if the same name is defined twice in
5770: two independent control flow paths?
1.5 anton 5771:
1.26 crook 5772: This should be enough detail for nearly all users, so you can skip the
5773: rest of this section. If you really must know all the gory details and
5774: options, read on.
1.5 anton 5775:
1.26 crook 5776: In order to implement this rule, the compiler has to know which places
5777: are unreachable. It knows this automatically after @code{AHEAD},
5778: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
5779: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
5780: compiler that the control flow never reaches that place. If
5781: @code{UNREACHABLE} is not used where it could, the only consequence is
5782: that the visibility of some locals is more limited than the rule above
5783: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
5784: lie to the compiler), buggy code will be produced.
1.5 anton 5785:
1.26 crook 5786: doc-unreachable
1.5 anton 5787:
1.26 crook 5788: Another problem with this rule is that at @code{BEGIN}, the compiler
5789: does not know which locals will be visible on the incoming
5790: back-edge. All problems discussed in the following are due to this
5791: ignorance of the compiler (we discuss the problems using @code{BEGIN}
5792: loops as examples; the discussion also applies to @code{?DO} and other
5793: loops). Perhaps the most insidious example is:
1.5 anton 5794: @example
1.26 crook 5795: AHEAD
5796: BEGIN
5797: x
5798: [ 1 CS-ROLL ] THEN
5799: @{ x @}
5800: ...
5801: UNTIL
5802: @end example
1.5 anton 5803:
1.26 crook 5804: This should be legal according to the visibility rule. The use of
5805: @code{x} can only be reached through the definition; but that appears
5806: textually below the use.
1.5 anton 5807:
1.26 crook 5808: From this example it is clear that the visibility rules cannot be fully
5809: implemented without major headaches. Our implementation treats common
5810: cases as advertised and the exceptions are treated in a safe way: The
5811: compiler makes a reasonable guess about the locals visible after a
5812: @code{BEGIN}; if it is too pessimistic, the
5813: user will get a spurious error about the local not being defined; if the
5814: compiler is too optimistic, it will notice this later and issue a
5815: warning. In the case above the compiler would complain about @code{x}
5816: being undefined at its use. You can see from the obscure examples in
5817: this section that it takes quite unusual control structures to get the
5818: compiler into trouble, and even then it will often do fine.
1.5 anton 5819:
1.26 crook 5820: If the @code{BEGIN} is reachable from above, the most optimistic guess
5821: is that all locals visible before the @code{BEGIN} will also be
5822: visible after the @code{BEGIN}. This guess is valid for all loops that
5823: are entered only through the @code{BEGIN}, in particular, for normal
5824: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
5825: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
5826: compiler. When the branch to the @code{BEGIN} is finally generated by
5827: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
5828: warns the user if it was too optimistic:
5829: @example
5830: IF
5831: @{ x @}
5832: BEGIN
5833: \ x ?
5834: [ 1 cs-roll ] THEN
5835: ...
5836: UNTIL
1.5 anton 5837: @end example
5838:
1.26 crook 5839: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
5840: optimistically assumes that it lives until the @code{THEN}. It notices
5841: this difference when it compiles the @code{UNTIL} and issues a
5842: warning. The user can avoid the warning, and make sure that @code{x}
5843: is not used in the wrong area by using explicit scoping:
5844: @example
5845: IF
5846: SCOPE
5847: @{ x @}
5848: ENDSCOPE
5849: BEGIN
5850: [ 1 cs-roll ] THEN
5851: ...
5852: UNTIL
5853: @end example
1.5 anton 5854:
1.26 crook 5855: Since the guess is optimistic, there will be no spurious error messages
5856: about undefined locals.
1.5 anton 5857:
1.26 crook 5858: If the @code{BEGIN} is not reachable from above (e.g., after
5859: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
5860: optimistic guess, as the locals visible after the @code{BEGIN} may be
5861: defined later. Therefore, the compiler assumes that no locals are
5862: visible after the @code{BEGIN}. However, the user can use
5863: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
5864: visible at the BEGIN as at the point where the top control-flow stack
5865: item was created.
1.5 anton 5866:
1.26 crook 5867: doc-assume-live
1.5 anton 5868:
1.26 crook 5869: E.g.,
1.5 anton 5870: @example
1.26 crook 5871: @{ x @}
5872: AHEAD
5873: ASSUME-LIVE
5874: BEGIN
5875: x
5876: [ 1 CS-ROLL ] THEN
5877: ...
5878: UNTIL
1.5 anton 5879: @end example
5880:
1.26 crook 5881: Other cases where the locals are defined before the @code{BEGIN} can be
5882: handled by inserting an appropriate @code{CS-ROLL} before the
5883: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
5884: behind the @code{ASSUME-LIVE}).
1.5 anton 5885:
1.26 crook 5886: Cases where locals are defined after the @code{BEGIN} (but should be
5887: visible immediately after the @code{BEGIN}) can only be handled by
5888: rearranging the loop. E.g., the ``most insidious'' example above can be
5889: arranged into:
1.5 anton 5890: @example
1.26 crook 5891: BEGIN
5892: @{ x @}
5893: ... 0=
5894: WHILE
5895: x
5896: REPEAT
1.5 anton 5897: @end example
5898:
1.26 crook 5899: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
5900: @subsubsection How long do locals live?
5901: @cindex locals lifetime
5902: @cindex lifetime of locals
1.5 anton 5903:
1.26 crook 5904: The right answer for the lifetime question would be: A local lives at
5905: least as long as it can be accessed. For a value-flavoured local this
5906: means: until the end of its visibility. However, a variable-flavoured
5907: local could be accessed through its address far beyond its visibility
5908: scope. Ultimately, this would mean that such locals would have to be
5909: garbage collected. Since this entails un-Forth-like implementation
5910: complexities, I adopted the same cowardly solution as some other
5911: languages (e.g., C): The local lives only as long as it is visible;
5912: afterwards its address is invalid (and programs that access it
5913: afterwards are erroneous).
1.5 anton 5914:
1.26 crook 5915: @node Programming Style, Implementation, How long do locals live?, Gforth locals
5916: @subsubsection Programming Style
5917: @cindex locals programming style
5918: @cindex programming style, locals
1.5 anton 5919:
1.26 crook 5920: The freedom to define locals anywhere has the potential to change
5921: programming styles dramatically. In particular, the need to use the
5922: return stack for intermediate storage vanishes. Moreover, all stack
5923: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
5924: determined arguments) can be eliminated: If the stack items are in the
5925: wrong order, just write a locals definition for all of them; then
5926: write the items in the order you want.
1.5 anton 5927:
1.26 crook 5928: This seems a little far-fetched and eliminating stack manipulations is
5929: unlikely to become a conscious programming objective. Still, the number
5930: of stack manipulations will be reduced dramatically if local variables
5931: are used liberally (e.g., compare @code{max} in @ref{Gforth locals} with
5932: a traditional implementation of @code{max}).
1.5 anton 5933:
1.26 crook 5934: This shows one potential benefit of locals: making Forth programs more
5935: readable. Of course, this benefit will only be realized if the
5936: programmers continue to honour the principle of factoring instead of
5937: using the added latitude to make the words longer.
1.5 anton 5938:
1.26 crook 5939: @cindex single-assignment style for locals
5940: Using @code{TO} can and should be avoided. Without @code{TO},
5941: every value-flavoured local has only a single assignment and many
5942: advantages of functional languages apply to Forth. I.e., programs are
5943: easier to analyse, to optimize and to read: It is clear from the
5944: definition what the local stands for, it does not turn into something
5945: different later.
1.5 anton 5946:
1.26 crook 5947: E.g., a definition using @code{TO} might look like this:
1.5 anton 5948: @example
1.26 crook 5949: : strcmp @{ addr1 u1 addr2 u2 -- n @}
5950: u1 u2 min 0
5951: ?do
5952: addr1 c@@ addr2 c@@ -
5953: ?dup-if
5954: unloop exit
5955: then
5956: addr1 char+ TO addr1
5957: addr2 char+ TO addr2
5958: loop
5959: u1 u2 - ;
1.5 anton 5960: @end example
1.26 crook 5961: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
5962: every loop iteration. @code{strcmp} is a typical example of the
5963: readability problems of using @code{TO}. When you start reading
5964: @code{strcmp}, you think that @code{addr1} refers to the start of the
5965: string. Only near the end of the loop you realize that it is something
5966: else.
1.5 anton 5967:
1.26 crook 5968: This can be avoided by defining two locals at the start of the loop that
5969: are initialized with the right value for the current iteration.
1.5 anton 5970: @example
1.26 crook 5971: : strcmp @{ addr1 u1 addr2 u2 -- n @}
5972: addr1 addr2
5973: u1 u2 min 0
5974: ?do @{ s1 s2 @}
5975: s1 c@@ s2 c@@ -
5976: ?dup-if
5977: unloop exit
5978: then
5979: s1 char+ s2 char+
5980: loop
5981: 2drop
5982: u1 u2 - ;
1.5 anton 5983: @end example
1.26 crook 5984: Here it is clear from the start that @code{s1} has a different value
5985: in every loop iteration.
1.5 anton 5986:
1.26 crook 5987: @node Implementation, , Programming Style, Gforth locals
5988: @subsubsection Implementation
5989: @cindex locals implementation
5990: @cindex implementation of locals
1.5 anton 5991:
1.26 crook 5992: @cindex locals stack
5993: Gforth uses an extra locals stack. The most compelling reason for
5994: this is that the return stack is not float-aligned; using an extra stack
5995: also eliminates the problems and restrictions of using the return stack
5996: as locals stack. Like the other stacks, the locals stack grows toward
5997: lower addresses. A few primitives allow an efficient implementation:
1.5 anton 5998:
1.26 crook 5999: doc-@local#
6000: doc-f@local#
6001: doc-laddr#
6002: doc-lp+!#
6003: doc-lp!
6004: doc->l
6005: doc-f>l
1.5 anton 6006:
1.26 crook 6007: In addition to these primitives, some specializations of these
6008: primitives for commonly occurring inline arguments are provided for
6009: efficiency reasons, e.g., @code{@@local0} as specialization of
6010: @code{@@local#} for the inline argument 0. The following compiling words
6011: compile the right specialized version, or the general version, as
6012: appropriate:
1.6 pazsan 6013:
1.26 crook 6014: doc-compile-@local
6015: doc-compile-f@local
6016: doc-compile-lp+!
1.12 anton 6017:
1.26 crook 6018: Combinations of conditional branches and @code{lp+!#} like
6019: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
6020: is taken) are provided for efficiency and correctness in loops.
1.6 pazsan 6021:
1.26 crook 6022: A special area in the dictionary space is reserved for keeping the
6023: local variable names. @code{@{} switches the dictionary pointer to this
6024: area and @code{@}} switches it back and generates the locals
6025: initializing code. @code{W:} etc.@ are normal defining words. This
6026: special area is cleared at the start of every colon definition.
1.6 pazsan 6027:
1.26 crook 6028: @cindex word list for defining locals
6029: A special feature of Gforth's dictionary is used to implement the
6030: definition of locals without type specifiers: every word list (aka
6031: vocabulary) has its own methods for searching
6032: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
6033: with a special search method: When it is searched for a word, it
6034: actually creates that word using @code{W:}. @code{@{} changes the search
6035: order to first search the word list containing @code{@}}, @code{W:} etc.,
6036: and then the word list for defining locals without type specifiers.
1.12 anton 6037:
1.26 crook 6038: The lifetime rules support a stack discipline within a colon
6039: definition: The lifetime of a local is either nested with other locals
6040: lifetimes or it does not overlap them.
1.6 pazsan 6041:
1.26 crook 6042: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
6043: pointer manipulation is generated. Between control structure words
6044: locals definitions can push locals onto the locals stack. @code{AGAIN}
6045: is the simplest of the other three control flow words. It has to
6046: restore the locals stack depth of the corresponding @code{BEGIN}
6047: before branching. The code looks like this:
6048: @format
6049: @code{lp+!#} current-locals-size @minus{} dest-locals-size
6050: @code{branch} <begin>
6051: @end format
1.6 pazsan 6052:
1.26 crook 6053: @code{UNTIL} is a little more complicated: If it branches back, it
6054: must adjust the stack just like @code{AGAIN}. But if it falls through,
6055: the locals stack must not be changed. The compiler generates the
6056: following code:
6057: @format
6058: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
6059: @end format
6060: The locals stack pointer is only adjusted if the branch is taken.
1.6 pazsan 6061:
1.26 crook 6062: @code{THEN} can produce somewhat inefficient code:
6063: @format
6064: @code{lp+!#} current-locals-size @minus{} orig-locals-size
6065: <orig target>:
6066: @code{lp+!#} orig-locals-size @minus{} new-locals-size
6067: @end format
6068: The second @code{lp+!#} adjusts the locals stack pointer from the
6069: level at the @var{orig} point to the level after the @code{THEN}. The
6070: first @code{lp+!#} adjusts the locals stack pointer from the current
6071: level to the level at the orig point, so the complete effect is an
6072: adjustment from the current level to the right level after the
6073: @code{THEN}.
1.6 pazsan 6074:
1.26 crook 6075: @cindex locals information on the control-flow stack
6076: @cindex control-flow stack items, locals information
6077: In a conventional Forth implementation a dest control-flow stack entry
6078: is just the target address and an orig entry is just the address to be
6079: patched. Our locals implementation adds a word list to every orig or dest
6080: item. It is the list of locals visible (or assumed visible) at the point
6081: described by the entry. Our implementation also adds a tag to identify
6082: the kind of entry, in particular to differentiate between live and dead
6083: (reachable and unreachable) orig entries.
1.6 pazsan 6084:
1.26 crook 6085: A few unusual operations have to be performed on locals word lists:
1.6 pazsan 6086:
1.26 crook 6087: doc-common-list
6088: doc-sub-list?
6089: doc-list-size
1.6 pazsan 6090:
1.26 crook 6091: Several features of our locals word list implementation make these
6092: operations easy to implement: The locals word lists are organised as
6093: linked lists; the tails of these lists are shared, if the lists
6094: contain some of the same locals; and the address of a name is greater
6095: than the address of the names behind it in the list.
1.6 pazsan 6096:
1.26 crook 6097: Another important implementation detail is the variable
6098: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
6099: determine if they can be reached directly or only through the branch
6100: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
6101: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
6102: definition, by @code{BEGIN} and usually by @code{THEN}.
1.6 pazsan 6103:
1.26 crook 6104: Counted loops are similar to other loops in most respects, but
6105: @code{LEAVE} requires special attention: It performs basically the same
6106: service as @code{AHEAD}, but it does not create a control-flow stack
6107: entry. Therefore the information has to be stored elsewhere;
6108: traditionally, the information was stored in the target fields of the
6109: branches created by the @code{LEAVE}s, by organizing these fields into a
6110: linked list. Unfortunately, this clever trick does not provide enough
6111: space for storing our extended control flow information. Therefore, we
6112: introduce another stack, the leave stack. It contains the control-flow
6113: stack entries for all unresolved @code{LEAVE}s.
1.6 pazsan 6114:
1.26 crook 6115: Local names are kept until the end of the colon definition, even if
6116: they are no longer visible in any control-flow path. In a few cases
6117: this may lead to increased space needs for the locals name area, but
6118: usually less than reclaiming this space would cost in code size.
1.6 pazsan 6119:
6120:
1.26 crook 6121: @node ANS Forth locals, , Gforth locals, Locals
6122: @subsection ANS Forth locals
6123: @cindex locals, ANS Forth style
1.6 pazsan 6124:
1.26 crook 6125: The ANS Forth locals wordset does not define a syntax for locals, but
6126: words that make it possible to define various syntaxes. One of the
6127: possible syntaxes is a subset of the syntax we used in the Gforth locals
6128: wordset, i.e.:
1.6 pazsan 6129:
6130: @example
1.26 crook 6131: @{ local1 local2 ... -- comment @}
1.6 pazsan 6132: @end example
1.23 crook 6133: @noindent
1.26 crook 6134: or
1.6 pazsan 6135: @example
1.26 crook 6136: @{ local1 local2 ... @}
1.6 pazsan 6137: @end example
6138:
1.26 crook 6139: The order of the locals corresponds to the order in a stack comment. The
6140: restrictions are:
1.6 pazsan 6141:
6142: @itemize @bullet
6143: @item
1.26 crook 6144: Locals can only be cell-sized values (no type specifiers are allowed).
1.6 pazsan 6145: @item
1.26 crook 6146: Locals can be defined only outside control structures.
1.6 pazsan 6147: @item
1.26 crook 6148: Locals can interfere with explicit usage of the return stack. For the
6149: exact (and long) rules, see the standard. If you don't use return stack
6150: accessing words in a definition using locals, you will be all right. The
6151: purpose of this rule is to make locals implementation on the return
6152: stack easier.
1.6 pazsan 6153: @item
1.26 crook 6154: The whole definition must be in one line.
6155: @end itemize
1.6 pazsan 6156:
1.26 crook 6157: Locals defined in this way behave like @code{VALUE}s (@xref{Simple
6158: Defining Words}). I.e., they are initialized from the stack. Using their
6159: name produces their value. Their value can be changed using @code{TO}.
1.6 pazsan 6160:
1.26 crook 6161: Since this syntax is supported by Gforth directly, you need not do
6162: anything to use it. If you want to port a program using this syntax to
6163: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
6164: syntax on the other system.
1.6 pazsan 6165:
1.26 crook 6166: Note that a syntax shown in the standard, section A.13 looks
6167: similar, but is quite different in having the order of locals
6168: reversed. Beware!
1.6 pazsan 6169:
1.26 crook 6170: The ANS Forth locals wordset itself consists of a word:
1.6 pazsan 6171:
1.26 crook 6172: doc-(local)
1.6 pazsan 6173:
1.26 crook 6174: The ANS Forth locals extension wordset defines a syntax using @code{locals|}, but it is so
6175: awful that we strongly recommend not to use it. We have implemented this
6176: syntax to make porting to Gforth easy, but do not document it here. The
6177: problem with this syntax is that the locals are defined in an order
6178: reversed with respect to the standard stack comment notation, making
6179: programs harder to read, and easier to misread and miswrite. The only
6180: merit of this syntax is that it is easy to implement using the ANS Forth
6181: locals wordset.
1.7 pazsan 6182:
6183:
1.26 crook 6184: @c ----------------------------------------------------------
6185: @node Structures, Object-oriented Forth, Locals, Words
6186: @section Structures
6187: @cindex structures
6188: @cindex records
1.7 pazsan 6189:
1.26 crook 6190: This section presents the structure package that comes with Gforth. A
6191: version of the package implemented in ANS Forth is available in
6192: @file{compat/struct.fs}. This package was inspired by a posting on
6193: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
6194: possibly John Hayes). A version of this section has been published in
6195: ???. Marcel Hendrix provided helpful comments.
1.7 pazsan 6196:
1.26 crook 6197: @menu
6198: * Why explicit structure support?::
6199: * Structure Usage::
6200: * Structure Naming Convention::
6201: * Structure Implementation::
6202: * Structure Glossary::
6203: @end menu
1.7 pazsan 6204:
1.26 crook 6205: @node Why explicit structure support?, Structure Usage, Structures, Structures
6206: @subsection Why explicit structure support?
1.7 pazsan 6207:
1.26 crook 6208: @cindex address arithmetic for structures
6209: @cindex structures using address arithmetic
6210: If we want to use a structure containing several fields, we could simply
6211: reserve memory for it, and access the fields using address arithmetic
1.27 crook 6212: (@pxref{Address Arithmetic}). As an example, consider a structure with
1.26 crook 6213: the following fields
1.7 pazsan 6214:
1.26 crook 6215: @table @code
6216: @item a
6217: is a float
6218: @item b
6219: is a cell
6220: @item c
6221: is a float
6222: @end table
1.7 pazsan 6223:
1.26 crook 6224: Given the (float-aligned) base address of the structure we get the
6225: address of the field
1.13 pazsan 6226:
1.26 crook 6227: @table @code
6228: @item a
6229: without doing anything further.
6230: @item b
6231: with @code{float+}
6232: @item c
6233: with @code{float+ cell+ faligned}
6234: @end table
1.13 pazsan 6235:
1.26 crook 6236: It is easy to see that this can become quite tiring.
1.13 pazsan 6237:
1.26 crook 6238: Moreover, it is not very readable, because seeing a
6239: @code{cell+} tells us neither which kind of structure is
6240: accessed nor what field is accessed; we have to somehow infer the kind
6241: of structure, and then look up in the documentation, which field of
6242: that structure corresponds to that offset.
1.13 pazsan 6243:
1.26 crook 6244: Finally, this kind of address arithmetic also causes maintenance
6245: troubles: If you add or delete a field somewhere in the middle of the
6246: structure, you have to find and change all computations for the fields
6247: afterwards.
1.13 pazsan 6248:
1.26 crook 6249: So, instead of using @code{cell+} and friends directly, how
6250: about storing the offsets in constants:
1.13 pazsan 6251:
6252: @example
1.26 crook 6253: 0 constant a-offset
6254: 0 float+ constant b-offset
6255: 0 float+ cell+ faligned c-offset
1.13 pazsan 6256: @end example
6257:
1.26 crook 6258: Now we can get the address of field @code{x} with @code{x-offset
6259: +}. This is much better in all respects. Of course, you still
6260: have to change all later offset definitions if you add a field. You can
6261: fix this by declaring the offsets in the following way:
1.13 pazsan 6262:
6263: @example
1.26 crook 6264: 0 constant a-offset
6265: a-offset float+ constant b-offset
6266: b-offset cell+ faligned constant c-offset
1.13 pazsan 6267: @end example
6268:
1.26 crook 6269: Since we always use the offsets with @code{+}, we could use a defining
6270: word @code{cfield} that includes the @code{+} in the action of the
6271: defined word:
1.8 pazsan 6272:
6273: @example
1.26 crook 6274: : cfield ( n "name" -- )
6275: create ,
6276: does> ( name execution: addr1 -- addr2 )
6277: @@ + ;
1.13 pazsan 6278:
1.26 crook 6279: 0 cfield a
6280: 0 a float+ cfield b
6281: 0 b cell+ faligned cfield c
1.13 pazsan 6282: @end example
6283:
1.26 crook 6284: Instead of @code{x-offset +}, we now simply write @code{x}.
6285:
6286: The structure field words now can be used quite nicely. However,
6287: their definition is still a bit cumbersome: We have to repeat the
6288: name, the information about size and alignment is distributed before
6289: and after the field definitions etc. The structure package presented
6290: here addresses these problems.
6291:
6292: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
6293: @subsection Structure Usage
6294: @cindex structure usage
1.13 pazsan 6295:
1.26 crook 6296: @cindex @code{field} usage
6297: @cindex @code{struct} usage
6298: @cindex @code{end-struct} usage
6299: You can define a structure for a (data-less) linked list with:
1.13 pazsan 6300: @example
1.26 crook 6301: struct
6302: cell% field list-next
6303: end-struct list%
1.13 pazsan 6304: @end example
6305:
1.26 crook 6306: With the address of the list node on the stack, you can compute the
6307: address of the field that contains the address of the next node with
6308: @code{list-next}. E.g., you can determine the length of a list
6309: with:
1.13 pazsan 6310:
6311: @example
1.26 crook 6312: : list-length ( list -- n )
6313: \ "list" is a pointer to the first element of a linked list
6314: \ "n" is the length of the list
6315: 0 BEGIN ( list1 n1 )
6316: over
6317: WHILE ( list1 n1 )
6318: 1+ swap list-next @@ swap
6319: REPEAT
6320: nip ;
1.13 pazsan 6321: @end example
6322:
1.26 crook 6323: You can reserve memory for a list node in the dictionary with
6324: @code{list% %allot}, which leaves the address of the list node on the
6325: stack. For the equivalent allocation on the heap you can use @code{list%
6326: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
6327: use @code{list% %allocate}). You can get the the size of a list
6328: node with @code{list% %size} and its alignment with @code{list%
6329: %alignment}.
1.13 pazsan 6330:
1.26 crook 6331: Note that in ANS Forth the body of a @code{create}d word is
6332: @code{aligned} but not necessarily @code{faligned};
6333: therefore, if you do a:
1.13 pazsan 6334: @example
1.26 crook 6335: create @emph{name} foo% %allot
1.8 pazsan 6336: @end example
6337:
1.26 crook 6338: @noindent
6339: then the memory alloted for @code{foo%} is
6340: guaranteed to start at the body of @code{@emph{name}} only if
6341: @code{foo%} contains only character, cell and double fields.
1.20 pazsan 6342:
1.26 crook 6343: @cindex strcutures containing structures
6344: You can include a structure @code{foo%} as a field of
6345: another structure, like this:
1.20 pazsan 6346: @example
1.26 crook 6347: struct
6348: ...
6349: foo% field ...
6350: ...
6351: end-struct ...
1.20 pazsan 6352: @end example
6353:
1.26 crook 6354: @cindex structure extension
6355: @cindex extended records
6356: Instead of starting with an empty structure, you can extend an
6357: existing structure. E.g., a plain linked list without data, as defined
6358: above, is hardly useful; You can extend it to a linked list of integers,
6359: like this:@footnote{This feature is also known as @emph{extended
6360: records}. It is the main innovation in the Oberon language; in other
6361: words, adding this feature to Modula-2 led Wirth to create a new
6362: language, write a new compiler etc. Adding this feature to Forth just
6363: required a few lines of code.}
1.20 pazsan 6364:
6365: @example
1.26 crook 6366: list%
6367: cell% field intlist-int
6368: end-struct intlist%
1.20 pazsan 6369: @end example
6370:
1.26 crook 6371: @code{intlist%} is a structure with two fields:
6372: @code{list-next} and @code{intlist-int}.
1.20 pazsan 6373:
1.26 crook 6374: @cindex structures containing arrays
6375: You can specify an array type containing @emph{n} elements of
6376: type @code{foo%} like this:
1.20 pazsan 6377:
6378: @example
1.26 crook 6379: foo% @emph{n} *
1.20 pazsan 6380: @end example
6381:
1.26 crook 6382: You can use this array type in any place where you can use a normal
6383: type, e.g., when defining a @code{field}, or with
6384: @code{%allot}.
1.20 pazsan 6385:
1.26 crook 6386: @cindex first field optimization
6387: The first field is at the base address of a structure and the word
6388: for this field (e.g., @code{list-next}) actually does not change
6389: the address on the stack. You may be tempted to leave it away in the
6390: interest of run-time and space efficiency. This is not necessary,
6391: because the structure package optimizes this case and compiling such
6392: words does not generate any code. So, in the interest of readability
6393: and maintainability you should include the word for the field when
6394: accessing the field.
1.20 pazsan 6395:
1.26 crook 6396: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
6397: @subsection Structure Naming Convention
6398: @cindex structure naming convention
1.20 pazsan 6399:
1.26 crook 6400: The field names that come to (my) mind are often quite generic, and,
6401: if used, would cause frequent name clashes. E.g., many structures
6402: probably contain a @code{counter} field. The structure names
6403: that come to (my) mind are often also the logical choice for the names
6404: of words that create such a structure.
1.20 pazsan 6405:
1.26 crook 6406: Therefore, I have adopted the following naming conventions:
1.20 pazsan 6407:
1.26 crook 6408: @itemize @bullet
6409: @cindex field naming convention
6410: @item
6411: The names of fields are of the form
6412: @code{@emph{struct}-@emph{field}}, where
6413: @code{@emph{struct}} is the basic name of the structure, and
6414: @code{@emph{field}} is the basic name of the field. You can
6415: think of field words as converting the (address of the)
6416: structure into the (address of the) field.
1.20 pazsan 6417:
1.26 crook 6418: @cindex structure naming convention
6419: @item
6420: The names of structures are of the form
6421: @code{@emph{struct}%}, where
6422: @code{@emph{struct}} is the basic name of the structure.
6423: @end itemize
1.20 pazsan 6424:
1.26 crook 6425: This naming convention does not work that well for fields of extended
6426: structures; e.g., the integer list structure has a field
6427: @code{intlist-int}, but has @code{list-next}, not
6428: @code{intlist-next}.
1.20 pazsan 6429:
1.26 crook 6430: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
6431: @subsection Structure Implementation
6432: @cindex structure implementation
6433: @cindex implementation of structures
1.20 pazsan 6434:
1.26 crook 6435: The central idea in the implementation is to pass the data about the
6436: structure being built on the stack, not in some global
6437: variable. Everything else falls into place naturally once this design
6438: decision is made.
1.20 pazsan 6439:
1.26 crook 6440: The type description on the stack is of the form @emph{align
6441: size}. Keeping the size on the top-of-stack makes dealing with arrays
6442: very simple.
1.20 pazsan 6443:
1.26 crook 6444: @code{field} is a defining word that uses @code{Create}
6445: and @code{DOES>}. The body of the field contains the offset
6446: of the field, and the normal @code{DOES>} action is simply:
1.20 pazsan 6447:
6448: @example
1.26 crook 6449: @ +
1.20 pazsan 6450: @end example
6451:
1.23 crook 6452: @noindent
1.26 crook 6453: i.e., add the offset to the address, giving the stack effect
6454: @var{addr1 -- addr2} for a field.
1.20 pazsan 6455:
1.26 crook 6456: @cindex first field optimization, implementation
6457: This simple structure is slightly complicated by the optimization
6458: for fields with offset 0, which requires a different
6459: @code{DOES>}-part (because we cannot rely on there being
6460: something on the stack if such a field is invoked during
6461: compilation). Therefore, we put the different @code{DOES>}-parts
6462: in separate words, and decide which one to invoke based on the
6463: offset. For a zero offset, the field is basically a noop; it is
6464: immediate, and therefore no code is generated when it is compiled.
1.20 pazsan 6465:
1.26 crook 6466: @node Structure Glossary, , Structure Implementation, Structures
6467: @subsection Structure Glossary
6468: @cindex structure glossary
1.20 pazsan 6469:
1.26 crook 6470: doc-%align
6471: doc-%alignment
6472: doc-%alloc
6473: doc-%allocate
6474: doc-%allot
6475: doc-cell%
6476: doc-char%
6477: doc-dfloat%
6478: doc-double%
6479: doc-end-struct
6480: doc-field
6481: doc-float%
6482: doc-naligned
6483: doc-sfloat%
6484: doc-%size
6485: doc-struct
1.23 crook 6486:
1.26 crook 6487: @c -------------------------------------------------------------
6488: @node Object-oriented Forth, Passing Commands to the OS, Structures, Words
6489: @section Object-oriented Forth
1.20 pazsan 6490:
1.26 crook 6491: Gforth comes with three packages for object-oriented programming:
6492: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
6493: is preloaded, so you have to @code{include} them before use. The most
6494: important differences between these packages (and others) are discussed
6495: in @ref{Comparison with other object models}. All packages are written
6496: in ANS Forth and can be used with any other ANS Forth.
1.20 pazsan 6497:
1.26 crook 6498: @menu
6499: * Why object-oriented programming?::
6500: * Object-Oriented Terminology::
6501: * Objects::
6502: * OOF::
6503: * Mini-OOF::
6504: * Comparison with other object models::
6505: @end menu
1.20 pazsan 6506:
1.23 crook 6507:
1.26 crook 6508: @node Why object-oriented programming?, Object-Oriented Terminology, , Object-oriented Forth
6509: @subsubsection Why object-oriented programming?
6510: @cindex object-oriented programming motivation
6511: @cindex motivation for object-oriented programming
1.23 crook 6512:
1.26 crook 6513: Often we have to deal with several data structures (@emph{objects}),
6514: that have to be treated similarly in some respects, but differently in
6515: others. Graphical objects are the textbook example: circles, triangles,
6516: dinosaurs, icons, and others, and we may want to add more during program
6517: development. We want to apply some operations to any graphical object,
6518: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
6519: has to do something different for every kind of object.
6520: @comment TODO add some other operations eg perimeter, area
6521: @comment and tie in to concrete examples later..
1.23 crook 6522:
1.26 crook 6523: We could implement @code{draw} as a big @code{CASE}
6524: control structure that executes the appropriate code depending on the
6525: kind of object to be drawn. This would be not be very elegant, and,
6526: moreover, we would have to change @code{draw} every time we add
6527: a new kind of graphical object (say, a spaceship).
1.23 crook 6528:
1.26 crook 6529: What we would rather do is: When defining spaceships, we would tell
6530: the system: ``Here's how you @code{draw} a spaceship; you figure
6531: out the rest''.
1.23 crook 6532:
1.26 crook 6533: This is the problem that all systems solve that (rightfully) call
6534: themselves object-oriented; the object-oriented packages presented here
6535: solve this problem (and not much else).
6536: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.23 crook 6537:
1.26 crook 6538: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
6539: @subsubsection Object-Oriented Terminology
6540: @cindex object-oriented terminology
6541: @cindex terminology for object-oriented programming
1.23 crook 6542:
1.26 crook 6543: This section is mainly for reference, so you don't have to understand
6544: all of it right away. The terminology is mainly Smalltalk-inspired. In
6545: short:
1.23 crook 6546:
1.26 crook 6547: @table @emph
6548: @cindex class
6549: @item class
6550: a data structure definition with some extras.
1.23 crook 6551:
1.26 crook 6552: @cindex object
6553: @item object
6554: an instance of the data structure described by the class definition.
1.23 crook 6555:
1.26 crook 6556: @cindex instance variables
6557: @item instance variables
6558: fields of the data structure.
1.23 crook 6559:
1.26 crook 6560: @cindex selector
6561: @cindex method selector
6562: @cindex virtual function
6563: @item selector
6564: (or @emph{method selector}) a word (e.g.,
6565: @code{draw}) that performs an operation on a variety of data
6566: structures (classes). A selector describes @emph{what} operation to
6567: perform. In C++ terminology: a (pure) virtual function.
1.23 crook 6568:
1.26 crook 6569: @cindex method
6570: @item method
6571: the concrete definition that performs the operation
6572: described by the selector for a specific class. A method specifies
6573: @emph{how} the operation is performed for a specific class.
1.23 crook 6574:
1.26 crook 6575: @cindex selector invocation
6576: @cindex message send
6577: @cindex invoking a selector
6578: @item selector invocation
6579: a call of a selector. One argument of the call (the TOS (top-of-stack))
6580: is used for determining which method is used. In Smalltalk terminology:
6581: a message (consisting of the selector and the other arguments) is sent
6582: to the object.
1.1 anton 6583:
1.26 crook 6584: @cindex receiving object
6585: @item receiving object
6586: the object used for determining the method executed by a selector
6587: invocation. In the @file{objects.fs} model, it is the object that is on
6588: the TOS when the selector is invoked. (@emph{Receiving} comes from
6589: the Smalltalk @emph{message} terminology.)
1.1 anton 6590:
1.26 crook 6591: @cindex child class
6592: @cindex parent class
6593: @cindex inheritance
6594: @item child class
6595: a class that has (@emph{inherits}) all properties (instance variables,
6596: selectors, methods) from a @emph{parent class}. In Smalltalk
6597: terminology: The subclass inherits from the superclass. In C++
6598: terminology: The derived class inherits from the base class.
1.1 anton 6599:
1.26 crook 6600: @end table
1.21 crook 6601:
1.26 crook 6602: @c If you wonder about the message sending terminology, it comes from
6603: @c a time when each object had it's own task and objects communicated via
6604: @c message passing; eventually the Smalltalk developers realized that
6605: @c they can do most things through simple (indirect) calls. They kept the
6606: @c terminology.
1.1 anton 6607:
6608:
1.26 crook 6609: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
6610: @subsection The @file{objects.fs} model
6611: @cindex objects
6612: @cindex object-oriented programming
1.1 anton 6613:
1.26 crook 6614: @cindex @file{objects.fs}
6615: @cindex @file{oof.fs}
1.1 anton 6616:
1.26 crook 6617: This section describes the @file{objects.fs} package. 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}).
6618: @c McKewan's and Zsoter's packages
1.1 anton 6619:
1.26 crook 6620: This section assumes that you have read @ref{Structures}.
1.1 anton 6621:
1.26 crook 6622: The techniques on which this model is based have been used to implement
6623: the parser generator, Gray, and have also been used in Gforth for
6624: implementing the various flavours of word lists (hashed or not,
6625: case-sensitive or not, special-purpose word lists for locals etc.).
1.1 anton 6626:
6627:
1.26 crook 6628: @menu
6629: * Properties of the Objects model::
6630: * Basic Objects Usage::
6631: * The Objects base class::
6632: * Creating objects::
6633: * Object-Oriented Programming Style::
6634: * Class Binding::
6635: * Method conveniences::
6636: * Classes and Scoping::
6637: * Object Interfaces::
6638: * Objects Implementation::
6639: * Objects Glossary::
6640: @end menu
1.1 anton 6641:
1.26 crook 6642: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
6643: and Bernd Paysan helped me with the related works section.
1.1 anton 6644:
1.26 crook 6645: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
6646: @subsubsection Properties of the @file{objects.fs} model
6647: @cindex @file{objects.fs} properties
1.1 anton 6648:
1.26 crook 6649: @itemize @bullet
6650: @item
6651: It is straightforward to pass objects on the stack. Passing
6652: selectors on the stack is a little less convenient, but possible.
1.1 anton 6653:
1.26 crook 6654: @item
6655: Objects are just data structures in memory, and are referenced by their
6656: address. You can create words for objects with normal defining words
6657: like @code{constant}. Likewise, there is no difference between instance
6658: variables that contain objects and those that contain other data.
1.1 anton 6659:
1.26 crook 6660: @item
6661: Late binding is efficient and easy to use.
1.21 crook 6662:
1.26 crook 6663: @item
6664: It avoids parsing, and thus avoids problems with state-smartness
6665: and reduced extensibility; for convenience there are a few parsing
6666: words, but they have non-parsing counterparts. There are also a few
6667: defining words that parse. This is hard to avoid, because all standard
6668: defining words parse (except @code{:noname}); however, such
6669: words are not as bad as many other parsing words, because they are not
6670: state-smart.
1.21 crook 6671:
1.26 crook 6672: @item
6673: It does not try to incorporate everything. It does a few things and does
6674: them well (IMO). In particular, this model was not designed to support
6675: information hiding (although it has features that may help); you can use
6676: a separate package for achieving this.
1.21 crook 6677:
1.26 crook 6678: @item
6679: It is layered; you don't have to learn and use all features to use this
6680: model. Only a few features are necessary (@xref{Basic Objects Usage},
6681: @xref{The Objects base class}, @xref{Creating objects}.), the others
6682: are optional and independent of each other.
1.21 crook 6683:
1.26 crook 6684: @item
6685: An implementation in ANS Forth is available.
1.21 crook 6686:
1.26 crook 6687: @end itemize
1.21 crook 6688:
6689:
1.26 crook 6690: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
6691: @subsubsection Basic @file{objects.fs} Usage
6692: @cindex basic objects usage
6693: @cindex objects, basic usage
1.21 crook 6694:
1.26 crook 6695: You can define a class for graphical objects like this:
1.21 crook 6696:
1.26 crook 6697: @cindex @code{class} usage
6698: @cindex @code{end-class} usage
6699: @cindex @code{selector} usage
6700: @example
6701: object class \ "object" is the parent class
6702: selector draw ( x y graphical -- )
6703: end-class graphical
6704: @end example
1.21 crook 6705:
1.26 crook 6706: This code defines a class @code{graphical} with an
6707: operation @code{draw}. We can perform the operation
6708: @code{draw} on any @code{graphical} object, e.g.:
1.21 crook 6709:
1.26 crook 6710: @example
6711: 100 100 t-rex draw
6712: @end example
1.21 crook 6713:
1.26 crook 6714: @noindent
6715: where @code{t-rex} is a word (say, a constant) that produces a
6716: graphical object.
1.21 crook 6717:
1.26 crook 6718: @comment nac TODO add a 2nd operation eg perimeter.. and use for
6719: @comment a concrete example
1.21 crook 6720:
1.26 crook 6721: @cindex abstract class
6722: How do we create a graphical object? With the present definitions,
6723: we cannot create a useful graphical object. The class
6724: @code{graphical} describes graphical objects in general, but not
6725: any concrete graphical object type (C++ users would call it an
6726: @emph{abstract class}); e.g., there is no method for the selector
6727: @code{draw} in the class @code{graphical}.
1.21 crook 6728:
1.26 crook 6729: For concrete graphical objects, we define child classes of the
6730: class @code{graphical}, e.g.:
1.21 crook 6731:
1.26 crook 6732: @cindex @code{overrides} usage
6733: @cindex @code{field} usage in class definition
6734: @example
6735: graphical class \ "graphical" is the parent class
6736: cell% field circle-radius
1.21 crook 6737:
1.26 crook 6738: :noname ( x y circle -- )
6739: circle-radius @@ draw-circle ;
6740: overrides draw
1.21 crook 6741:
1.26 crook 6742: :noname ( n-radius circle -- )
6743: circle-radius ! ;
6744: overrides construct
1.21 crook 6745:
1.26 crook 6746: end-class circle
1.21 crook 6747: @end example
6748:
1.26 crook 6749: Here we define a class @code{circle} as a child of @code{graphical},
6750: with field @code{circle-radius} (which behaves just like a field
6751: (@pxref{Structures}); it defines (using @code{overrides}) new methods
6752: for the selectors @code{draw} and @code{construct} (@code{construct} is
6753: defined in @code{object}, the parent class of @code{graphical}).
1.21 crook 6754:
1.26 crook 6755: Now we can create a circle on the heap (i.e.,
6756: @code{allocate}d memory) with:
1.21 crook 6757:
1.26 crook 6758: @cindex @code{heap-new} usage
1.21 crook 6759: @example
1.26 crook 6760: 50 circle heap-new constant my-circle
6761: @end example
1.21 crook 6762:
1.26 crook 6763: @noindent
6764: @code{heap-new} invokes @code{construct}, thus
6765: initializing the field @code{circle-radius} with 50. We can draw
6766: this new circle at (100,100) with:
1.21 crook 6767:
1.26 crook 6768: @example
6769: 100 100 my-circle draw
1.21 crook 6770: @end example
6771:
1.26 crook 6772: @cindex selector invocation, restrictions
6773: @cindex class definition, restrictions
6774: Note: You can only invoke a selector if the object on the TOS
6775: (the receiving object) belongs to the class where the selector was
6776: defined or one of its descendents; e.g., you can invoke
6777: @code{draw} only for objects belonging to @code{graphical}
6778: or its descendents (e.g., @code{circle}). Immediately before
6779: @code{end-class}, the search order has to be the same as
6780: immediately after @code{class}.
1.21 crook 6781:
1.26 crook 6782: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
6783: @subsubsection The @file{object.fs} base class
6784: @cindex @code{object} class
1.21 crook 6785:
1.26 crook 6786: When you define a class, you have to specify a parent class. So how do
6787: you start defining classes? There is one class available from the start:
6788: @code{object}. It is ancestor for all classes and so is the
6789: only class that has no parent. It has two selectors: @code{construct}
6790: and @code{print}.
1.21 crook 6791:
1.26 crook 6792: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
6793: @subsubsection Creating objects
6794: @cindex creating objects
6795: @cindex object creation
6796: @cindex object allocation options
1.21 crook 6797:
1.26 crook 6798: @cindex @code{heap-new} discussion
6799: @cindex @code{dict-new} discussion
6800: @cindex @code{construct} discussion
6801: You can create and initialize an object of a class on the heap with
6802: @code{heap-new} ( ... class -- object ) and in the dictionary
6803: (allocation with @code{allot}) with @code{dict-new} (
6804: ... class -- object ). Both words invoke @code{construct}, which
6805: consumes the stack items indicated by "..." above.
1.21 crook 6806:
1.26 crook 6807: @cindex @code{init-object} discussion
6808: @cindex @code{class-inst-size} discussion
6809: If you want to allocate memory for an object yourself, you can get its
6810: alignment and size with @code{class-inst-size 2@@} ( class --
6811: align size ). Once you have memory for an object, you can initialize
6812: it with @code{init-object} ( ... class object -- );
6813: @code{construct} does only a part of the necessary work.
1.21 crook 6814:
1.26 crook 6815: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
6816: @subsubsection Object-Oriented Programming Style
6817: @cindex object-oriented programming style
1.21 crook 6818:
1.26 crook 6819: This section is not exhaustive.
1.1 anton 6820:
1.26 crook 6821: @cindex stack effects of selectors
6822: @cindex selectors and stack effects
6823: In general, it is a good idea to ensure that all methods for the
6824: same selector have the same stack effect: when you invoke a selector,
6825: you often have no idea which method will be invoked, so, unless all
6826: methods have the same stack effect, you will not know the stack effect
6827: of the selector invocation.
1.21 crook 6828:
1.26 crook 6829: One exception to this rule is methods for the selector
6830: @code{construct}. We know which method is invoked, because we
6831: specify the class to be constructed at the same place. Actually, I
6832: defined @code{construct} as a selector only to give the users a
6833: convenient way to specify initialization. The way it is used, a
6834: mechanism different from selector invocation would be more natural
6835: (but probably would take more code and more space to explain).
1.21 crook 6836:
1.26 crook 6837: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
6838: @subsubsection Class Binding
6839: @cindex class binding
6840: @cindex early binding
1.21 crook 6841:
1.26 crook 6842: @cindex late binding
6843: Normal selector invocations determine the method at run-time depending
6844: on the class of the receiving object. This run-time selection is called
6845: @var{late binding}.
1.21 crook 6846:
1.26 crook 6847: Sometimes it's preferable to invoke a different method. For example,
6848: you might want to use the simple method for @code{print}ing
6849: @code{object}s instead of the possibly long-winded @code{print} method
6850: of the receiver class. You can achieve this by replacing the invocation
6851: of @code{print} with:
1.21 crook 6852:
1.26 crook 6853: @cindex @code{[bind]} usage
6854: @example
6855: [bind] object print
1.21 crook 6856: @end example
6857:
1.26 crook 6858: @noindent
6859: in compiled code or:
1.21 crook 6860:
1.26 crook 6861: @cindex @code{bind} usage
1.21 crook 6862: @example
1.26 crook 6863: bind object print
1.21 crook 6864: @end example
6865:
1.26 crook 6866: @cindex class binding, alternative to
6867: @noindent
6868: in interpreted code. Alternatively, you can define the method with a
6869: name (e.g., @code{print-object}), and then invoke it through the
6870: name. Class binding is just a (often more convenient) way to achieve
6871: the same effect; it avoids name clutter and allows you to invoke
6872: methods directly without naming them first.
6873:
6874: @cindex superclass binding
6875: @cindex parent class binding
6876: A frequent use of class binding is this: When we define a method
6877: for a selector, we often want the method to do what the selector does
6878: in the parent class, and a little more. There is a special word for
6879: this purpose: @code{[parent]}; @code{[parent]
6880: @emph{selector}} is equivalent to @code{[bind] @emph{parent
6881: selector}}, where @code{@emph{parent}} is the parent
6882: class of the current class. E.g., a method definition might look like:
1.21 crook 6883:
1.26 crook 6884: @cindex @code{[parent]} usage
1.21 crook 6885: @example
1.26 crook 6886: :noname
6887: dup [parent] foo \ do parent's foo on the receiving object
6888: ... \ do some more
6889: ; overrides foo
1.21 crook 6890: @end example
6891:
1.26 crook 6892: @cindex class binding as optimization
6893: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
6894: March 1997), Andrew McKewan presents class binding as an optimization
6895: technique. I recommend not using it for this purpose unless you are in
6896: an emergency. Late binding is pretty fast with this model anyway, so the
6897: benefit of using class binding is small; the cost of using class binding
6898: where it is not appropriate is reduced maintainability.
1.21 crook 6899:
1.26 crook 6900: While we are at programming style questions: You should bind
6901: selectors only to ancestor classes of the receiving object. E.g., say,
6902: you know that the receiving object is of class @code{foo} or its
6903: descendents; then you should bind only to @code{foo} and its
6904: ancestors.
1.21 crook 6905:
1.26 crook 6906: @node Method conveniences, Classes and Scoping, Class Binding, Objects
6907: @subsubsection Method conveniences
6908: @cindex method conveniences
1.1 anton 6909:
1.26 crook 6910: In a method you usually access the receiving object pretty often. If
6911: you define the method as a plain colon definition (e.g., with
6912: @code{:noname}), you may have to do a lot of stack
6913: gymnastics. To avoid this, you can define the method with @code{m:
6914: ... ;m}. E.g., you could define the method for
6915: @code{draw}ing a @code{circle} with
1.20 pazsan 6916:
1.26 crook 6917: @cindex @code{this} usage
6918: @cindex @code{m:} usage
6919: @cindex @code{;m} usage
6920: @example
6921: m: ( x y circle -- )
6922: ( x y ) this circle-radius @@ draw-circle ;m
6923: @end example
1.20 pazsan 6924:
1.26 crook 6925: @cindex @code{exit} in @code{m: ... ;m}
6926: @cindex @code{exitm} discussion
6927: @cindex @code{catch} in @code{m: ... ;m}
6928: When this method is executed, the receiver object is removed from the
6929: stack; you can access it with @code{this} (admittedly, in this
6930: example the use of @code{m: ... ;m} offers no advantage). Note
6931: that I specify the stack effect for the whole method (i.e. including
6932: the receiver object), not just for the code between @code{m:}
6933: and @code{;m}. You cannot use @code{exit} in
6934: @code{m:...;m}; instead, use
6935: @code{exitm}.@footnote{Moreover, for any word that calls
6936: @code{catch} and was defined before loading
6937: @code{objects.fs}, you have to redefine it like I redefined
6938: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.20 pazsan 6939:
1.26 crook 6940: @cindex @code{inst-var} usage
6941: You will frequently use sequences of the form @code{this
6942: @emph{field}} (in the example above: @code{this
6943: circle-radius}). If you use the field only in this way, you can
6944: define it with @code{inst-var} and eliminate the
6945: @code{this} before the field name. E.g., the @code{circle}
6946: class above could also be defined with:
1.20 pazsan 6947:
1.26 crook 6948: @example
6949: graphical class
6950: cell% inst-var radius
1.20 pazsan 6951:
1.26 crook 6952: m: ( x y circle -- )
6953: radius @@ draw-circle ;m
6954: overrides draw
1.20 pazsan 6955:
1.26 crook 6956: m: ( n-radius circle -- )
6957: radius ! ;m
6958: overrides construct
1.12 anton 6959:
1.26 crook 6960: end-class circle
6961: @end example
1.12 anton 6962:
1.26 crook 6963: @code{radius} can only be used in @code{circle} and its
6964: descendent classes and inside @code{m:...;m}.
1.12 anton 6965:
1.26 crook 6966: @cindex @code{inst-value} usage
6967: You can also define fields with @code{inst-value}, which is
6968: to @code{inst-var} what @code{value} is to
6969: @code{variable}. You can change the value of such a field with
6970: @code{[to-inst]}. E.g., we could also define the class
6971: @code{circle} like this:
1.12 anton 6972:
1.26 crook 6973: @example
6974: graphical class
6975: inst-value radius
1.12 anton 6976:
1.26 crook 6977: m: ( x y circle -- )
6978: radius draw-circle ;m
6979: overrides draw
1.12 anton 6980:
1.26 crook 6981: m: ( n-radius circle -- )
6982: [to-inst] radius ;m
6983: overrides construct
1.21 crook 6984:
1.26 crook 6985: end-class circle
1.12 anton 6986: @end example
6987:
6988:
1.26 crook 6989: @node Classes and Scoping, Object Interfaces, Method conveniences, Objects
6990: @subsubsection Classes and Scoping
6991: @cindex classes and scoping
6992: @cindex scoping and classes
1.12 anton 6993:
1.26 crook 6994: Inheritance is frequent, unlike structure extension. This exacerbates
6995: the problem with the field name convention (@pxref{Structure Naming
6996: Convention}): One always has to remember in which class the field was
6997: originally defined; changing a part of the class structure would require
6998: changes for renaming in otherwise unaffected code.
1.12 anton 6999:
1.26 crook 7000: @cindex @code{inst-var} visibility
7001: @cindex @code{inst-value} visibility
7002: To solve this problem, I added a scoping mechanism (which was not in my
7003: original charter): A field defined with @code{inst-var} (or
7004: @code{inst-value}) is visible only in the class where it is defined and in
7005: the descendent classes of this class. Using such fields only makes
7006: sense in @code{m:}-defined methods in these classes anyway.
1.12 anton 7007:
1.26 crook 7008: This scoping mechanism allows us to use the unadorned field name,
7009: because name clashes with unrelated words become much less likely.
1.12 anton 7010:
1.26 crook 7011: @cindex @code{protected} discussion
7012: @cindex @code{private} discussion
7013: Once we have this mechanism, we can also use it for controlling the
7014: visibility of other words: All words defined after
7015: @code{protected} are visible only in the current class and its
7016: descendents. @code{public} restores the compilation
7017: (i.e. @code{current}) word list that was in effect before. If you
7018: have several @code{protected}s without an intervening
7019: @code{public} or @code{set-current}, @code{public}
7020: will restore the compilation word list in effect before the first of
7021: these @code{protected}s.
1.12 anton 7022:
1.26 crook 7023: @node Object Interfaces, Objects Implementation, Classes and Scoping, Objects
7024: @subsubsection Object Interfaces
7025: @cindex object interfaces
7026: @cindex interfaces for objects
1.12 anton 7027:
1.26 crook 7028: In this model you can only call selectors defined in the class of the
7029: receiving objects or in one of its ancestors. If you call a selector
7030: with a receiving object that is not in one of these classes, the
7031: result is undefined; if you are lucky, the program crashes
7032: immediately.
1.12 anton 7033:
1.26 crook 7034: @cindex selectors common to hardly-related classes
7035: Now consider the case when you want to have a selector (or several)
7036: available in two classes: You would have to add the selector to a
7037: common ancestor class, in the worst case to @code{object}. You
7038: may not want to do this, e.g., because someone else is responsible for
7039: this ancestor class.
1.12 anton 7040:
1.26 crook 7041: The solution for this problem is interfaces. An interface is a
7042: collection of selectors. If a class implements an interface, the
7043: selectors become available to the class and its descendents. A class
7044: can implement an unlimited number of interfaces. For the problem
7045: discussed above, we would define an interface for the selector(s), and
7046: both classes would implement the interface.
1.12 anton 7047:
1.26 crook 7048: As an example, consider an interface @code{storage} for
7049: writing objects to disk and getting them back, and a class
7050: @code{foo} that implements it. The code would look like this:
1.12 anton 7051:
1.26 crook 7052: @cindex @code{interface} usage
7053: @cindex @code{end-interface} usage
7054: @cindex @code{implementation} usage
7055: @example
7056: interface
7057: selector write ( file object -- )
7058: selector read1 ( file object -- )
7059: end-interface storage
1.12 anton 7060:
1.26 crook 7061: bar class
7062: storage implementation
1.12 anton 7063:
1.26 crook 7064: ... overrides write
7065: ... overrides read
7066: ...
7067: end-class foo
1.12 anton 7068: @end example
7069:
1.26 crook 7070: @noindent
7071: (I would add a word @code{read} @var{( file -- object )} that uses
7072: @code{read1} internally, but that's beyond the point illustrated
7073: here.)
1.12 anton 7074:
1.26 crook 7075: Note that you cannot use @code{protected} in an interface; and
7076: of course you cannot define fields.
1.12 anton 7077:
1.26 crook 7078: In the Neon model, all selectors are available for all classes;
7079: therefore it does not need interfaces. The price you pay in this model
7080: is slower late binding, and therefore, added complexity to avoid late
7081: binding.
1.12 anton 7082:
1.26 crook 7083: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
7084: @subsubsection @file{objects.fs} Implementation
7085: @cindex @file{objects.fs} implementation
1.12 anton 7086:
1.26 crook 7087: @cindex @code{object-map} discussion
7088: An object is a piece of memory, like one of the data structures
7089: described with @code{struct...end-struct}. It has a field
7090: @code{object-map} that points to the method map for the object's
7091: class.
1.12 anton 7092:
1.26 crook 7093: @cindex method map
7094: @cindex virtual function table
7095: The @emph{method map}@footnote{This is Self terminology; in C++
7096: terminology: virtual function table.} is an array that contains the
7097: execution tokens (@var{xt}s) of the methods for the object's class. Each
7098: selector contains an offset into a method map.
1.12 anton 7099:
1.26 crook 7100: @cindex @code{selector} implementation, class
7101: @code{selector} is a defining word that uses
7102: @code{CREATE} and @code{DOES>}. The body of the
7103: selector contains the offset; the @code{does>} action for a
7104: class selector is, basically:
1.21 crook 7105:
1.26 crook 7106: @example
7107: ( object addr ) @@ over object-map @@ + @@ execute
7108: @end example
1.12 anton 7109:
1.26 crook 7110: Since @code{object-map} is the first field of the object, it
7111: does not generate any code. As you can see, calling a selector has a
7112: small, constant cost.
1.12 anton 7113:
1.26 crook 7114: @cindex @code{current-interface} discussion
7115: @cindex class implementation and representation
7116: A class is basically a @code{struct} combined with a method
7117: map. During the class definition the alignment and size of the class
7118: are passed on the stack, just as with @code{struct}s, so
7119: @code{field} can also be used for defining class
7120: fields. However, passing more items on the stack would be
7121: inconvenient, so @code{class} builds a data structure in memory,
7122: which is accessed through the variable
7123: @code{current-interface}. After its definition is complete, the
7124: class is represented on the stack by a pointer (e.g., as parameter for
7125: a child class definition).
1.1 anton 7126:
1.26 crook 7127: A new class starts off with the alignment and size of its parent,
7128: and a copy of the parent's method map. Defining new fields extends the
7129: size and alignment; likewise, defining new selectors extends the
7130: method map. @code{overrides} just stores a new @var{xt} in the method
7131: map at the offset given by the selector.
1.20 pazsan 7132:
1.26 crook 7133: @cindex class binding, implementation
7134: Class binding just gets the @var{xt} at the offset given by the selector
7135: from the class's method map and @code{compile,}s (in the case of
7136: @code{[bind]}) it.
1.21 crook 7137:
1.26 crook 7138: @cindex @code{this} implementation
7139: @cindex @code{catch} and @code{this}
7140: @cindex @code{this} and @code{catch}
7141: I implemented @code{this} as a @code{value}. At the
7142: start of an @code{m:...;m} method the old @code{this} is
7143: stored to the return stack and restored at the end; and the object on
7144: the TOS is stored @code{TO this}. This technique has one
7145: disadvantage: If the user does not leave the method via
7146: @code{;m}, but via @code{throw} or @code{exit},
7147: @code{this} is not restored (and @code{exit} may
7148: crash). To deal with the @code{throw} problem, I have redefined
7149: @code{catch} to save and restore @code{this}; the same
7150: should be done with any word that can catch an exception. As for
7151: @code{exit}, I simply forbid it (as a replacement, there is
7152: @code{exitm}).
1.21 crook 7153:
1.26 crook 7154: @cindex @code{inst-var} implementation
7155: @code{inst-var} is just the same as @code{field}, with
7156: a different @code{DOES>} action:
7157: @example
7158: @@ this +
7159: @end example
7160: Similar for @code{inst-value}.
1.21 crook 7161:
1.26 crook 7162: @cindex class scoping implementation
7163: Each class also has a word list that contains the words defined with
7164: @code{inst-var} and @code{inst-value}, and its protected
7165: words. It also has a pointer to its parent. @code{class} pushes
7166: the word lists of the class and all its ancestors onto the search order stack,
7167: and @code{end-class} drops them.
1.21 crook 7168:
1.26 crook 7169: @cindex interface implementation
7170: An interface is like a class without fields, parent and protected
7171: words; i.e., it just has a method map. If a class implements an
7172: interface, its method map contains a pointer to the method map of the
7173: interface. The positive offsets in the map are reserved for class
7174: methods, therefore interface map pointers have negative
7175: offsets. Interfaces have offsets that are unique throughout the
7176: system, unlike class selectors, whose offsets are only unique for the
7177: classes where the selector is available (invokable).
1.21 crook 7178:
1.26 crook 7179: This structure means that interface selectors have to perform one
7180: indirection more than class selectors to find their method. Their body
7181: contains the interface map pointer offset in the class method map, and
7182: the method offset in the interface method map. The
7183: @code{does>} action for an interface selector is, basically:
1.21 crook 7184:
7185: @example
1.26 crook 7186: ( object selector-body )
7187: 2dup selector-interface @@ ( object selector-body object interface-offset )
7188: swap object-map @@ + @@ ( object selector-body map )
7189: swap selector-offset @@ + @@ execute
1.21 crook 7190: @end example
7191:
1.26 crook 7192: where @code{object-map} and @code{selector-offset} are
7193: first fields and generate no code.
7194:
7195: As a concrete example, consider the following code:
1.21 crook 7196:
1.26 crook 7197: @example
7198: interface
7199: selector if1sel1
7200: selector if1sel2
7201: end-interface if1
1.21 crook 7202:
1.26 crook 7203: object class
7204: if1 implementation
7205: selector cl1sel1
7206: cell% inst-var cl1iv1
1.21 crook 7207:
1.26 crook 7208: ' m1 overrides construct
7209: ' m2 overrides if1sel1
7210: ' m3 overrides if1sel2
7211: ' m4 overrides cl1sel2
7212: end-class cl1
1.21 crook 7213:
1.26 crook 7214: create obj1 object dict-new drop
7215: create obj2 cl1 dict-new drop
7216: @end example
1.21 crook 7217:
1.26 crook 7218: The data structure created by this code (including the data structure
7219: for @code{object}) is shown in the <a
7220: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
7221: @comment nac TODO add this diagram..
1.21 crook 7222:
1.26 crook 7223: @node Objects Glossary, , Objects Implementation, Objects
7224: @subsubsection @file{objects.fs} Glossary
7225: @cindex @file{objects.fs} Glossary
1.21 crook 7226:
1.26 crook 7227: doc---objects-bind
7228: doc---objects-<bind>
7229: doc---objects-bind'
7230: doc---objects-[bind]
7231: doc---objects-class
7232: doc---objects-class->map
7233: doc---objects-class-inst-size
7234: doc---objects-class-override!
7235: doc---objects-construct
7236: doc---objects-current'
7237: doc---objects-[current]
7238: doc---objects-current-interface
7239: doc---objects-dict-new
7240: doc---objects-drop-order
7241: doc---objects-end-class
7242: doc---objects-end-class-noname
7243: doc---objects-end-interface
7244: doc---objects-end-interface-noname
7245: doc---objects-exitm
7246: doc---objects-heap-new
7247: doc---objects-implementation
7248: doc---objects-init-object
7249: doc---objects-inst-value
7250: doc---objects-inst-var
7251: doc---objects-interface
7252: doc---objects-;m
7253: doc---objects-m:
7254: doc---objects-method
7255: doc---objects-object
7256: doc---objects-overrides
7257: doc---objects-[parent]
7258: doc---objects-print
7259: doc---objects-protected
7260: doc---objects-public
7261: doc---objects-push-order
7262: doc---objects-selector
7263: doc---objects-this
7264: doc---objects-<to-inst>
7265: doc---objects-[to-inst]
7266: doc---objects-to-this
7267: doc---objects-xt-new
1.21 crook 7268:
1.26 crook 7269: @c -------------------------------------------------------------
7270: @node OOF, Mini-OOF, Objects, Object-oriented Forth
7271: @subsection The @file{oof.fs} model
7272: @cindex oof
7273: @cindex object-oriented programming
1.21 crook 7274:
1.26 crook 7275: @cindex @file{objects.fs}
7276: @cindex @file{oof.fs}
1.21 crook 7277:
1.26 crook 7278: This section describes the @file{oof.fs} package.
1.21 crook 7279:
1.26 crook 7280: The package described in this section has been used in bigFORTH since 1991, and
7281: used for two large applications: a chromatographic system used to
7282: create new medicaments, and a graphic user interface library (MINOS).
1.21 crook 7283:
1.26 crook 7284: You can find a description (in German) of @file{oof.fs} in @cite{Object
7285: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
7286: 10(2), 1994.
1.21 crook 7287:
1.26 crook 7288: @menu
7289: * Properties of the OOF model::
7290: * Basic OOF Usage::
7291: * The OOF base class::
7292: * Class Declaration::
7293: * Class Implementation::
7294: @end menu
1.21 crook 7295:
1.26 crook 7296: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
7297: @subsubsection Properties of the @file{oof.fs} model
7298: @cindex @file{oof.fs} properties
1.21 crook 7299:
1.26 crook 7300: @itemize @bullet
7301: @item
7302: This model combines object oriented programming with information
7303: hiding. It helps you writing large application, where scoping is
7304: necessary, because it provides class-oriented scoping.
1.21 crook 7305:
1.26 crook 7306: @item
7307: Named objects, object pointers, and object arrays can be created,
7308: selector invocation uses the ``object selector'' syntax. Selector invocation
7309: to objects and/or selectors on the stack is a bit less convenient, but
7310: possible.
1.21 crook 7311:
1.26 crook 7312: @item
7313: Selector invocation and instance variable usage of the active object is
7314: straightforward, since both make use of the active object.
1.21 crook 7315:
1.26 crook 7316: @item
7317: Late binding is efficient and easy to use.
1.21 crook 7318:
1.26 crook 7319: @item
7320: State-smart objects parse selectors. However, extensibility is provided
7321: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.21 crook 7322:
7323: @item
1.26 crook 7324: An implementation in ANS Forth is available.
7325:
1.21 crook 7326: @end itemize
7327:
7328:
1.26 crook 7329: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
7330: @subsubsection Basic @file{oof.fs} Usage
7331: @cindex @file{oof.fs} usage
7332:
7333: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.21 crook 7334:
1.26 crook 7335: You can define a class for graphical objects like this:
1.21 crook 7336:
1.26 crook 7337: @cindex @code{class} usage
7338: @cindex @code{class;} usage
7339: @cindex @code{method} usage
7340: @example
7341: object class graphical \ "object" is the parent class
7342: method draw ( x y graphical -- )
7343: class;
7344: @end example
1.21 crook 7345:
1.26 crook 7346: This code defines a class @code{graphical} with an
7347: operation @code{draw}. We can perform the operation
7348: @code{draw} on any @code{graphical} object, e.g.:
1.21 crook 7349:
1.26 crook 7350: @example
7351: 100 100 t-rex draw
7352: @end example
1.21 crook 7353:
1.26 crook 7354: @noindent
7355: where @code{t-rex} is an object or object pointer, created with e.g.
7356: @code{graphical : t-rex}.
1.21 crook 7357:
1.26 crook 7358: @cindex abstract class
7359: How do we create a graphical object? With the present definitions,
7360: we cannot create a useful graphical object. The class
7361: @code{graphical} describes graphical objects in general, but not
7362: any concrete graphical object type (C++ users would call it an
7363: @emph{abstract class}); e.g., there is no method for the selector
7364: @code{draw} in the class @code{graphical}.
1.21 crook 7365:
1.26 crook 7366: For concrete graphical objects, we define child classes of the
7367: class @code{graphical}, e.g.:
1.21 crook 7368:
7369: @example
1.26 crook 7370: graphical class circle \ "graphical" is the parent class
7371: cell var circle-radius
7372: how:
7373: : draw ( x y -- )
7374: circle-radius @@ draw-circle ;
7375:
7376: : init ( n-radius -- (
7377: circle-radius ! ;
7378: class;
7379: @end example
7380:
7381: Here we define a class @code{circle} as a child of @code{graphical},
7382: with a field @code{circle-radius}; it defines new methods for the
7383: selectors @code{draw} and @code{init} (@code{init} is defined in
7384: @code{object}, the parent class of @code{graphical}).
1.21 crook 7385:
1.26 crook 7386: Now we can create a circle in the dictionary with:
1.21 crook 7387:
1.26 crook 7388: @example
7389: 50 circle : my-circle
1.21 crook 7390: @end example
7391:
1.26 crook 7392: @noindent
7393: @code{:} invokes @code{init}, thus initializing the field
7394: @code{circle-radius} with 50. We can draw this new circle at (100,100)
7395: with:
1.21 crook 7396:
7397: @example
1.26 crook 7398: 100 100 my-circle draw
1.21 crook 7399: @end example
7400:
1.26 crook 7401: @cindex selector invocation, restrictions
7402: @cindex class definition, restrictions
7403: Note: You can only invoke a selector if the receiving object belongs to
7404: the class where the selector was defined or one of its descendents;
7405: e.g., you can invoke @code{draw} only for objects belonging to
7406: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
7407: mechanism will check if you try to invoke a selector that is not
7408: defined in this class hierarchy, so you'll get an error at compilation
7409: time.
7410:
7411:
7412: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
7413: @subsubsection The @file{oof.fs} base class
7414: @cindex @file{oof.fs} base class
7415:
7416: When you define a class, you have to specify a parent class. So how do
7417: you start defining classes? There is one class available from the start:
7418: @code{object}. You have to use it as ancestor for all classes. It is the
7419: only class that has no parent. Classes are also objects, except that
7420: they don't have instance variables; class manipulation such as
7421: inheritance or changing definitions of a class is handled through
7422: selectors of the class @code{object}.
7423:
7424: @code{object} provides a number of selectors:
7425:
1.21 crook 7426: @itemize @bullet
7427: @item
1.26 crook 7428: @code{class} for subclassing, @code{definitions} to add definitions
7429: later on, and @code{class?} to get type informations (is the class a
7430: subclass of the class passed on the stack?).
7431: doc---object-class
7432: doc---object-definitions
7433: doc---object-class?
7434:
1.21 crook 7435: @item
1.26 crook 7436: @code{init} and @code{dispose} as constructor and destructor of the
7437: object. @code{init} is invocated after the object's memory is allocated,
7438: while @code{dispose} also handles deallocation. Thus if you redefine
7439: @code{dispose}, you have to call the parent's dispose with @code{super
7440: dispose}, too.
7441: doc---object-init
7442: doc---object-dispose
7443:
1.21 crook 7444: @item
1.26 crook 7445: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
7446: @code{[]} to create named and unnamed objects and object arrays or
7447: object pointers.
7448: doc---object-new
7449: doc---object-new[]
7450: doc---object-:
7451: doc---object-ptr
7452: doc---object-asptr
7453: doc---object-[]
1.21 crook 7454:
1.26 crook 7455: @item
7456: @code{::} and @code{super} for explicit scoping. You should use explicit
7457: scoping only for super classes or classes with the same set of instance
7458: variables. Explicitly-scoped selectors use early binding.
7459: doc---object-::
7460: doc---object-super
1.21 crook 7461:
1.26 crook 7462: @item
7463: @code{self} to get the address of the object
7464: doc---object-self
1.21 crook 7465:
7466: @item
1.26 crook 7467: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
7468: pointers and instance defers.
7469: doc---object-bind
7470: doc---object-bound
7471: doc---object-link
7472: doc---object-is
7473:
1.21 crook 7474: @item
1.26 crook 7475: @code{'} to obtain selector tokens, @code{send} to invocate selectors
7476: form the stack, and @code{postpone} to generate selector invocation code.
7477: doc---object-'
7478: doc---object-postpone
7479:
1.21 crook 7480: @item
1.26 crook 7481: @code{with} and @code{endwith} to select the active object from the
7482: stack, and enable its scope. Using @code{with} and @code{endwith}
7483: also allows you to create code using selector @code{postpone} without being
7484: trapped by the state-smart objects.
7485: doc---object-with
7486: doc---object-endwith
7487:
1.21 crook 7488: @end itemize
7489:
1.26 crook 7490: @node Class Declaration, Class Implementation, The OOF base class, OOF
7491: @subsubsection Class Declaration
7492: @cindex class declaration
7493:
7494: @itemize @bullet
7495: @item
7496: Instance variables
7497: doc---oof-var
1.21 crook 7498:
1.26 crook 7499: @item
7500: Object pointers
7501: doc---oof-ptr
7502: doc---oof-asptr
1.21 crook 7503:
1.26 crook 7504: @item
7505: Instance defers
7506: doc---oof-defer
1.21 crook 7507:
1.26 crook 7508: @item
7509: Method selectors
7510: doc---oof-early
7511: doc---oof-method
1.21 crook 7512:
1.26 crook 7513: @item
7514: Class-wide variables
7515: doc---oof-static
1.21 crook 7516:
1.26 crook 7517: @item
7518: End declaration
7519: doc---oof-how:
7520: doc---oof-class;
1.21 crook 7521:
1.26 crook 7522: @end itemize
1.21 crook 7523:
1.26 crook 7524: @c -------------------------------------------------------------
7525: @node Class Implementation, , Class Declaration, OOF
7526: @subsubsection Class Implementation
7527: @cindex class implementation
1.21 crook 7528:
1.26 crook 7529: @c -------------------------------------------------------------
7530: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
7531: @subsection The @file{mini-oof.fs} model
7532: @cindex mini-oof
1.1 anton 7533:
1.26 crook 7534: Gforth's third object oriented Forth package is a 12-liner. It uses a
7535: mixture of the @file{object.fs} and the @file{oof.fs} syntax,
7536: and reduces to the bare minimum of features. This is based on a posting
7537: of Bernd Paysan in comp.arch.
1.1 anton 7538:
7539: @menu
1.26 crook 7540: * Basic Mini-OOF Usage::
7541: * Mini-OOF Example::
7542: * Mini-OOF Implementation::
1.1 anton 7543: @end menu
7544:
1.26 crook 7545: @c -------------------------------------------------------------
7546: @node Basic Mini-OOF Usage, Mini-OOF Example, , Mini-OOF
7547: @subsubsection Basic @file{mini-oof.fs} Usage
7548: @cindex mini-oof usage
1.1 anton 7549:
1.28 ! crook 7550: There is a base class (@code{class}, which allocates one cell for the
! 7551: object pointer) plus seven other words: to define a method, a variable,
! 7552: a class; to end a class, to resolve binding, to allocate an object and
! 7553: to compile a class method.
1.26 crook 7554: @comment TODO better description of the last one
1.1 anton 7555:
1.26 crook 7556: doc-object
7557: doc-method
7558: doc-var
7559: doc-class
7560: doc-end-class
7561: doc-defines
7562: doc-new
7563: doc-::
1.1 anton 7564:
1.21 crook 7565:
1.26 crook 7566: @c -------------------------------------------------------------
7567: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
7568: @subsubsection Mini-OOF Example
7569: @cindex mini-oof example
1.21 crook 7570:
1.26 crook 7571: A short example shows how to use this package. This example, in slightly
7572: extended form, is supplied as @file{moof-exm.fs}
7573: @comment nac TODO could flesh this out with some comments from the Forthwrite article
1.21 crook 7574:
1.26 crook 7575: @example
7576: object class
7577: method init
7578: method draw
7579: end-class graphical
7580: @end example
1.21 crook 7581:
1.26 crook 7582: This code defines a class @code{graphical} with an
7583: operation @code{draw}. We can perform the operation
7584: @code{draw} on any @code{graphical} object, e.g.:
1.1 anton 7585:
1.26 crook 7586: @example
7587: 100 100 t-rex draw
7588: @end example
1.1 anton 7589:
1.26 crook 7590: where @code{t-rex} is an object or object pointer, created with e.g.
7591: @code{graphical new Constant t-rex}.
1.1 anton 7592:
1.26 crook 7593: For concrete graphical objects, we define child classes of the
7594: class @code{graphical}, e.g.:
1.21 crook 7595:
7596: @example
1.26 crook 7597: graphical class
7598: cell var circle-radius
7599: end-class circle \ "graphical" is the parent class
1.21 crook 7600:
1.26 crook 7601: :noname ( x y -- )
7602: circle-radius @@ draw-circle ; circle defines draw
7603: :noname ( r -- )
7604: circle-radius ! ; circle defines init
1.21 crook 7605: @end example
7606:
1.26 crook 7607: There is no implicit init method, so we have to define one. The creation
7608: code of the object now has to call init explicitely.
1.21 crook 7609:
1.26 crook 7610: @example
7611: circle new Constant my-circle
7612: 50 my-circle init
7613: @end example
1.21 crook 7614:
1.26 crook 7615: It is also possible to add a function to create named objects with
7616: automatic call of @code{init}, given that all objects have @code{init}
7617: on the same place:
1.1 anton 7618:
7619: @example
1.26 crook 7620: : new: ( .. o "name" -- )
7621: new dup Constant init ;
7622: 80 circle new: large-circle
1.1 anton 7623: @end example
7624:
1.26 crook 7625: We can draw this new circle at (100,100) with:
1.1 anton 7626:
7627: @example
1.26 crook 7628: 100 100 my-circle draw
1.1 anton 7629: @end example
7630:
1.26 crook 7631: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
7632: @subsubsection @file{mini-oof.fs} Implementation
1.1 anton 7633:
1.26 crook 7634: Object-oriented systems with late binding typically use a
7635: ``vtable''-approach: the first variable in each object is a pointer to a
7636: table, which contains the methods as function pointers. The vtable
7637: may also contain other information.
1.1 anton 7638:
1.26 crook 7639: So first, let's declare methods:
1.1 anton 7640:
1.26 crook 7641: @example
7642: : method ( m v -- m' v ) Create over , swap cell+ swap
7643: DOES> ( ... o -- ... ) @ over @ + @ execute ;
7644: @end example
1.1 anton 7645:
1.26 crook 7646: During method declaration, the number of methods and instance
7647: variables is on the stack (in address units). @code{method} creates
7648: one method and increments the method number. To execute a method, it
7649: takes the object, fetches the vtable pointer, adds the offset, and
7650: executes the @var{xt} stored there. Each method takes the object it is
7651: invoked from as top of stack parameter. The method itself should
7652: consume that object.
1.1 anton 7653:
1.26 crook 7654: Now, we also have to declare instance variables
1.21 crook 7655:
1.26 crook 7656: @example
7657: : var ( m v size -- m v' ) Create over , +
7658: DOES> ( o -- addr ) @ + ;
7659: @end example
1.21 crook 7660:
1.26 crook 7661: As before, a word is created with the current offset. Instance
7662: variables can have different sizes (cells, floats, doubles, chars), so
7663: all we do is take the size and add it to the offset. If your machine
7664: has alignment restrictions, put the proper @code{aligned} or
7665: @code{faligned} before the variable, to adjust the variable
7666: offset. That's why it is on the top of stack.
1.2 jwilke 7667:
1.26 crook 7668: We need a starting point (the base object) and some syntactic sugar:
1.21 crook 7669:
1.26 crook 7670: @example
7671: Create object 1 cells , 2 cells ,
7672: : class ( class -- class methods vars ) dup 2@ ;
7673: @end example
1.21 crook 7674:
1.26 crook 7675: For inheritance, the vtable of the parent object has to be
7676: copied when a new, derived class is declared. This gives all the
7677: methods of the parent class, which can be overridden, though.
1.21 crook 7678:
1.2 jwilke 7679: @example
1.26 crook 7680: : end-class ( class methods vars -- )
7681: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
7682: cell+ dup cell+ r> rot @ 2 cells /string move ;
7683: @end example
7684:
7685: The first line creates the vtable, initialized with
7686: @code{noop}s. The second line is the inheritance mechanism, it
7687: copies the xts from the parent vtable.
1.2 jwilke 7688:
1.26 crook 7689: We still have no way to define new methods, let's do that now:
1.2 jwilke 7690:
1.26 crook 7691: @example
7692: : defines ( xt class -- ) ' >body @ + ! ;
1.2 jwilke 7693: @end example
7694:
1.26 crook 7695: To allocate a new object, we need a word, too:
1.2 jwilke 7696:
1.26 crook 7697: @example
7698: : new ( class -- o ) here over @ allot swap over ! ;
7699: @end example
1.2 jwilke 7700:
1.26 crook 7701: Sometimes derived classes want to access the method of the
7702: parent object. There are two ways to achieve this with Mini-OOF:
7703: first, you could use named words, and second, you could look up the
7704: vtable of the parent object.
1.2 jwilke 7705:
1.26 crook 7706: @example
7707: : :: ( class "name" -- ) ' >body @ + @ compile, ;
7708: @end example
1.2 jwilke 7709:
7710:
1.26 crook 7711: Nothing can be more confusing than a good example, so here is
7712: one. First let's declare a text object (called
7713: @code{button}), that stores text and position:
1.2 jwilke 7714:
1.26 crook 7715: @example
7716: object class
7717: cell var text
7718: cell var len
7719: cell var x
7720: cell var y
7721: method init
7722: method draw
7723: end-class button
7724: @end example
1.2 jwilke 7725:
1.26 crook 7726: @noindent
7727: Now, implement the two methods, @code{draw} and @code{init}:
1.2 jwilke 7728:
1.26 crook 7729: @example
7730: :noname ( o -- )
7731: >r r@ x @ r@ y @ at-xy r@ text @ r> len @ type ;
7732: button defines draw
7733: :noname ( addr u o -- )
7734: >r 0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
7735: button defines init
7736: @end example
1.2 jwilke 7737:
1.26 crook 7738: @noindent
7739: To demonstrate inheritance, we define a class @code{bold-button}, with no
7740: new data and no new methods:
1.2 jwilke 7741:
1.26 crook 7742: @example
7743: button class
7744: end-class bold-button
1.1 anton 7745:
1.26 crook 7746: : bold 27 emit ." [1m" ;
7747: : normal 27 emit ." [0m" ;
7748: @end example
1.1 anton 7749:
1.26 crook 7750: @noindent
7751: The class @code{bold-button} has a different draw method to
7752: @code{button}, but the new method is defined in terms of the draw method
7753: for @code{button}:
1.1 anton 7754:
1.26 crook 7755: @example
7756: :noname bold [ button :: draw ] normal ; bold-button defines draw
7757: @end example
1.1 anton 7758:
1.26 crook 7759: @noindent
7760: Finally, create two objects and apply methods:
1.1 anton 7761:
1.26 crook 7762: @example
7763: button new Constant foo
7764: s" thin foo" foo init
7765: page
7766: foo draw
7767: bold-button new Constant bar
7768: s" fat bar" bar init
7769: 1 bar y !
7770: bar draw
7771: @end example
1.1 anton 7772:
7773:
1.26 crook 7774: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
7775: @subsubsection Comparison with other object models
7776: @cindex comparison of object models
7777: @cindex object models, comparison
1.1 anton 7778:
1.26 crook 7779: Many object-oriented Forth extensions have been proposed (@cite{A survey
7780: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
7781: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
7782: relation of the object models described here to two well-known and two
7783: closely-related (by the use of method maps) models.
1.1 anton 7784:
1.26 crook 7785: @cindex Neon model
7786: The most popular model currently seems to be the Neon model (see
7787: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
7788: 1997) by Andrew McKewan) but this model has a number of limitations
7789: @footnote{A longer version of this critique can be
7790: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
7791: Dimensions, May 1997) by Anton Ertl.}:
1.1 anton 7792:
1.26 crook 7793: @itemize @bullet
7794: @item
7795: It uses a @code{@emph{selector
7796: object}} syntax, which makes it unnatural to pass objects on the
7797: stack.
1.1 anton 7798:
1.26 crook 7799: @item
7800: It requires that the selector parses the input stream (at
7801: compile time); this leads to reduced extensibility and to bugs that are+
7802: hard to find.
1.1 anton 7803:
1.26 crook 7804: @item
7805: It allows using every selector to every object;
7806: this eliminates the need for classes, but makes it harder to create
7807: efficient implementations.
7808: @end itemize
1.1 anton 7809:
1.26 crook 7810: @cindex Pountain's object-oriented model
7811: Another well-known publication is @cite{Object-Oriented Forth} (Academic
7812: Press, London, 1987) by Dick Pountain. However, it is not really about
7813: object-oriented programming, because it hardly deals with late
7814: binding. Instead, it focuses on features like information hiding and
7815: overloading that are characteristic of modular languages like Ada (83).
1.1 anton 7816:
1.26 crook 7817: @cindex Zsoter's object-oriented model
7818: In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1) 1996, pages 31-35)
7819: Andras Zsoter describes a model that makes heavy use of an active object
7820: (like @code{this} in @file{objects.fs}): The active object is not only
7821: used for accessing all fields, but also specifies the receiving object
7822: of every selector invocation; you have to change the active object
7823: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
7824: changes more or less implicitly at @code{m: ... ;m}. Such a change at
7825: the method entry point is unnecessary with the Zsoter's model, because
7826: the receiving object is the active object already. On the other hand, the explicit
7827: change is absolutely necessary in that model, because otherwise no one
7828: could ever change the active object. An ANS Forth implementation of this
7829: model is available at @url{http://www.forth.org/fig/oopf.html}.
1.1 anton 7830:
1.26 crook 7831: @cindex @file{oof.fs}, differences to other models
7832: The @file{oof.fs} model combines information hiding and overloading
7833: resolution (by keeping names in various word lists) with object-oriented
7834: programming. It sets the active object implicitly on method entry, but
7835: also allows explicit changing (with @code{>o...o>} or with
7836: @code{with...endwith}). It uses parsing and state-smart objects and
7837: classes for resolving overloading and for early binding: the object or
7838: class parses the selector and determines the method from this. If the
7839: selector is not parsed by an object or class, it performs a call to the
7840: selector for the active object (late binding), like Zsoter's model.
7841: Fields are always accessed through the active object. The big
7842: disadvantage of this model is the parsing and the state-smartness, which
7843: reduces extensibility and increases the opportunities for subtle bugs;
7844: essentially, you are only safe if you never tick or @code{postpone} an
7845: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.1 anton 7846:
1.26 crook 7847: @cindex @file{mini-oof.fs}, differences to other models
7848: The @file{mini-oof.fs} model is quite similar to a very stripped-down version of
7849: the @file{objects.fs} model, but syntactically it is a mixture of the @file{objects.fs} and
7850: @file{oof.fs} models.
1.1 anton 7851:
1.26 crook 7852: @c -------------------------------------------------------------
7853: @node Passing Commands to the OS, Miscellaneous Words, Object-oriented Forth, Words
1.21 crook 7854: @section Passing Commands to the Operating System
7855: @cindex operating system - passing commands
7856: @cindex shell commands
7857:
7858: Gforth allows you to pass an arbitrary string to the host operating
7859: system shell (if such a thing exists) for execution.
7860:
7861: doc-sh
7862: doc-system
7863: doc-$?
1.23 crook 7864: doc-getenv
1.21 crook 7865:
1.26 crook 7866: @c -------------------------------------------------------------
1.21 crook 7867: @node Miscellaneous Words, , Passing Commands to the OS, Words
7868: @section Miscellaneous Words
7869: @cindex miscellaneous words
7870:
1.26 crook 7871: These section lists the ANS Forth words that are not documented
1.21 crook 7872: elsewhere in this manual. Ultimately, they all need proper homes.
7873:
7874: doc-ms
7875: doc-time&date
1.27 crook 7876:
1.21 crook 7877: doc-[compile]
7878:
7879:
1.26 crook 7880: The following ANS Forth words are not currently supported by Gforth
1.27 crook 7881: (@pxref{ANS conformance}):
1.21 crook 7882:
7883: @code{EDITOR}
7884: @code{EKEY}
7885: @code{EKEY>CHAR}
7886: @code{EKEY?}
7887: @code{EMIT?}
7888: @code{FORGET}
7889:
1.24 anton 7890: @c ******************************************************************
7891: @node Error messages, Tools, Words, Top
7892: @chapter Error messages
7893: @cindex error messages
7894: @cindex backtrace
7895:
7896: A typical Gforth error message looks like this:
7897:
7898: @example
7899: in file included from :-1
7900: in file included from ./yyy.fs:1
7901: ./xxx.fs:4: Invalid memory address
7902: bar
7903: ^^^
1.25 anton 7904: $400E664C @@
7905: $400E6664 foo
1.24 anton 7906: @end example
7907:
7908: The message identifying the error is @code{Invalid memory address}. The
7909: error happened when text-interpreting line 4 of the file
7910: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
7911: word on the line where the error happened, is pointed out (with
7912: @code{^^^}).
7913:
7914: The file containing the error was included in line 1 of @file{./yyy.fs},
7915: and @file{yyy.fs} was included from a non-file (in this case, by giving
7916: @file{yyy.fs} as command-line parameter to Gforth).
7917:
7918: At the end of the error message you find a return stack dump that can be
7919: interpreted as a backtrace (possibly empty). On top you find the top of
7920: the return stack when the @code{throw} happened, and at the bottom you
7921: find the return stack entry just above the return stack of the topmost
7922: text interpreter.
7923:
7924: To the right of most return stack entries you see a guess for the word
7925: that pushed that return stack entry as its return address. This gives a
7926: backtrace. In our case we see that @code{bar} called @code{foo}, and
7927: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
7928: address} exception).
7929:
7930: Note that the backtrace is not perfect: We don't know which return stack
7931: entries are return addresses (so we may get false positives); and in
7932: some cases (e.g., for @code{abort"}) we cannot determine from the return
7933: address the word that pushed the return address, so for some return
7934: addresses you see no names in the return stack dump.
1.25 anton 7935:
7936: @cindex @code{catch} and backtraces
7937: The return stack dump represents the return stack at the time when a
7938: specific @code{throw} was executed. In programs that make use of
7939: @code{catch}, it is not necessarily clear which @code{throw} should be
7940: used for the return stack dump (e.g., consider one @code{throw} that
7941: indicates an error, which is caught, and during recovery another error
7942: happens; which @code{throw} should be used for the stack dump). Gforth
7943: presents the return stack dump for the first @code{throw} after the last
7944: executed (not returned-to) @code{catch}; this works well in the usual
7945: case.
7946:
7947: @cindex @code{gforth-fast} and backtraces
7948: @cindex @code{gforth-fast}, difference from @code{gforth}
7949: @cindex backtraces with @code{gforth-fast}
7950: @cindex return stack dump with @code{gforth-fast}
7951: @code{gforth} is able to do a return stack dump for throws generated
7952: from primitives (e.g., invalid memory address, stack empty etc.);
7953: @code{gforth-fast} is only able to do a return stack dump from a
7954: directly called @code{throw} (including @code{abort} etc.). This is the
7955: only difference (apart from a speed difference of about 30%) between
7956: @code{gforth} and @code{gforth-fast}. Given an exception caused by a
7957: primitive in @code{gforth-fast}, you will typically see no return stack
7958: dump at all; however, if the exception is caught by @code{catch} (e.g.,
7959: for restoring some state), and then @code{throw}n again, the return
7960: stack dump will be for the first such @code{throw}.
1.2 jwilke 7961:
1.5 anton 7962: @c ******************************************************************
1.24 anton 7963: @node Tools, ANS conformance, Error messages, Top
1.1 anton 7964: @chapter Tools
7965:
7966: @menu
7967: * ANS Report:: Report the words used, sorted by wordset.
7968: @end menu
7969:
7970: See also @ref{Emacs and Gforth}.
7971:
7972: @node ANS Report, , Tools, Tools
7973: @section @file{ans-report.fs}: Report the words used, sorted by wordset
7974: @cindex @file{ans-report.fs}
7975: @cindex report the words used in your program
7976: @cindex words used in your program
7977:
7978: If you want to label a Forth program as ANS Forth Program, you must
7979: document which wordsets the program uses; for extension wordsets, it is
7980: helpful to list the words the program requires from these wordsets
7981: (because Forth systems are allowed to provide only some words of them).
7982:
7983: The @file{ans-report.fs} tool makes it easy for you to determine which
7984: words from which wordset and which non-ANS words your application
7985: uses. You simply have to include @file{ans-report.fs} before loading the
7986: program you want to check. After loading your program, you can get the
7987: report with @code{print-ans-report}. A typical use is to run this as
7988: batch job like this:
7989: @example
7990: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
7991: @end example
7992:
7993: The output looks like this (for @file{compat/control.fs}):
7994: @example
7995: The program uses the following words
7996: from CORE :
7997: : POSTPONE THEN ; immediate ?dup IF 0=
7998: from BLOCK-EXT :
7999: \
8000: from FILE :
8001: (
8002: @end example
8003:
8004: @subsection Caveats
8005:
8006: Note that @file{ans-report.fs} just checks which words are used, not whether
8007: they are used in an ANS Forth conforming way!
8008:
8009: Some words are defined in several wordsets in the
8010: standard. @file{ans-report.fs} reports them for only one of the
8011: wordsets, and not necessarily the one you expect. It depends on usage
8012: which wordset is the right one to specify. E.g., if you only use the
8013: compilation semantics of @code{S"}, it is a Core word; if you also use
8014: its interpretation semantics, it is a File word.
8015:
8016: @c ******************************************************************
8017: @node ANS conformance, Model, Tools, Top
8018: @chapter ANS conformance
8019: @cindex ANS conformance of Gforth
8020:
8021: To the best of our knowledge, Gforth is an
8022:
8023: ANS Forth System
8024: @itemize @bullet
8025: @item providing the Core Extensions word set
8026: @item providing the Block word set
8027: @item providing the Block Extensions word set
8028: @item providing the Double-Number word set
8029: @item providing the Double-Number Extensions word set
8030: @item providing the Exception word set
8031: @item providing the Exception Extensions word set
8032: @item providing the Facility word set
8033: @item providing @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
8034: @item providing the File Access word set
8035: @item providing the File Access Extensions word set
8036: @item providing the Floating-Point word set
8037: @item providing the Floating-Point Extensions word set
8038: @item providing the Locals word set
8039: @item providing the Locals Extensions word set
8040: @item providing the Memory-Allocation word set
8041: @item providing the Memory-Allocation Extensions word set (that one's easy)
8042: @item providing the Programming-Tools word set
8043: @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
8044: @item providing the Search-Order word set
8045: @item providing the Search-Order Extensions word set
8046: @item providing the String word set
8047: @item providing the String Extensions word set (another easy one)
8048: @end itemize
8049:
8050: @cindex system documentation
8051: In addition, ANS Forth systems are required to document certain
8052: implementation choices. This chapter tries to meet these
8053: requirements. In many cases it gives a way to ask the system for the
8054: information instead of providing the information directly, in
8055: particular, if the information depends on the processor, the operating
8056: system or the installation options chosen, or if they are likely to
8057: change during the maintenance of Gforth.
8058:
8059: @comment The framework for the rest has been taken from pfe.
8060:
8061: @menu
8062: * The Core Words::
8063: * The optional Block word set::
8064: * The optional Double Number word set::
8065: * The optional Exception word set::
8066: * The optional Facility word set::
8067: * The optional File-Access word set::
8068: * The optional Floating-Point word set::
8069: * The optional Locals word set::
8070: * The optional Memory-Allocation word set::
8071: * The optional Programming-Tools word set::
8072: * The optional Search-Order word set::
8073: @end menu
8074:
8075:
8076: @c =====================================================================
8077: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
8078: @comment node-name, next, previous, up
8079: @section The Core Words
8080: @c =====================================================================
8081: @cindex core words, system documentation
8082: @cindex system documentation, core words
8083:
8084: @menu
8085: * core-idef:: Implementation Defined Options
8086: * core-ambcond:: Ambiguous Conditions
8087: * core-other:: Other System Documentation
8088: @end menu
8089:
8090: @c ---------------------------------------------------------------------
8091: @node core-idef, core-ambcond, The Core Words, The Core Words
8092: @subsection Implementation Defined Options
8093: @c ---------------------------------------------------------------------
8094: @cindex core words, implementation-defined options
8095: @cindex implementation-defined options, core words
8096:
8097:
8098: @table @i
8099: @item (Cell) aligned addresses:
8100: @cindex cell-aligned addresses
8101: @cindex aligned addresses
8102: processor-dependent. Gforth's alignment words perform natural alignment
8103: (e.g., an address aligned for a datum of size 8 is divisible by
8104: 8). Unaligned accesses usually result in a @code{-23 THROW}.
8105:
8106: @item @code{EMIT} and non-graphic characters:
8107: @cindex @code{EMIT} and non-graphic characters
8108: @cindex non-graphic characters and @code{EMIT}
8109: The character is output using the C library function (actually, macro)
8110: @code{putc}.
8111:
8112: @item character editing of @code{ACCEPT} and @code{EXPECT}:
8113: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
8114: @cindex editing in @code{ACCEPT} and @code{EXPECT}
8115: @cindex @code{ACCEPT}, editing
8116: @cindex @code{EXPECT}, editing
8117: This is modeled on the GNU readline library (@pxref{Readline
8118: Interaction, , Command Line Editing, readline, The GNU Readline
8119: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
8120: producing a full word completion every time you type it (instead of
1.28 ! crook 8121: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 8122:
8123: @item character set:
8124: @cindex character set
8125: The character set of your computer and display device. Gforth is
8126: 8-bit-clean (but some other component in your system may make trouble).
8127:
8128: @item Character-aligned address requirements:
8129: @cindex character-aligned address requirements
8130: installation-dependent. Currently a character is represented by a C
8131: @code{unsigned char}; in the future we might switch to @code{wchar_t}
8132: (Comments on that requested).
8133:
8134: @item character-set extensions and matching of names:
8135: @cindex character-set extensions and matching of names
1.26 crook 8136: @cindex case-sensitivity for name lookup
8137: @cindex name lookup, case-sensitivity
8138: @cindex locale and case-sensitivity
1.21 crook 8139: Any character except the ASCII NUL character can be used in a
1.1 anton 8140: name. Matching is case-insensitive (except in @code{TABLE}s). The
8141: matching is performed using the C function @code{strncasecmp}, whose
8142: function is probably influenced by the locale. E.g., the @code{C} locale
8143: does not know about accents and umlauts, so they are matched
8144: case-sensitively in that locale. For portability reasons it is best to
8145: write programs such that they work in the @code{C} locale. Then one can
8146: use libraries written by a Polish programmer (who might use words
8147: containing ISO Latin-2 encoded characters) and by a French programmer
8148: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
8149: funny results for some of the words (which ones, depends on the font you
8150: are using)). Also, the locale you prefer may not be available in other
8151: operating systems. Hopefully, Unicode will solve these problems one day.
8152:
8153: @item conditions under which control characters match a space delimiter:
8154: @cindex space delimiters
8155: @cindex control characters as delimiters
8156: If @code{WORD} is called with the space character as a delimiter, all
8157: white-space characters (as identified by the C macro @code{isspace()})
8158: are delimiters. @code{PARSE}, on the other hand, treats space like other
8159: delimiters. @code{PARSE-WORD} treats space like @code{WORD}, but behaves
8160: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
8161: interpreter (aka text interpreter) by default, treats all white-space
8162: characters as delimiters.
8163:
1.26 crook 8164: @item format of the control-flow stack:
8165: @cindex control-flow stack, format
8166: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 8167: stack item in cells is given by the constant @code{cs-item-size}. At the
8168: time of this writing, an item consists of a (pointer to a) locals list
8169: (third), an address in the code (second), and a tag for identifying the
8170: item (TOS). The following tags are used: @code{defstart},
8171: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
8172: @code{scopestart}.
8173:
8174: @item conversion of digits > 35
8175: @cindex digits > 35
8176: The characters @code{[\]^_'} are the digits with the decimal value
8177: 36@minus{}41. There is no way to input many of the larger digits.
8178:
8179: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
8180: @cindex @code{EXPECT}, display after end of input
8181: @cindex @code{ACCEPT}, display after end of input
8182: The cursor is moved to the end of the entered string. If the input is
8183: terminated using the @kbd{Return} key, a space is typed.
8184:
8185: @item exception abort sequence of @code{ABORT"}:
8186: @cindex exception abort sequence of @code{ABORT"}
8187: @cindex @code{ABORT"}, exception abort sequence
8188: The error string is stored into the variable @code{"error} and a
8189: @code{-2 throw} is performed.
8190:
8191: @item input line terminator:
8192: @cindex input line terminator
8193: @cindex line terminator on input
1.26 crook 8194: @cindex newline character on input
1.1 anton 8195: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
8196: lines. One of these characters is typically produced when you type the
8197: @kbd{Enter} or @kbd{Return} key.
8198:
8199: @item maximum size of a counted string:
8200: @cindex maximum size of a counted string
8201: @cindex counted string, maximum size
8202: @code{s" /counted-string" environment? drop .}. Currently 255 characters
8203: on all ports, but this may change.
8204:
8205: @item maximum size of a parsed string:
8206: @cindex maximum size of a parsed string
8207: @cindex parsed string, maximum size
8208: Given by the constant @code{/line}. Currently 255 characters.
8209:
8210: @item maximum size of a definition name, in characters:
8211: @cindex maximum size of a definition name, in characters
8212: @cindex name, maximum length
8213: 31
8214:
8215: @item maximum string length for @code{ENVIRONMENT?}, in characters:
8216: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
8217: @cindex @code{ENVIRONMENT?} string length, maximum
8218: 31
8219:
8220: @item method of selecting the user input device:
8221: @cindex user input device, method of selecting
8222: The user input device is the standard input. There is currently no way to
8223: change it from within Gforth. However, the input can typically be
8224: redirected in the command line that starts Gforth.
8225:
8226: @item method of selecting the user output device:
8227: @cindex user output device, method of selecting
8228: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 8229: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
8230: output when the user output device is a terminal, otherwise the output
8231: is buffered.
1.1 anton 8232:
8233: @item methods of dictionary compilation:
8234: What are we expected to document here?
8235:
8236: @item number of bits in one address unit:
8237: @cindex number of bits in one address unit
8238: @cindex address unit, size in bits
8239: @code{s" address-units-bits" environment? drop .}. 8 in all current
8240: ports.
8241:
8242: @item number representation and arithmetic:
8243: @cindex number representation and arithmetic
8244: Processor-dependent. Binary two's complement on all current ports.
8245:
8246: @item ranges for integer types:
8247: @cindex ranges for integer types
8248: @cindex integer types, ranges
8249: Installation-dependent. Make environmental queries for @code{MAX-N},
8250: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
8251: unsigned (and positive) types is 0. The lower bound for signed types on
8252: two's complement and one's complement machines machines can be computed
8253: by adding 1 to the upper bound.
8254:
8255: @item read-only data space regions:
8256: @cindex read-only data space regions
8257: @cindex data-space, read-only regions
8258: The whole Forth data space is writable.
8259:
8260: @item size of buffer at @code{WORD}:
8261: @cindex size of buffer at @code{WORD}
8262: @cindex @code{WORD} buffer size
8263: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
8264: shared with the pictured numeric output string. If overwriting
8265: @code{PAD} is acceptable, it is as large as the remaining dictionary
8266: space, although only as much can be sensibly used as fits in a counted
8267: string.
8268:
8269: @item size of one cell in address units:
8270: @cindex cell size
8271: @code{1 cells .}.
8272:
8273: @item size of one character in address units:
8274: @cindex char size
8275: @code{1 chars .}. 1 on all current ports.
8276:
8277: @item size of the keyboard terminal buffer:
8278: @cindex size of the keyboard terminal buffer
8279: @cindex terminal buffer, size
8280: Varies. You can determine the size at a specific time using @code{lp@@
8281: tib - .}. It is shared with the locals stack and TIBs of files that
8282: include the current file. You can change the amount of space for TIBs
8283: and locals stack at Gforth startup with the command line option
8284: @code{-l}.
8285:
8286: @item size of the pictured numeric output buffer:
8287: @cindex size of the pictured numeric output buffer
8288: @cindex pictured numeric output buffer, size
8289: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
8290: shared with @code{WORD}.
8291:
8292: @item size of the scratch area returned by @code{PAD}:
8293: @cindex size of the scratch area returned by @code{PAD}
8294: @cindex @code{PAD} size
8295: The remainder of dictionary space. @code{unused pad here - - .}.
8296:
8297: @item system case-sensitivity characteristics:
8298: @cindex case-sensitivity characteristics
1.26 crook 8299: Dictionary searches are case-insensitive (except in
1.1 anton 8300: @code{TABLE}s). However, as explained above under @i{character-set
8301: extensions}, the matching for non-ASCII characters is determined by the
8302: locale you are using. In the default @code{C} locale all non-ASCII
8303: characters are matched case-sensitively.
8304:
8305: @item system prompt:
8306: @cindex system prompt
8307: @cindex prompt
8308: @code{ ok} in interpret state, @code{ compiled} in compile state.
8309:
8310: @item division rounding:
8311: @cindex division rounding
8312: installation dependent. @code{s" floored" environment? drop .}. We leave
8313: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
8314: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
8315:
8316: @item values of @code{STATE} when true:
8317: @cindex @code{STATE} values
8318: -1.
8319:
8320: @item values returned after arithmetic overflow:
8321: On two's complement machines, arithmetic is performed modulo
8322: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
8323: arithmetic (with appropriate mapping for signed types). Division by zero
8324: typically results in a @code{-55 throw} (Floating-point unidentified
8325: fault), although a @code{-10 throw} (divide by zero) would be more
8326: appropriate.
8327:
8328: @item whether the current definition can be found after @t{DOES>}:
8329: @cindex @t{DOES>}, visibility of current definition
8330: No.
8331:
8332: @end table
8333:
8334: @c ---------------------------------------------------------------------
8335: @node core-ambcond, core-other, core-idef, The Core Words
8336: @subsection Ambiguous conditions
8337: @c ---------------------------------------------------------------------
8338: @cindex core words, ambiguous conditions
8339: @cindex ambiguous conditions, core words
8340:
8341: @table @i
8342:
8343: @item a name is neither a word nor a number:
8344: @cindex name not found
1.26 crook 8345: @cindex undefined word
1.1 anton 8346: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
8347: preserves the data and FP stack, so you don't lose more work than
8348: necessary.
8349:
8350: @item a definition name exceeds the maximum length allowed:
1.26 crook 8351: @cindex word name too long
1.1 anton 8352: @code{-19 throw} (Word name too long)
8353:
8354: @item addressing a region not inside the various data spaces of the forth system:
8355: @cindex Invalid memory address
8356: The stacks, code space and name space are accessible. Machine code space is
8357: typically readable. Accessing other addresses gives results dependent on
8358: the operating system. On decent systems: @code{-9 throw} (Invalid memory
8359: address).
8360:
8361: @item argument type incompatible with parameter:
1.26 crook 8362: @cindex argument type mismatch
1.1 anton 8363: This is usually not caught. Some words perform checks, e.g., the control
8364: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
8365: mismatch).
8366:
8367: @item attempting to obtain the execution token of a word with undefined execution semantics:
8368: @cindex Interpreting a compile-only word, for @code{'} etc.
8369: @cindex execution token of words with undefined execution semantics
8370: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
8371: get an execution token for @code{compile-only-error} (which performs a
8372: @code{-14 throw} when executed).
8373:
8374: @item dividing by zero:
8375: @cindex dividing by zero
8376: @cindex floating point unidentified fault, integer division
1.24 anton 8377: On better platforms, this produces a @code{-10 throw} (Division by
8378: zero); on other systems, this typically results in a @code{-55 throw}
8379: (Floating-point unidentified fault).
1.1 anton 8380:
8381: @item insufficient data stack or return stack space:
8382: @cindex insufficient data stack or return stack space
8383: @cindex stack overflow
1.26 crook 8384: @cindex address alignment exception, stack overflow
1.1 anton 8385: @cindex Invalid memory address, stack overflow
8386: Depending on the operating system, the installation, and the invocation
8387: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 8388: it is not checked. If it is checked, you typically get a @code{-3 throw}
8389: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
8390: throw} (Invalid memory address) (depending on the platform and how you
8391: achieved the overflow) as soon as the overflow happens. If it is not
8392: checked, overflows typically result in mysterious illegal memory
8393: accesses, producing @code{-9 throw} (Invalid memory address) or
8394: @code{-23 throw} (Address alignment exception); they might also destroy
8395: the internal data structure of @code{ALLOCATE} and friends, resulting in
8396: various errors in these words.
1.1 anton 8397:
8398: @item insufficient space for loop control parameters:
8399: @cindex insufficient space for loop control parameters
8400: like other return stack overflows.
8401:
8402: @item insufficient space in the dictionary:
8403: @cindex insufficient space in the dictionary
8404: @cindex dictionary overflow
1.12 anton 8405: If you try to allot (either directly with @code{allot}, or indirectly
8406: with @code{,}, @code{create} etc.) more memory than available in the
8407: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
8408: to access memory beyond the end of the dictionary, the results are
8409: similar to stack overflows.
1.1 anton 8410:
8411: @item interpreting a word with undefined interpretation semantics:
8412: @cindex interpreting a word with undefined interpretation semantics
8413: @cindex Interpreting a compile-only word
8414: For some words, we have defined interpretation semantics. For the
8415: others: @code{-14 throw} (Interpreting a compile-only word).
8416:
8417: @item modifying the contents of the input buffer or a string literal:
8418: @cindex modifying the contents of the input buffer or a string literal
8419: These are located in writable memory and can be modified.
8420:
8421: @item overflow of the pictured numeric output string:
8422: @cindex overflow of the pictured numeric output string
8423: @cindex pictured numeric output string, overflow
1.24 anton 8424: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 8425:
8426: @item parsed string overflow:
8427: @cindex parsed string overflow
8428: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
8429:
8430: @item producing a result out of range:
8431: @cindex result out of range
8432: On two's complement machines, arithmetic is performed modulo
8433: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
8434: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 8435: typically results in a @code{-10 throw} (divide by zero) or @code{-55
8436: throw} (floating point unidentified fault). @code{convert} and
8437: @code{>number} currently overflow silently.
1.1 anton 8438:
8439: @item reading from an empty data or return stack:
8440: @cindex stack empty
8441: @cindex stack underflow
1.24 anton 8442: @cindex return stack underflow
1.1 anton 8443: The data stack is checked by the outer (aka text) interpreter after
8444: every word executed. If it has underflowed, a @code{-4 throw} (Stack
8445: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 8446: depending on operating system, installation, and invocation. If they are
8447: caught by a check, they typically result in @code{-4 throw} (Stack
8448: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
8449: (Invalid memory address), depending on the platform and which stack
8450: underflows and by how much. Note that even if the system uses checking
8451: (through the MMU), your program may have to underflow by a significant
8452: number of stack items to trigger the reaction (the reason for this is
8453: that the MMU, and therefore the checking, works with a page-size
8454: granularity). If there is no checking, the symptoms resulting from an
8455: underflow are similar to those from an overflow. Unbalanced return
8456: stack errors result in a variaty of symptoms, including @code{-9 throw}
8457: (Invalid memory address) and Illegal Instruction (typically @code{-260
8458: throw}).
1.1 anton 8459:
8460: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
8461: @cindex unexpected end of the input buffer
8462: @cindex zero-length string as a name
8463: @cindex Attempt to use zero-length string as a name
8464: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
8465: use zero-length string as a name). Words like @code{'} probably will not
8466: find what they search. Note that it is possible to create zero-length
8467: names with @code{nextname} (should it not?).
8468:
8469: @item @code{>IN} greater than input buffer:
8470: @cindex @code{>IN} greater than input buffer
8471: The next invocation of a parsing word returns a string with length 0.
8472:
8473: @item @code{RECURSE} appears after @code{DOES>}:
8474: @cindex @code{RECURSE} appears after @code{DOES>}
8475: Compiles a recursive call to the defining word, not to the defined word.
8476:
8477: @item argument input source different than current input source for @code{RESTORE-INPUT}:
8478: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 8479: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 8480: @cindex @code{RESTORE-INPUT}, Argument type mismatch
8481: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
8482: the end of the file was reached), its source-id may be
8483: reused. Therefore, restoring an input source specification referencing a
8484: closed file may lead to unpredictable results instead of a @code{-12
8485: THROW}.
8486:
8487: In the future, Gforth may be able to restore input source specifications
8488: from other than the current input source.
8489:
8490: @item data space containing definitions gets de-allocated:
8491: @cindex data space containing definitions gets de-allocated
8492: Deallocation with @code{allot} is not checked. This typically results in
8493: memory access faults or execution of illegal instructions.
8494:
8495: @item data space read/write with incorrect alignment:
8496: @cindex data space read/write with incorrect alignment
8497: @cindex alignment faults
1.26 crook 8498: @cindex address alignment exception
1.1 anton 8499: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 8500: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 8501: alignment turned on, incorrect alignment results in a @code{-9 throw}
8502: (Invalid memory address). There are reportedly some processors with
1.12 anton 8503: alignment restrictions that do not report violations.
1.1 anton 8504:
8505: @item data space pointer not properly aligned, @code{,}, @code{C,}:
8506: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
8507: Like other alignment errors.
8508:
8509: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
8510: Like other stack underflows.
8511:
8512: @item loop control parameters not available:
8513: @cindex loop control parameters not available
8514: Not checked. The counted loop words simply assume that the top of return
8515: stack items are loop control parameters and behave accordingly.
8516:
8517: @item most recent definition does not have a name (@code{IMMEDIATE}):
8518: @cindex most recent definition does not have a name (@code{IMMEDIATE})
8519: @cindex last word was headerless
8520: @code{abort" last word was headerless"}.
8521:
8522: @item name not defined by @code{VALUE} used by @code{TO}:
8523: @cindex name not defined by @code{VALUE} used by @code{TO}
8524: @cindex @code{TO} on non-@code{VALUE}s
8525: @cindex Invalid name argument, @code{TO}
8526: @code{-32 throw} (Invalid name argument) (unless name is a local or was
8527: defined by @code{CONSTANT}; in the latter case it just changes the constant).
8528:
8529: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
8530: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 8531: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 8532: @code{-13 throw} (Undefined word)
8533:
8534: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
8535: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
8536: Gforth behaves as if they were of the same type. I.e., you can predict
8537: the behaviour by interpreting all parameters as, e.g., signed.
8538:
8539: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
8540: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
8541: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
8542: compilation semantics of @code{TO}.
8543:
8544: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 8545: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 8546: @cindex @code{WORD}, string overflow
8547: Not checked. The string will be ok, but the count will, of course,
8548: contain only the least significant bits of the length.
8549:
8550: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
8551: @cindex @code{LSHIFT}, large shift counts
8552: @cindex @code{RSHIFT}, large shift counts
8553: Processor-dependent. Typical behaviours are returning 0 and using only
8554: the low bits of the shift count.
8555:
8556: @item word not defined via @code{CREATE}:
8557: @cindex @code{>BODY} of non-@code{CREATE}d words
8558: @code{>BODY} produces the PFA of the word no matter how it was defined.
8559:
8560: @cindex @code{DOES>} of non-@code{CREATE}d words
8561: @code{DOES>} changes the execution semantics of the last defined word no
8562: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
8563: @code{CREATE , DOES>}.
8564:
8565: @item words improperly used outside @code{<#} and @code{#>}:
8566: Not checked. As usual, you can expect memory faults.
8567:
8568: @end table
8569:
8570:
8571: @c ---------------------------------------------------------------------
8572: @node core-other, , core-ambcond, The Core Words
8573: @subsection Other system documentation
8574: @c ---------------------------------------------------------------------
8575: @cindex other system documentation, core words
8576: @cindex core words, other system documentation
8577:
8578: @table @i
8579: @item nonstandard words using @code{PAD}:
8580: @cindex @code{PAD} use by nonstandard words
8581: None.
8582:
8583: @item operator's terminal facilities available:
8584: @cindex operator's terminal facilities available
8585: After processing the command line, Gforth goes into interactive mode,
8586: and you can give commands to Gforth interactively. The actual facilities
8587: available depend on how you invoke Gforth.
8588:
8589: @item program data space available:
8590: @cindex program data space available
8591: @cindex data space available
8592: @code{UNUSED .} gives the remaining dictionary space. The total
8593: dictionary space can be specified with the @code{-m} switch
8594: (@pxref{Invoking Gforth}) when Gforth starts up.
8595:
8596: @item return stack space available:
8597: @cindex return stack space available
8598: You can compute the total return stack space in cells with
8599: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
8600: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
8601:
8602: @item stack space available:
8603: @cindex stack space available
8604: You can compute the total data stack space in cells with
8605: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
8606: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
8607:
8608: @item system dictionary space required, in address units:
8609: @cindex system dictionary space required, in address units
8610: Type @code{here forthstart - .} after startup. At the time of this
8611: writing, this gives 80080 (bytes) on a 32-bit system.
8612: @end table
8613:
8614:
8615: @c =====================================================================
8616: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
8617: @section The optional Block word set
8618: @c =====================================================================
8619: @cindex system documentation, block words
8620: @cindex block words, system documentation
8621:
8622: @menu
8623: * block-idef:: Implementation Defined Options
8624: * block-ambcond:: Ambiguous Conditions
8625: * block-other:: Other System Documentation
8626: @end menu
8627:
8628:
8629: @c ---------------------------------------------------------------------
8630: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
8631: @subsection Implementation Defined Options
8632: @c ---------------------------------------------------------------------
8633: @cindex implementation-defined options, block words
8634: @cindex block words, implementation-defined options
8635:
8636: @table @i
8637: @item the format for display by @code{LIST}:
8638: @cindex @code{LIST} display format
8639: First the screen number is displayed, then 16 lines of 64 characters,
8640: each line preceded by the line number.
8641:
8642: @item the length of a line affected by @code{\}:
8643: @cindex length of a line affected by @code{\}
8644: @cindex @code{\}, line length in blocks
8645: 64 characters.
8646: @end table
8647:
8648:
8649: @c ---------------------------------------------------------------------
8650: @node block-ambcond, block-other, block-idef, The optional Block word set
8651: @subsection Ambiguous conditions
8652: @c ---------------------------------------------------------------------
8653: @cindex block words, ambiguous conditions
8654: @cindex ambiguous conditions, block words
8655:
8656: @table @i
8657: @item correct block read was not possible:
8658: @cindex block read not possible
8659: Typically results in a @code{throw} of some OS-derived value (between
8660: -512 and -2048). If the blocks file was just not long enough, blanks are
8661: supplied for the missing portion.
8662:
8663: @item I/O exception in block transfer:
8664: @cindex I/O exception in block transfer
8665: @cindex block transfer, I/O exception
8666: Typically results in a @code{throw} of some OS-derived value (between
8667: -512 and -2048).
8668:
8669: @item invalid block number:
8670: @cindex invalid block number
8671: @cindex block number invalid
8672: @code{-35 throw} (Invalid block number)
8673:
8674: @item a program directly alters the contents of @code{BLK}:
8675: @cindex @code{BLK}, altering @code{BLK}
8676: The input stream is switched to that other block, at the same
8677: position. If the storing to @code{BLK} happens when interpreting
8678: non-block input, the system will get quite confused when the block ends.
8679:
8680: @item no current block buffer for @code{UPDATE}:
8681: @cindex @code{UPDATE}, no current block buffer
8682: @code{UPDATE} has no effect.
8683:
8684: @end table
8685:
8686: @c ---------------------------------------------------------------------
8687: @node block-other, , block-ambcond, The optional Block word set
8688: @subsection Other system documentation
8689: @c ---------------------------------------------------------------------
8690: @cindex other system documentation, block words
8691: @cindex block words, other system documentation
8692:
8693: @table @i
8694: @item any restrictions a multiprogramming system places on the use of buffer addresses:
8695: No restrictions (yet).
8696:
8697: @item the number of blocks available for source and data:
8698: depends on your disk space.
8699:
8700: @end table
8701:
8702:
8703: @c =====================================================================
8704: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
8705: @section The optional Double Number word set
8706: @c =====================================================================
8707: @cindex system documentation, double words
8708: @cindex double words, system documentation
8709:
8710: @menu
8711: * double-ambcond:: Ambiguous Conditions
8712: @end menu
8713:
8714:
8715: @c ---------------------------------------------------------------------
8716: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
8717: @subsection Ambiguous conditions
8718: @c ---------------------------------------------------------------------
8719: @cindex double words, ambiguous conditions
8720: @cindex ambiguous conditions, double words
8721:
8722: @table @i
8723: @item @var{d} outside of range of @var{n} in @code{D>S}:
8724: @cindex @code{D>S}, @var{d} out of range of @var{n}
8725: The least significant cell of @var{d} is produced.
8726:
8727: @end table
8728:
8729:
8730: @c =====================================================================
8731: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
8732: @section The optional Exception word set
8733: @c =====================================================================
8734: @cindex system documentation, exception words
8735: @cindex exception words, system documentation
8736:
8737: @menu
8738: * exception-idef:: Implementation Defined Options
8739: @end menu
8740:
8741:
8742: @c ---------------------------------------------------------------------
8743: @node exception-idef, , The optional Exception word set, The optional Exception word set
8744: @subsection Implementation Defined Options
8745: @c ---------------------------------------------------------------------
8746: @cindex implementation-defined options, exception words
8747: @cindex exception words, implementation-defined options
8748:
8749: @table @i
8750: @item @code{THROW}-codes used in the system:
8751: @cindex @code{THROW}-codes used in the system
8752: The codes -256@minus{}-511 are used for reporting signals. The mapping
8753: from OS signal numbers to throw codes is -256@minus{}@var{signal}. The
8754: codes -512@minus{}-2047 are used for OS errors (for file and memory
8755: allocation operations). The mapping from OS error numbers to throw codes
8756: is -512@minus{}@code{errno}. One side effect of this mapping is that
8757: undefined OS errors produce a message with a strange number; e.g.,
8758: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
8759: @end table
8760:
8761: @c =====================================================================
8762: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
8763: @section The optional Facility word set
8764: @c =====================================================================
8765: @cindex system documentation, facility words
8766: @cindex facility words, system documentation
8767:
8768: @menu
8769: * facility-idef:: Implementation Defined Options
8770: * facility-ambcond:: Ambiguous Conditions
8771: @end menu
8772:
8773:
8774: @c ---------------------------------------------------------------------
8775: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
8776: @subsection Implementation Defined Options
8777: @c ---------------------------------------------------------------------
8778: @cindex implementation-defined options, facility words
8779: @cindex facility words, implementation-defined options
8780:
8781: @table @i
8782: @item encoding of keyboard events (@code{EKEY}):
8783: @cindex keyboard events, encoding in @code{EKEY}
8784: @cindex @code{EKEY}, encoding of keyboard events
8785: Not yet implemented.
8786:
8787: @item duration of a system clock tick:
8788: @cindex duration of a system clock tick
8789: @cindex clock tick duration
8790: System dependent. With respect to @code{MS}, the time is specified in
8791: microseconds. How well the OS and the hardware implement this, is
8792: another question.
8793:
8794: @item repeatability to be expected from the execution of @code{MS}:
8795: @cindex repeatability to be expected from the execution of @code{MS}
8796: @cindex @code{MS}, repeatability to be expected
8797: System dependent. On Unix, a lot depends on load. If the system is
8798: lightly loaded, and the delay is short enough that Gforth does not get
8799: swapped out, the performance should be acceptable. Under MS-DOS and
8800: other single-tasking systems, it should be good.
8801:
8802: @end table
8803:
8804:
8805: @c ---------------------------------------------------------------------
8806: @node facility-ambcond, , facility-idef, The optional Facility word set
8807: @subsection Ambiguous conditions
8808: @c ---------------------------------------------------------------------
8809: @cindex facility words, ambiguous conditions
8810: @cindex ambiguous conditions, facility words
8811:
8812: @table @i
8813: @item @code{AT-XY} can't be performed on user output device:
8814: @cindex @code{AT-XY} can't be performed on user output device
8815: Largely terminal dependent. No range checks are done on the arguments.
8816: No errors are reported. You may see some garbage appearing, you may see
8817: simply nothing happen.
8818:
8819: @end table
8820:
8821:
8822: @c =====================================================================
8823: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
8824: @section The optional File-Access word set
8825: @c =====================================================================
8826: @cindex system documentation, file words
8827: @cindex file words, system documentation
8828:
8829: @menu
8830: * file-idef:: Implementation Defined Options
8831: * file-ambcond:: Ambiguous Conditions
8832: @end menu
8833:
8834: @c ---------------------------------------------------------------------
8835: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
8836: @subsection Implementation Defined Options
8837: @c ---------------------------------------------------------------------
8838: @cindex implementation-defined options, file words
8839: @cindex file words, implementation-defined options
8840:
8841: @table @i
8842: @item file access methods used:
8843: @cindex file access methods used
8844: @code{R/O}, @code{R/W} and @code{BIN} work as you would
8845: expect. @code{W/O} translates into the C file opening mode @code{w} (or
8846: @code{wb}): The file is cleared, if it exists, and created, if it does
8847: not (with both @code{open-file} and @code{create-file}). Under Unix
8848: @code{create-file} creates a file with 666 permissions modified by your
8849: umask.
8850:
8851: @item file exceptions:
8852: @cindex file exceptions
8853: The file words do not raise exceptions (except, perhaps, memory access
8854: faults when you pass illegal addresses or file-ids).
8855:
8856: @item file line terminator:
8857: @cindex file line terminator
8858: System-dependent. Gforth uses C's newline character as line
8859: terminator. What the actual character code(s) of this are is
8860: system-dependent.
8861:
8862: @item file name format:
8863: @cindex file name format
8864: System dependent. Gforth just uses the file name format of your OS.
8865:
8866: @item information returned by @code{FILE-STATUS}:
8867: @cindex @code{FILE-STATUS}, returned information
8868: @code{FILE-STATUS} returns the most powerful file access mode allowed
8869: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
8870: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
8871: along with the returned mode.
8872:
8873: @item input file state after an exception when including source:
8874: @cindex exception when including source
8875: All files that are left via the exception are closed.
8876:
8877: @item @var{ior} values and meaning:
8878: @cindex @var{ior} values and meaning
8879: The @var{ior}s returned by the file and memory allocation words are
8880: intended as throw codes. They typically are in the range
8881: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
8882: @var{ior}s is -512@minus{}@var{errno}.
8883:
8884: @item maximum depth of file input nesting:
8885: @cindex maximum depth of file input nesting
8886: @cindex file input nesting, maximum depth
8887: limited by the amount of return stack, locals/TIB stack, and the number
8888: of open files available. This should not give you troubles.
8889:
8890: @item maximum size of input line:
8891: @cindex maximum size of input line
8892: @cindex input line size, maximum
8893: @code{/line}. Currently 255.
8894:
8895: @item methods of mapping block ranges to files:
8896: @cindex mapping block ranges to files
8897: @cindex files containing blocks
8898: @cindex blocks in files
8899: By default, blocks are accessed in the file @file{blocks.fb} in the
8900: current working directory. The file can be switched with @code{USE}.
8901:
8902: @item number of string buffers provided by @code{S"}:
8903: @cindex @code{S"}, number of string buffers
8904: 1
8905:
8906: @item size of string buffer used by @code{S"}:
8907: @cindex @code{S"}, size of string buffer
8908: @code{/line}. currently 255.
8909:
8910: @end table
8911:
8912: @c ---------------------------------------------------------------------
8913: @node file-ambcond, , file-idef, The optional File-Access word set
8914: @subsection Ambiguous conditions
8915: @c ---------------------------------------------------------------------
8916: @cindex file words, ambiguous conditions
8917: @cindex ambiguous conditions, file words
8918:
8919: @table @i
8920: @item attempting to position a file outside its boundaries:
8921: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
8922: @code{REPOSITION-FILE} is performed as usual: Afterwards,
8923: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
8924:
8925: @item attempting to read from file positions not yet written:
8926: @cindex reading from file positions not yet written
8927: End-of-file, i.e., zero characters are read and no error is reported.
8928:
8929: @item @var{file-id} is invalid (@code{INCLUDE-FILE}):
8930: @cindex @code{INCLUDE-FILE}, @var{file-id} is invalid
8931: An appropriate exception may be thrown, but a memory fault or other
8932: problem is more probable.
8933:
8934: @item I/O exception reading or closing @var{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
8935: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @var{file-id}
8936: @cindex @code{INCLUDED}, I/O exception reading or closing @var{file-id}
8937: The @var{ior} produced by the operation, that discovered the problem, is
8938: thrown.
8939:
8940: @item named file cannot be opened (@code{INCLUDED}):
8941: @cindex @code{INCLUDED}, named file cannot be opened
8942: The @var{ior} produced by @code{open-file} is thrown.
8943:
8944: @item requesting an unmapped block number:
8945: @cindex unmapped block numbers
8946: There are no unmapped legal block numbers. On some operating systems,
8947: writing a block with a large number may overflow the file system and
8948: have an error message as consequence.
8949:
8950: @item using @code{source-id} when @code{blk} is non-zero:
8951: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
8952: @code{source-id} performs its function. Typically it will give the id of
8953: the source which loaded the block. (Better ideas?)
8954:
8955: @end table
8956:
8957:
8958: @c =====================================================================
8959: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
8960: @section The optional Floating-Point word set
8961: @c =====================================================================
8962: @cindex system documentation, floating-point words
8963: @cindex floating-point words, system documentation
8964:
8965: @menu
8966: * floating-idef:: Implementation Defined Options
8967: * floating-ambcond:: Ambiguous Conditions
8968: @end menu
8969:
8970:
8971: @c ---------------------------------------------------------------------
8972: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
8973: @subsection Implementation Defined Options
8974: @c ---------------------------------------------------------------------
8975: @cindex implementation-defined options, floating-point words
8976: @cindex floating-point words, implementation-defined options
8977:
8978: @table @i
8979: @item format and range of floating point numbers:
8980: @cindex format and range of floating point numbers
8981: @cindex floating point numbers, format and range
8982: System-dependent; the @code{double} type of C.
8983:
8984: @item results of @code{REPRESENT} when @var{float} is out of range:
8985: @cindex @code{REPRESENT}, results when @var{float} is out of range
8986: System dependent; @code{REPRESENT} is implemented using the C library
8987: function @code{ecvt()} and inherits its behaviour in this respect.
8988:
8989: @item rounding or truncation of floating-point numbers:
8990: @cindex rounding of floating-point numbers
8991: @cindex truncation of floating-point numbers
8992: @cindex floating-point numbers, rounding or truncation
8993: System dependent; the rounding behaviour is inherited from the hosting C
8994: compiler. IEEE-FP-based (i.e., most) systems by default round to
8995: nearest, and break ties by rounding to even (i.e., such that the last
8996: bit of the mantissa is 0).
8997:
8998: @item size of floating-point stack:
8999: @cindex floating-point stack size
9000: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
9001: the floating-point stack (in floats). You can specify this on startup
9002: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
9003:
9004: @item width of floating-point stack:
9005: @cindex floating-point stack width
9006: @code{1 floats}.
9007:
9008: @end table
9009:
9010:
9011: @c ---------------------------------------------------------------------
9012: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
9013: @subsection Ambiguous conditions
9014: @c ---------------------------------------------------------------------
9015: @cindex floating-point words, ambiguous conditions
9016: @cindex ambiguous conditions, floating-point words
9017:
9018: @table @i
9019: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
9020: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
9021: System-dependent. Typically results in a @code{-23 THROW} like other
9022: alignment violations.
9023:
9024: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
9025: @cindex @code{f@@} used with an address that is not float aligned
9026: @cindex @code{f!} used with an address that is not float aligned
9027: System-dependent. Typically results in a @code{-23 THROW} like other
9028: alignment violations.
9029:
9030: @item floating-point result out of range:
9031: @cindex floating-point result out of range
9032: System-dependent. Can result in a @code{-55 THROW} (Floating-point
9033: unidentified fault), or can produce a special value representing, e.g.,
9034: Infinity.
9035:
9036: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
9037: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
9038: System-dependent. Typically results in an alignment fault like other
9039: alignment violations.
9040:
9041: @item @code{BASE} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
9042: @cindex @code{BASE} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
9043: The floating-point number is converted into decimal nonetheless.
9044:
9045: @item Both arguments are equal to zero (@code{FATAN2}):
9046: @cindex @code{FATAN2}, both arguments are equal to zero
9047: System-dependent. @code{FATAN2} is implemented using the C library
9048: function @code{atan2()}.
9049:
9050: @item Using @code{FTAN} on an argument @var{r1} where cos(@var{r1}) is zero:
9051: @cindex @code{FTAN} on an argument @var{r1} where cos(@var{r1}) is zero
9052: System-dependent. Anyway, typically the cos of @var{r1} will not be zero
9053: because of small errors and the tan will be a very large (or very small)
9054: but finite number.
9055:
9056: @item @var{d} cannot be presented precisely as a float in @code{D>F}:
9057: @cindex @code{D>F}, @var{d} cannot be presented precisely as a float
9058: The result is rounded to the nearest float.
9059:
9060: @item dividing by zero:
9061: @cindex dividing by zero, floating-point
9062: @cindex floating-point dividing by zero
9063: @cindex floating-point unidentified fault, FP divide-by-zero
9064: @code{-55 throw} (Floating-point unidentified fault)
9065:
9066: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
9067: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
9068: System dependent. On IEEE-FP based systems the number is converted into
9069: an infinity.
9070:
9071: @item @var{float}<1 (@code{FACOSH}):
9072: @cindex @code{FACOSH}, @var{float}<1
9073: @cindex floating-point unidentified fault, @code{FACOSH}
9074: @code{-55 throw} (Floating-point unidentified fault)
9075:
9076: @item @var{float}=<-1 (@code{FLNP1}):
9077: @cindex @code{FLNP1}, @var{float}=<-1
9078: @cindex floating-point unidentified fault, @code{FLNP1}
9079: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
9080: negative infinity is typically produced for @var{float}=-1.
9081:
9082: @item @var{float}=<0 (@code{FLN}, @code{FLOG}):
9083: @cindex @code{FLN}, @var{float}=<0
9084: @cindex @code{FLOG}, @var{float}=<0
9085: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
9086: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
9087: negative infinity is typically produced for @var{float}=0.
9088:
9089: @item @var{float}<0 (@code{FASINH}, @code{FSQRT}):
9090: @cindex @code{FASINH}, @var{float}<0
9091: @cindex @code{FSQRT}, @var{float}<0
9092: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
9093: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
9094: produces values for these inputs on my Linux box (Bug in the C library?)
9095:
9096: @item |@var{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
9097: @cindex @code{FACOS}, |@var{float}|>1
9098: @cindex @code{FASIN}, |@var{float}|>1
9099: @cindex @code{FATANH}, |@var{float}|>1
9100: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
9101: @code{-55 throw} (Floating-point unidentified fault).
9102:
9103: @item integer part of float cannot be represented by @var{d} in @code{F>D}:
9104: @cindex @code{F>D}, integer part of float cannot be represented by @var{d}
9105: @cindex floating-point unidentified fault, @code{F>D}
9106: @code{-55 throw} (Floating-point unidentified fault).
9107:
9108: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
9109: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
9110: This does not happen.
9111: @end table
9112:
9113: @c =====================================================================
9114: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
9115: @section The optional Locals word set
9116: @c =====================================================================
9117: @cindex system documentation, locals words
9118: @cindex locals words, system documentation
9119:
9120: @menu
9121: * locals-idef:: Implementation Defined Options
9122: * locals-ambcond:: Ambiguous Conditions
9123: @end menu
9124:
9125:
9126: @c ---------------------------------------------------------------------
9127: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
9128: @subsection Implementation Defined Options
9129: @c ---------------------------------------------------------------------
9130: @cindex implementation-defined options, locals words
9131: @cindex locals words, implementation-defined options
9132:
9133: @table @i
9134: @item maximum number of locals in a definition:
9135: @cindex maximum number of locals in a definition
9136: @cindex locals, maximum number in a definition
9137: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
9138: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
9139: characters. The number of locals in a definition is bounded by the size
9140: of locals-buffer, which contains the names of the locals.
9141:
9142: @end table
9143:
9144:
9145: @c ---------------------------------------------------------------------
9146: @node locals-ambcond, , locals-idef, The optional Locals word set
9147: @subsection Ambiguous conditions
9148: @c ---------------------------------------------------------------------
9149: @cindex locals words, ambiguous conditions
9150: @cindex ambiguous conditions, locals words
9151:
9152: @table @i
9153: @item executing a named local in interpretation state:
9154: @cindex local in interpretation state
9155: @cindex Interpreting a compile-only word, for a local
9156: Locals have no interpretation semantics. If you try to perform the
9157: interpretation semantics, you will get a @code{-14 throw} somewhere
9158: (Interpreting a compile-only word). If you perform the compilation
9159: semantics, the locals access will be compiled (irrespective of state).
9160:
9161: @item @var{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
9162: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
9163: @cindex @code{TO} on non-@code{VALUE}s and non-locals
9164: @cindex Invalid name argument, @code{TO}
9165: @code{-32 throw} (Invalid name argument)
9166:
9167: @end table
9168:
9169:
9170: @c =====================================================================
9171: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
9172: @section The optional Memory-Allocation word set
9173: @c =====================================================================
9174: @cindex system documentation, memory-allocation words
9175: @cindex memory-allocation words, system documentation
9176:
9177: @menu
9178: * memory-idef:: Implementation Defined Options
9179: @end menu
9180:
9181:
9182: @c ---------------------------------------------------------------------
9183: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
9184: @subsection Implementation Defined Options
9185: @c ---------------------------------------------------------------------
9186: @cindex implementation-defined options, memory-allocation words
9187: @cindex memory-allocation words, implementation-defined options
9188:
9189: @table @i
9190: @item values and meaning of @var{ior}:
9191: @cindex @var{ior} values and meaning
9192: The @var{ior}s returned by the file and memory allocation words are
9193: intended as throw codes. They typically are in the range
9194: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
9195: @var{ior}s is -512@minus{}@var{errno}.
9196:
9197: @end table
9198:
9199: @c =====================================================================
9200: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
9201: @section The optional Programming-Tools word set
9202: @c =====================================================================
9203: @cindex system documentation, programming-tools words
9204: @cindex programming-tools words, system documentation
9205:
9206: @menu
9207: * programming-idef:: Implementation Defined Options
9208: * programming-ambcond:: Ambiguous Conditions
9209: @end menu
9210:
9211:
9212: @c ---------------------------------------------------------------------
9213: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
9214: @subsection Implementation Defined Options
9215: @c ---------------------------------------------------------------------
9216: @cindex implementation-defined options, programming-tools words
9217: @cindex programming-tools words, implementation-defined options
9218:
9219: @table @i
9220: @item ending sequence for input following @code{;CODE} and @code{CODE}:
9221: @cindex @code{;CODE} ending sequence
9222: @cindex @code{CODE} ending sequence
9223: @code{END-CODE}
9224:
9225: @item manner of processing input following @code{;CODE} and @code{CODE}:
9226: @cindex @code{;CODE}, processing input
9227: @cindex @code{CODE}, processing input
9228: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
9229: the input is processed by the text interpreter, (starting) in interpret
9230: state.
9231:
9232: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
9233: @cindex @code{ASSEMBLER}, search order capability
9234: The ANS Forth search order word set.
9235:
9236: @item source and format of display by @code{SEE}:
9237: @cindex @code{SEE}, source and format of output
9238: The source for @code{see} is the intermediate code used by the inner
9239: interpreter. The current @code{see} tries to output Forth source code
9240: as well as possible.
9241:
9242: @end table
9243:
9244: @c ---------------------------------------------------------------------
9245: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
9246: @subsection Ambiguous conditions
9247: @c ---------------------------------------------------------------------
9248: @cindex programming-tools words, ambiguous conditions
9249: @cindex ambiguous conditions, programming-tools words
9250:
9251: @table @i
9252:
1.21 crook 9253: @item deleting the compilation word list (@code{FORGET}):
9254: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 9255: Not implemented (yet).
9256:
1.26 crook 9257: @item fewer than @var{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
9258: @cindex @code{CS-PICK}, fewer than @var{u}+1 items on the control flow-stack
9259: @cindex @code{CS-ROLL}, fewer than @var{u}+1 items on the control flow-stack
1.1 anton 9260: @cindex control-flow stack underflow
9261: This typically results in an @code{abort"} with a descriptive error
9262: message (may change into a @code{-22 throw} (Control structure mismatch)
9263: in the future). You may also get a memory access error. If you are
9264: unlucky, this ambiguous condition is not caught.
9265:
9266: @item @var{name} can't be found (@code{FORGET}):
9267: @cindex @code{FORGET}, @var{name} can't be found
9268: Not implemented (yet).
9269:
9270: @item @var{name} not defined via @code{CREATE}:
9271: @cindex @code{;CODE}, @var{name} not defined via @code{CREATE}
9272: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
9273: the execution semantics of the last defined word no matter how it was
9274: defined.
9275:
9276: @item @code{POSTPONE} applied to @code{[IF]}:
9277: @cindex @code{POSTPONE} applied to @code{[IF]}
9278: @cindex @code{[IF]} and @code{POSTPONE}
9279: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
9280: equivalent to @code{[IF]}.
9281:
9282: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
9283: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
9284: Continue in the same state of conditional compilation in the next outer
9285: input source. Currently there is no warning to the user about this.
9286:
9287: @item removing a needed definition (@code{FORGET}):
9288: @cindex @code{FORGET}, removing a needed definition
9289: Not implemented (yet).
9290:
9291: @end table
9292:
9293:
9294: @c =====================================================================
9295: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
9296: @section The optional Search-Order word set
9297: @c =====================================================================
9298: @cindex system documentation, search-order words
9299: @cindex search-order words, system documentation
9300:
9301: @menu
9302: * search-idef:: Implementation Defined Options
9303: * search-ambcond:: Ambiguous Conditions
9304: @end menu
9305:
9306:
9307: @c ---------------------------------------------------------------------
9308: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
9309: @subsection Implementation Defined Options
9310: @c ---------------------------------------------------------------------
9311: @cindex implementation-defined options, search-order words
9312: @cindex search-order words, implementation-defined options
9313:
9314: @table @i
9315: @item maximum number of word lists in search order:
9316: @cindex maximum number of word lists in search order
9317: @cindex search order, maximum depth
9318: @code{s" wordlists" environment? drop .}. Currently 16.
9319:
9320: @item minimum search order:
9321: @cindex minimum search order
9322: @cindex search order, minimum
9323: @code{root root}.
9324:
9325: @end table
9326:
9327: @c ---------------------------------------------------------------------
9328: @node search-ambcond, , search-idef, The optional Search-Order word set
9329: @subsection Ambiguous conditions
9330: @c ---------------------------------------------------------------------
9331: @cindex search-order words, ambiguous conditions
9332: @cindex ambiguous conditions, search-order words
9333:
9334: @table @i
1.21 crook 9335: @item changing the compilation word list (during compilation):
9336: @cindex changing the compilation word list (during compilation)
9337: @cindex compilation word list, change before definition ends
9338: The word is entered into the word list that was the compilation word list
1.1 anton 9339: at the start of the definition. Any changes to the name field (e.g.,
9340: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
9341: are applied to the latest defined word (as reported by @code{last} or
1.21 crook 9342: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1 anton 9343:
9344: @item search order empty (@code{previous}):
9345: @cindex @code{previous}, search order empty
1.26 crook 9346: @cindex vocstack empty, @code{previous}
1.1 anton 9347: @code{abort" Vocstack empty"}.
9348:
9349: @item too many word lists in search order (@code{also}):
9350: @cindex @code{also}, too many word lists in search order
1.26 crook 9351: @cindex vocstack full, @code{also}
1.1 anton 9352: @code{abort" Vocstack full"}.
9353:
9354: @end table
9355:
9356: @c ***************************************************************
9357: @node Model, Integrating Gforth, ANS conformance, Top
9358: @chapter Model
9359:
9360: This chapter has yet to be written. It will contain information, on
9361: which internal structures you can rely.
9362:
9363: @c ***************************************************************
9364: @node Integrating Gforth, Emacs and Gforth, Model, Top
9365: @chapter Integrating Gforth into C programs
9366:
9367: This is not yet implemented.
9368:
9369: Several people like to use Forth as scripting language for applications
9370: that are otherwise written in C, C++, or some other language.
9371:
9372: The Forth system ATLAST provides facilities for embedding it into
9373: applications; unfortunately it has several disadvantages: most
9374: importantly, it is not based on ANS Forth, and it is apparently dead
9375: (i.e., not developed further and not supported). The facilities
1.21 crook 9376: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 9377: making the switch should not be hard.
9378:
9379: We also tried to design the interface such that it can easily be
9380: implemented by other Forth systems, so that we may one day arrive at a
9381: standardized interface. Such a standard interface would allow you to
9382: replace the Forth system without having to rewrite C code.
9383:
9384: You embed the Gforth interpreter by linking with the library
9385: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
9386: global symbols in this library that belong to the interface, have the
9387: prefix @code{forth_}. (Global symbols that are used internally have the
9388: prefix @code{gforth_}).
9389:
9390: You can include the declarations of Forth types and the functions and
9391: variables of the interface with @code{#include <forth.h>}.
9392:
9393: Types.
9394:
9395: Variables.
9396:
9397: Data and FP Stack pointer. Area sizes.
9398:
9399: functions.
9400:
9401: forth_init(imagefile)
9402: forth_evaluate(string) exceptions?
9403: forth_goto(address) (or forth_execute(xt)?)
9404: forth_continue() (a corountining mechanism)
9405:
9406: Adding primitives.
9407:
9408: No checking.
9409:
9410: Signals?
9411:
9412: Accessing the Stacks
9413:
1.26 crook 9414: @c ******************************************************************
1.1 anton 9415: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
9416: @chapter Emacs and Gforth
9417: @cindex Emacs and Gforth
9418:
9419: @cindex @file{gforth.el}
9420: @cindex @file{forth.el}
9421: @cindex Rydqvist, Goran
9422: @cindex comment editing commands
9423: @cindex @code{\}, editing with Emacs
9424: @cindex debug tracer editing commands
9425: @cindex @code{~~}, removal with Emacs
9426: @cindex Forth mode in Emacs
9427: Gforth comes with @file{gforth.el}, an improved version of
9428: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 9429: improvements are:
9430:
9431: @itemize @bullet
9432: @item
9433: A better (but still not perfect) handling of indentation.
9434: @item
9435: Comment paragraph filling (@kbd{M-q})
9436: @item
9437: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
9438: @item
9439: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
9440: @end itemize
9441:
9442: I left the stuff I do not use alone, even though some of it only makes
9443: sense for TILE. To get a description of these features, enter Forth mode
9444: and type @kbd{C-h m}.
1.1 anton 9445:
9446: @cindex source location of error or debugging output in Emacs
9447: @cindex error output, finding the source location in Emacs
9448: @cindex debugging output, finding the source location in Emacs
9449: In addition, Gforth supports Emacs quite well: The source code locations
9450: given in error messages, debugging output (from @code{~~}) and failed
9451: assertion messages are in the right format for Emacs' compilation mode
9452: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
9453: Manual}) so the source location corresponding to an error or other
9454: message is only a few keystrokes away (@kbd{C-x `} for the next error,
9455: @kbd{C-c C-c} for the error under the cursor).
9456:
9457: @cindex @file{TAGS} file
9458: @cindex @file{etags.fs}
9459: @cindex viewing the source of a word in Emacs
1.26 crook 9460: Also, if you @code{include} @file{etags.fs}, a new @file{TAGS} file will
9461: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 9462: contains the definitions of all words defined afterwards. You can then
9463: find the source for a word using @kbd{M-.}. Note that emacs can use
9464: several tags files at the same time (e.g., one for the Gforth sources
9465: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
9466: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
9467: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
9468: @file{/usr/local/share/gforth/0.2.0/TAGS}).
9469:
9470: @cindex @file{.emacs}
9471: To get all these benefits, add the following lines to your @file{.emacs}
9472: file:
9473:
9474: @example
9475: (autoload 'forth-mode "gforth.el")
9476: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
9477: @end example
9478:
1.26 crook 9479: @c ******************************************************************
1.1 anton 9480: @node Image Files, Engine, Emacs and Gforth, Top
9481: @chapter Image Files
1.26 crook 9482: @cindex image file
9483: @cindex @file{.fi} files
1.1 anton 9484: @cindex precompiled Forth code
9485: @cindex dictionary in persistent form
9486: @cindex persistent form of dictionary
9487:
9488: An image file is a file containing an image of the Forth dictionary,
9489: i.e., compiled Forth code and data residing in the dictionary. By
9490: convention, we use the extension @code{.fi} for image files.
9491:
9492: @menu
1.18 anton 9493: * Image Licensing Issues:: Distribution terms for images.
9494: * Image File Background:: Why have image files?
9495: * Non-Relocatable Image Files:: don't always work.
9496: * Data-Relocatable Image Files:: are better.
1.1 anton 9497: * Fully Relocatable Image Files:: better yet.
1.18 anton 9498: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
9499: * Running Image Files:: @code{gforth -i @var{file}} or @var{file}.
9500: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 9501: @end menu
9502:
1.18 anton 9503: @node Image Licensing Issues, Image File Background, Image Files, Image Files
9504: @section Image Licensing Issues
9505: @cindex license for images
9506: @cindex image license
9507:
9508: An image created with @code{gforthmi} (@pxref{gforthmi}) or
9509: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
9510: original image; i.e., according to copyright law it is a derived work of
9511: the original image.
9512:
9513: Since Gforth is distributed under the GNU GPL, the newly created image
9514: falls under the GNU GPL, too. In particular, this means that if you
9515: distribute the image, you have to make all of the sources for the image
9516: available, including those you wrote. For details see @ref{License, ,
9517: GNU General Public License (Section 3)}.
9518:
9519: If you create an image with @code{cross} (@pxref{cross.fs}), the image
9520: contains only code compiled from the sources you gave it; if none of
9521: these sources is under the GPL, the terms discussed above do not apply
9522: to the image. However, if your image needs an engine (a gforth binary)
9523: that is under the GPL, you should make sure that you distribute both in
9524: a way that is at most a @emph{mere aggregation}, if you don't want the
9525: terms of the GPL to apply to the image.
9526:
9527: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 9528: @section Image File Background
9529: @cindex image file background
9530:
9531: Our Forth system consists not only of primitives, but also of
9532: definitions written in Forth. Since the Forth compiler itself belongs to
9533: those definitions, it is not possible to start the system with the
9534: primitives and the Forth source alone. Therefore we provide the Forth
1.26 crook 9535: code as an image file in nearly executable form. When Gforth starts up,
9536: a C routine loads the image file into memory, optionally relocates the
9537: addresses, then sets up the memory (stacks etc.) according to
9538: information in the image file, and (finally) starts executing Forth
9539: code.
1.1 anton 9540:
9541: The image file variants represent different compromises between the
9542: goals of making it easy to generate image files and making them
9543: portable.
9544:
9545: @cindex relocation at run-time
1.26 crook 9546: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 9547: run-time. This avoids many of the complications discussed below (image
9548: files are data relocatable without further ado), but costs performance
9549: (one addition per memory access).
9550:
9551: @cindex relocation at load-time
1.26 crook 9552: By contrast, the Gforth loader performs relocation at image load time. The
9553: loader also has to replace tokens that represent primitive calls with the
1.1 anton 9554: appropriate code-field addresses (or code addresses in the case of
9555: direct threading).
9556:
9557: There are three kinds of image files, with different degrees of
9558: relocatability: non-relocatable, data-relocatable, and fully relocatable
9559: image files.
9560:
9561: @cindex image file loader
9562: @cindex relocating loader
9563: @cindex loader for image files
9564: These image file variants have several restrictions in common; they are
9565: caused by the design of the image file loader:
9566:
9567: @itemize @bullet
9568: @item
9569: There is only one segment; in particular, this means, that an image file
9570: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 9571: them). The contents of the stacks are not represented, either.
1.1 anton 9572:
9573: @item
9574: The only kinds of relocation supported are: adding the same offset to
9575: all cells that represent data addresses; and replacing special tokens
9576: with code addresses or with pieces of machine code.
9577:
9578: If any complex computations involving addresses are performed, the
9579: results cannot be represented in the image file. Several applications that
9580: use such computations come to mind:
9581: @itemize @minus
9582: @item
9583: Hashing addresses (or data structures which contain addresses) for table
9584: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
9585: purpose, you will have no problem, because the hash tables are
9586: recomputed automatically when the system is started. If you use your own
9587: hash tables, you will have to do something similar.
9588:
9589: @item
9590: There's a cute implementation of doubly-linked lists that uses
9591: @code{XOR}ed addresses. You could represent such lists as singly-linked
9592: in the image file, and restore the doubly-linked representation on
9593: startup.@footnote{In my opinion, though, you should think thrice before
9594: using a doubly-linked list (whatever implementation).}
9595:
9596: @item
9597: The code addresses of run-time routines like @code{docol:} cannot be
9598: represented in the image file (because their tokens would be replaced by
9599: machine code in direct threaded implementations). As a workaround,
9600: compute these addresses at run-time with @code{>code-address} from the
9601: executions tokens of appropriate words (see the definitions of
9602: @code{docol:} and friends in @file{kernel.fs}).
9603:
9604: @item
9605: On many architectures addresses are represented in machine code in some
9606: shifted or mangled form. You cannot put @code{CODE} words that contain
9607: absolute addresses in this form in a relocatable image file. Workarounds
9608: are representing the address in some relative form (e.g., relative to
9609: the CFA, which is present in some register), or loading the address from
9610: a place where it is stored in a non-mangled form.
9611: @end itemize
9612: @end itemize
9613:
9614: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
9615: @section Non-Relocatable Image Files
9616: @cindex non-relocatable image files
1.26 crook 9617: @cindex image file, non-relocatable
1.1 anton 9618:
9619: These files are simple memory dumps of the dictionary. They are specific
9620: to the executable (i.e., @file{gforth} file) they were created
9621: with. What's worse, they are specific to the place on which the
9622: dictionary resided when the image was created. Now, there is no
9623: guarantee that the dictionary will reside at the same place the next
9624: time you start Gforth, so there's no guarantee that a non-relocatable
9625: image will work the next time (Gforth will complain instead of crashing,
9626: though).
9627:
9628: You can create a non-relocatable image file with
9629:
9630: doc-savesystem
9631:
9632: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
9633: @section Data-Relocatable Image Files
9634: @cindex data-relocatable image files
1.26 crook 9635: @cindex image file, data-relocatable
1.1 anton 9636:
9637: These files contain relocatable data addresses, but fixed code addresses
9638: (instead of tokens). They are specific to the executable (i.e.,
9639: @file{gforth} file) they were created with. For direct threading on some
9640: architectures (e.g., the i386), data-relocatable images do not work. You
9641: get a data-relocatable image, if you use @file{gforthmi} with a
9642: Gforth binary that is not doubly indirect threaded (@pxref{Fully
9643: Relocatable Image Files}).
9644:
9645: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
9646: @section Fully Relocatable Image Files
9647: @cindex fully relocatable image files
1.26 crook 9648: @cindex image file, fully relocatable
1.1 anton 9649:
9650: @cindex @file{kern*.fi}, relocatability
9651: @cindex @file{gforth.fi}, relocatability
9652: These image files have relocatable data addresses, and tokens for code
9653: addresses. They can be used with different binaries (e.g., with and
9654: without debugging) on the same machine, and even across machines with
9655: the same data formats (byte order, cell size, floating point
9656: format). However, they are usually specific to the version of Gforth
9657: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
9658: are fully relocatable.
9659:
9660: There are two ways to create a fully relocatable image file:
9661:
9662: @menu
9663: * gforthmi:: The normal way
9664: * cross.fs:: The hard way
9665: @end menu
9666:
9667: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
9668: @subsection @file{gforthmi}
9669: @cindex @file{comp-i.fs}
9670: @cindex @file{gforthmi}
9671:
9672: You will usually use @file{gforthmi}. If you want to create an
9673: image @var{file} that contains everything you would load by invoking
1.27 crook 9674: Gforth with @code{gforth @var{options}}, you simply say:
1.1 anton 9675: @example
9676: gforthmi @var{file} @var{options}
9677: @end example
9678:
9679: E.g., if you want to create an image @file{asm.fi} that has the file
9680: @file{asm.fs} loaded in addition to the usual stuff, you could do it
9681: like this:
9682:
9683: @example
9684: gforthmi asm.fi asm.fs
9685: @end example
9686:
1.27 crook 9687: @file{gforthmi} is implemented as a sh script and works like this: It
9688: produces two non-relocatable images for different addresses and then
9689: compares them. Its output reflects this: first you see the output (if
9690: any) of the two Gforth invocations that produce the nonrelocatable image
9691: files, then you see the output of the comparing program: It displays the
9692: offset used for data addresses and the offset used for code addresses;
1.1 anton 9693: moreover, for each cell that cannot be represented correctly in the
9694: image files, it displays a line like the following one:
9695:
9696: @example
9697: 78DC BFFFFA50 BFFFFA40
9698: @end example
9699:
9700: This means that at offset $78dc from @code{forthstart}, one input image
9701: contains $bffffa50, and the other contains $bffffa40. Since these cells
9702: cannot be represented correctly in the output image, you should examine
9703: these places in the dictionary and verify that these cells are dead
9704: (i.e., not read before they are written).
9705:
1.27 crook 9706: If you type @file{gforthmi} with no arguments, it prints some usage
9707: instructions.
9708:
1.1 anton 9709: @cindex @code{savesystem} during @file{gforthmi}
9710: @cindex @code{bye} during @file{gforthmi}
9711: @cindex doubly indirect threaded code
9712: @cindex environment variable @code{GFORTHD}
9713: @cindex @code{GFORTHD} environment variable
9714: @cindex @code{gforth-ditc}
9715: There are a few wrinkles: After processing the passed @var{options}, the
9716: words @code{savesystem} and @code{bye} must be visible. A special doubly
9717: indirect threaded version of the @file{gforth} executable is used for
9718: creating the nonrelocatable images; you can pass the exact filename of
9719: this executable through the environment variable @code{GFORTHD}
9720: (default: @file{gforth-ditc}); if you pass a version that is not doubly
9721: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 9722: data-relocatable image (because there is no code address offset). The
9723: normal @file{gforth} executable is used for creating the relocatable
9724: image; you can pass the exact filename of this executable through the
9725: environment variable @code{GFORTH}.
1.1 anton 9726:
9727: @node cross.fs, , gforthmi, Fully Relocatable Image Files
9728: @subsection @file{cross.fs}
9729: @cindex @file{cross.fs}
9730: @cindex cross-compiler
9731: @cindex metacompiler
9732:
9733: You can also use @code{cross}, a batch compiler that accepts a Forth-like
9734: programming language. This @code{cross} language has to be documented
9735: yet.
9736:
9737: @cindex target compiler
9738: @code{cross} also allows you to create image files for machines with
9739: different data sizes and data formats than the one used for generating
9740: the image file. You can also use it to create an application image that
9741: does not contain a Forth compiler. These features are bought with
9742: restrictions and inconveniences in programming. E.g., addresses have to
9743: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
9744: order to make the code relocatable.
9745:
9746:
9747: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
9748: @section Stack and Dictionary Sizes
9749: @cindex image file, stack and dictionary sizes
9750: @cindex dictionary size default
9751: @cindex stack size default
9752:
9753: If you invoke Gforth with a command line flag for the size
9754: (@pxref{Invoking Gforth}), the size you specify is stored in the
9755: dictionary. If you save the dictionary with @code{savesystem} or create
9756: an image with @file{gforthmi}, this size will become the default
9757: for the resulting image file. E.g., the following will create a
1.21 crook 9758: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 9759:
9760: @example
9761: gforthmi gforth.fi -m 1M
9762: @end example
9763:
9764: In other words, if you want to set the default size for the dictionary
9765: and the stacks of an image, just invoke @file{gforthmi} with the
9766: appropriate options when creating the image.
9767:
9768: @cindex stack size, cache-friendly
9769: Note: For cache-friendly behaviour (i.e., good performance), you should
9770: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
9771: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
9772: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
9773:
9774: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
9775: @section Running Image Files
9776: @cindex running image files
9777: @cindex invoking image files
9778: @cindex image file invocation
9779:
9780: @cindex -i, invoke image file
9781: @cindex --image file, invoke image file
9782: You can invoke Gforth with an image file @var{image} instead of the
9783: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
9784: @example
9785: gforth -i @var{image}
9786: @end example
9787:
9788: @cindex executable image file
1.26 crook 9789: @cindex image file, executable
1.1 anton 9790: If your operating system supports starting scripts with a line of the
9791: form @code{#! ...}, you just have to type the image file name to start
9792: Gforth with this image file (note that the file extension @code{.fi} is
9793: just a convention). I.e., to run Gforth with the image file @var{image},
9794: you can just type @var{image} instead of @code{gforth -i @var{image}}.
1.27 crook 9795: This works because every @code{.fi} file starts with a line of this
9796: format:
9797:
9798: @example
9799: #! /usr/local/bin/gforth-0.4.0 -i
9800: @end example
9801:
9802: The file and pathname for the Gforth engine specified on this line is
9803: the specific Gforth executable that it was built against; i.e. the value
9804: of the environment variable @code{GFORTH} at the time that
9805: @file{gforthmi} was executed.
1.1 anton 9806:
1.27 crook 9807: You can make use of the same shell capability to make a Forth source
9808: file into an executable. For example, if you place this text in a file:
1.26 crook 9809:
9810: @example
9811: #! /usr/local/bin/gforth
9812:
9813: ." Hello, world" CR
9814: bye
9815: @end example
9816:
9817: @noindent
1.27 crook 9818: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 9819: directly from the command line. The sequence @code{#!} is used in two
9820: ways; firstly, it is recognised as a ``magic sequence'' by the operating
9821: system, secondly it is treated as a comment character by Gforth. Because
9822: of the second usage, a space is required between @code{#!} and the path
9823: to the executable.
1.27 crook 9824:
9825: The disadvantage of this latter technique, compared with using
9826: @file{gforthmi}, is that it is slower; the Forth source code is compiled
9827: on-the-fly, each time the program is invoked.
9828:
1.26 crook 9829: @comment TODO describe the #! magic with reference to the Power Tools book.
9830:
1.1 anton 9831: doc-#!
9832:
9833: @node Modifying the Startup Sequence, , Running Image Files, Image Files
9834: @section Modifying the Startup Sequence
9835: @cindex startup sequence for image file
9836: @cindex image file initialization sequence
9837: @cindex initialization sequence of image file
9838:
9839: You can add your own initialization to the startup sequence through the
1.26 crook 9840: deferred word @code{'cold}. @code{'cold} is invoked just before the
9841: image-specific command line processing (by default, loading files and
9842: evaluating (@code{-e}) strings) starts.
1.1 anton 9843:
9844: A sequence for adding your initialization usually looks like this:
9845:
9846: @example
9847: :noname
9848: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
9849: ... \ your stuff
9850: ; IS 'cold
9851: @end example
9852:
9853: @cindex turnkey image files
1.26 crook 9854: @cindex image file, turnkey applications
1.1 anton 9855: You can make a turnkey image by letting @code{'cold} execute a word
9856: (your turnkey application) that never returns; instead, it exits Gforth
9857: via @code{bye} or @code{throw}.
9858:
9859: @cindex command-line arguments, access
9860: @cindex arguments on the command line, access
9861: You can access the (image-specific) command-line arguments through the
1.26 crook 9862: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1 anton 9863: access to @code{argv}.
9864:
1.26 crook 9865: If @code{'cold} exits normally, Gforth processes the command-line
9866: arguments as files to be loaded and strings to be evaluated. Therefore,
9867: @code{'cold} should remove the arguments it has used in this case.
9868:
9869: doc-'cold
1.1 anton 9870: doc-argc
9871: doc-argv
9872: doc-arg
9873:
9874:
9875: @c ******************************************************************
1.13 pazsan 9876: @node Engine, Binding to System Library, Image Files, Top
1.1 anton 9877: @chapter Engine
9878: @cindex engine
9879: @cindex virtual machine
9880:
1.26 crook 9881: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 9882: may be helpful for finding your way in the Gforth sources.
9883:
9884: The ideas in this section have also been published in the papers
9885: @cite{ANS fig/GNU/??? Forth} (in German) by Bernd Paysan, presented at
9886: the Forth-Tagung '93 and @cite{A Portable Forth Engine} by M. Anton
9887: Ertl, presented at EuroForth '93; the latter is available at
9888: @*@url{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z}.
9889:
9890: @menu
9891: * Portability::
9892: * Threading::
9893: * Primitives::
9894: * Performance::
9895: @end menu
9896:
9897: @node Portability, Threading, Engine, Engine
9898: @section Portability
9899: @cindex engine portability
9900:
1.26 crook 9901: An important goal of the Gforth Project is availability across a wide
9902: range of personal machines. fig-Forth, and, to a lesser extent, F83,
9903: achieved this goal by manually coding the engine in assembly language
9904: for several then-popular processors. This approach is very
9905: labor-intensive and the results are short-lived due to progress in
9906: computer architecture.
1.1 anton 9907:
9908: @cindex C, using C for the engine
9909: Others have avoided this problem by coding in C, e.g., Mitch Bradley
9910: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
9911: particularly popular for UNIX-based Forths due to the large variety of
9912: architectures of UNIX machines. Unfortunately an implementation in C
9913: does not mix well with the goals of efficiency and with using
9914: traditional techniques: Indirect or direct threading cannot be expressed
9915: in C, and switch threading, the fastest technique available in C, is
9916: significantly slower. Another problem with C is that it is very
9917: cumbersome to express double integer arithmetic.
9918:
9919: @cindex GNU C for the engine
9920: @cindex long long
9921: Fortunately, there is a portable language that does not have these
9922: limitations: GNU C, the version of C processed by the GNU C compiler
9923: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
9924: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
9925: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
9926: threading possible, its @code{long long} type (@pxref{Long Long, ,
9927: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
9928: double numbers@footnote{Unfortunately, long longs are not implemented
9929: properly on all machines (e.g., on alpha-osf1, long longs are only 64
9930: bits, the same size as longs (and pointers), but they should be twice as
1.4 anton 9931: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1 anton 9932: C Manual}). So, we had to implement doubles in C after all. Still, on
9933: most machines we can use long longs and achieve better performance than
9934: with the emulation package.}. GNU C is available for free on all
9935: important (and many unimportant) UNIX machines, VMS, 80386s running
9936: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
9937: on all these machines.
9938:
9939: Writing in a portable language has the reputation of producing code that
9940: is slower than assembly. For our Forth engine we repeatedly looked at
9941: the code produced by the compiler and eliminated most compiler-induced
9942: inefficiencies by appropriate changes in the source code.
9943:
9944: @cindex explicit register declarations
9945: @cindex --enable-force-reg, configuration flag
9946: @cindex -DFORCE_REG
9947: However, register allocation cannot be portably influenced by the
9948: programmer, leading to some inefficiencies on register-starved
9949: machines. We use explicit register declarations (@pxref{Explicit Reg
9950: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
9951: improve the speed on some machines. They are turned on by using the
9952: configuration flag @code{--enable-force-reg} (@code{gcc} switch
9953: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
9954: machine, but also on the compiler version: On some machines some
9955: compiler versions produce incorrect code when certain explicit register
9956: declarations are used. So by default @code{-DFORCE_REG} is not used.
9957:
9958: @node Threading, Primitives, Portability, Engine
9959: @section Threading
9960: @cindex inner interpreter implementation
9961: @cindex threaded code implementation
9962:
9963: @cindex labels as values
9964: GNU C's labels as values extension (available since @code{gcc-2.0},
9965: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
9966: makes it possible to take the address of @var{label} by writing
9967: @code{&&@var{label}}. This address can then be used in a statement like
9968: @code{goto *@var{address}}. I.e., @code{goto *&&x} is the same as
9969: @code{goto x}.
9970:
1.26 crook 9971: @cindex @code{NEXT}, indirect threaded
1.1 anton 9972: @cindex indirect threaded inner interpreter
9973: @cindex inner interpreter, indirect threaded
1.26 crook 9974: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 9975: @example
9976: cfa = *ip++;
9977: ca = *cfa;
9978: goto *ca;
9979: @end example
9980: @cindex instruction pointer
9981: For those unfamiliar with the names: @code{ip} is the Forth instruction
9982: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
9983: execution token and points to the code field of the next word to be
9984: executed; The @code{ca} (code address) fetched from there points to some
9985: executable code, e.g., a primitive or the colon definition handler
9986: @code{docol}.
9987:
1.26 crook 9988: @cindex @code{NEXT}, direct threaded
1.1 anton 9989: @cindex direct threaded inner interpreter
9990: @cindex inner interpreter, direct threaded
9991: Direct threading is even simpler:
9992: @example
9993: ca = *ip++;
9994: goto *ca;
9995: @end example
9996:
9997: Of course we have packaged the whole thing neatly in macros called
1.26 crook 9998: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 9999:
10000: @menu
10001: * Scheduling::
10002: * Direct or Indirect Threaded?::
10003: * DOES>::
10004: @end menu
10005:
10006: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
10007: @subsection Scheduling
10008: @cindex inner interpreter optimization
10009:
10010: There is a little complication: Pipelined and superscalar processors,
10011: i.e., RISC and some modern CISC machines can process independent
10012: instructions while waiting for the results of an instruction. The
10013: compiler usually reorders (schedules) the instructions in a way that
10014: achieves good usage of these delay slots. However, on our first tries
10015: the compiler did not do well on scheduling primitives. E.g., for
10016: @code{+} implemented as
10017: @example
10018: n=sp[0]+sp[1];
10019: sp++;
10020: sp[0]=n;
10021: NEXT;
10022: @end example
1.26 crook 10023: the @code{NEXT} comes strictly after the other code, i.e., there is nearly no
1.1 anton 10024: scheduling. After a little thought the problem becomes clear: The
1.21 crook 10025: compiler cannot know that @code{sp} and @code{ip} point to different
10026: addresses (and the version of @code{gcc} we used would not know it even
10027: if it was possible), so it could not move the load of the cfa above the
10028: store to the TOS. Indeed the pointers could be the same, if code on or
10029: very near the top of stack were executed. In the interest of speed we
10030: chose to forbid this probably unused ``feature'' and helped the compiler
1.26 crook 10031: in scheduling: @code{NEXT} is divided into the loading part (@code{NEXT_P1})
1.21 crook 10032: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
1.1 anton 10033: @example
10034: n=sp[0]+sp[1];
10035: sp++;
10036: NEXT_P1;
10037: sp[0]=n;
10038: NEXT_P2;
10039: @end example
10040: This can be scheduled optimally by the compiler.
10041:
10042: This division can be turned off with the switch @code{-DCISC_NEXT}. This
10043: switch is on by default on machines that do not profit from scheduling
10044: (e.g., the 80386), in order to preserve registers.
10045:
10046: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
10047: @subsection Direct or Indirect Threaded?
10048: @cindex threading, direct or indirect?
10049:
10050: @cindex -DDIRECT_THREADED
10051: Both! After packaging the nasty details in macro definitions we
10052: realized that we could switch between direct and indirect threading by
10053: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
10054: defining a few machine-specific macros for the direct-threading case.
10055: On the Forth level we also offer access words that hide the
10056: differences between the threading methods (@pxref{Threading Words}).
10057:
10058: Indirect threading is implemented completely machine-independently.
10059: Direct threading needs routines for creating jumps to the executable
1.21 crook 10060: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
10061: machine-dependent, but they do not amount to many source lines. Therefore,
10062: even porting direct threading to a new machine requires little effort.
1.1 anton 10063:
10064: @cindex --enable-indirect-threaded, configuration flag
10065: @cindex --enable-direct-threaded, configuration flag
10066: The default threading method is machine-dependent. You can enforce a
10067: specific threading method when building Gforth with the configuration
10068: flag @code{--enable-direct-threaded} or
10069: @code{--enable-indirect-threaded}. Note that direct threading is not
10070: supported on all machines.
10071:
10072: @node DOES>, , Direct or Indirect Threaded?, Threading
10073: @subsection DOES>
10074: @cindex @code{DOES>} implementation
10075:
1.26 crook 10076: @cindex @code{dodoes} routine
10077: @cindex @code{DOES>}-code
1.1 anton 10078: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
10079: the chunk of code executed by every word defined by a
10080: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
10081: the Forth code to be executed, i.e. the code after the
1.26 crook 10082: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
1.1 anton 10083:
1.21 crook 10084: In fig-Forth the code field points directly to the @code{dodoes} and the
1.26 crook 10085: @code{DOES>}code address is stored in the cell after the code address (i.e. at
10086: @code{@var{CFA} cell+}). It may seem that this solution is illegal in
1.1 anton 10087: the Forth-79 and all later standards, because in fig-Forth this address
10088: lies in the body (which is illegal in these standards). However, by
10089: making the code field larger for all words this solution becomes legal
10090: again. We use this approach for the indirect threaded version and for
10091: direct threading on some machines. Leaving a cell unused in most words
10092: is a bit wasteful, but on the machines we are targeting this is hardly a
10093: problem. The other reason for having a code field size of two cells is
10094: to avoid having different image files for direct and indirect threaded
10095: systems (direct threaded systems require two-cell code fields on many
10096: machines).
10097:
1.26 crook 10098: @cindex @code{DOES>}-handler
1.1 anton 10099: The other approach is that the code field points or jumps to the cell
1.26 crook 10100: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
10101: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
10102: @code{DOES>}-code address by computing the code address, i.e., the address of
1.1 anton 10103: the jump to dodoes, and add the length of that jump field. A variant of
10104: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
10105: return address (which can be found in the return register on RISCs) is
1.26 crook 10106: the @code{DOES>}-code address. Since the two cells available in the code field
1.1 anton 10107: are used up by the jump to the code address in direct threading on many
10108: architectures, we use this approach for direct threading on these
10109: architectures. We did not want to add another cell to the code field.
10110:
10111: @node Primitives, Performance, Threading, Engine
10112: @section Primitives
10113: @cindex primitives, implementation
10114: @cindex virtual machine instructions, implementation
10115:
10116: @menu
10117: * Automatic Generation::
10118: * TOS Optimization::
10119: * Produced code::
10120: @end menu
10121:
10122: @node Automatic Generation, TOS Optimization, Primitives, Primitives
10123: @subsection Automatic Generation
10124: @cindex primitives, automatic generation
10125:
10126: @cindex @file{prims2x.fs}
10127: Since the primitives are implemented in a portable language, there is no
10128: longer any need to minimize the number of primitives. On the contrary,
10129: having many primitives has an advantage: speed. In order to reduce the
10130: number of errors in primitives and to make programming them easier, we
10131: provide a tool, the primitive generator (@file{prims2x.fs}), that
10132: automatically generates most (and sometimes all) of the C code for a
10133: primitive from the stack effect notation. The source for a primitive
10134: has the following form:
10135:
10136: @cindex primitive source format
10137: @format
10138: @var{Forth-name} @var{stack-effect} @var{category} [@var{pronounc.}]
10139: [@code{""}@var{glossary entry}@code{""}]
10140: @var{C code}
10141: [@code{:}
10142: @var{Forth code}]
10143: @end format
10144:
10145: The items in brackets are optional. The category and glossary fields
10146: are there for generating the documentation, the Forth code is there
10147: for manual implementations on machines without GNU C. E.g., the source
10148: for the primitive @code{+} is:
10149: @example
10150: + n1 n2 -- n core plus
10151: n = n1+n2;
10152: @end example
10153:
10154: This looks like a specification, but in fact @code{n = n1+n2} is C
10155: code. Our primitive generation tool extracts a lot of information from
10156: the stack effect notations@footnote{We use a one-stack notation, even
10157: though we have separate data and floating-point stacks; The separate
10158: notation can be generated easily from the unified notation.}: The number
10159: of items popped from and pushed on the stack, their type, and by what
10160: name they are referred to in the C code. It then generates a C code
10161: prelude and postlude for each primitive. The final C code for @code{+}
10162: looks like this:
10163:
10164: @example
10165: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
10166: /* */ /* documentation */
10167: @{
10168: DEF_CA /* definition of variable ca (indirect threading) */
10169: Cell n1; /* definitions of variables */
10170: Cell n2;
10171: Cell n;
10172: n1 = (Cell) sp[1]; /* input */
10173: n2 = (Cell) TOS;
10174: sp += 1; /* stack adjustment */
10175: NAME("+") /* debugging output (with -DDEBUG) */
10176: @{
10177: n = n1+n2; /* C code taken from the source */
10178: @}
10179: NEXT_P1; /* NEXT part 1 */
10180: TOS = (Cell)n; /* output */
10181: NEXT_P2; /* NEXT part 2 */
10182: @}
10183: @end example
10184:
10185: This looks long and inefficient, but the GNU C compiler optimizes quite
10186: well and produces optimal code for @code{+} on, e.g., the R3000 and the
10187: HP RISC machines: Defining the @code{n}s does not produce any code, and
10188: using them as intermediate storage also adds no cost.
10189:
1.26 crook 10190: There are also other optimizations that are not illustrated by this
10191: example: assignments between simple variables are usually for free (copy
1.1 anton 10192: propagation). If one of the stack items is not used by the primitive
10193: (e.g. in @code{drop}), the compiler eliminates the load from the stack
10194: (dead code elimination). On the other hand, there are some things that
10195: the compiler does not do, therefore they are performed by
10196: @file{prims2x.fs}: The compiler does not optimize code away that stores
10197: a stack item to the place where it just came from (e.g., @code{over}).
10198:
10199: While programming a primitive is usually easy, there are a few cases
10200: where the programmer has to take the actions of the generator into
10201: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 10202: fall through to @code{NEXT}.
1.1 anton 10203:
10204: @node TOS Optimization, Produced code, Automatic Generation, Primitives
10205: @subsection TOS Optimization
10206: @cindex TOS optimization for primitives
10207: @cindex primitives, keeping the TOS in a register
10208:
10209: An important optimization for stack machine emulators, e.g., Forth
10210: engines, is keeping one or more of the top stack items in
10211: registers. If a word has the stack effect @var{in1}...@var{inx} @code{--}
10212: @var{out1}...@var{outy}, keeping the top @var{n} items in registers
10213: @itemize @bullet
10214: @item
10215: is better than keeping @var{n-1} items, if @var{x>=n} and @var{y>=n},
10216: due to fewer loads from and stores to the stack.
10217: @item is slower than keeping @var{n-1} items, if @var{x<>y} and @var{x<n} and
10218: @var{y<n}, due to additional moves between registers.
10219: @end itemize
10220:
10221: @cindex -DUSE_TOS
10222: @cindex -DUSE_NO_TOS
10223: In particular, keeping one item in a register is never a disadvantage,
10224: if there are enough registers. Keeping two items in registers is a
10225: disadvantage for frequent words like @code{?branch}, constants,
10226: variables, literals and @code{i}. Therefore our generator only produces
10227: code that keeps zero or one items in registers. The generated C code
10228: covers both cases; the selection between these alternatives is made at
10229: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
10230: code for @code{+} is just a simple variable name in the one-item case,
10231: otherwise it is a macro that expands into @code{sp[0]}. Note that the
10232: GNU C compiler tries to keep simple variables like @code{TOS} in
10233: registers, and it usually succeeds, if there are enough registers.
10234:
10235: @cindex -DUSE_FTOS
10236: @cindex -DUSE_NO_FTOS
10237: The primitive generator performs the TOS optimization for the
10238: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
10239: operations the benefit of this optimization is even larger:
10240: floating-point operations take quite long on most processors, but can be
10241: performed in parallel with other operations as long as their results are
10242: not used. If the FP-TOS is kept in a register, this works. If
10243: it is kept on the stack, i.e., in memory, the store into memory has to
10244: wait for the result of the floating-point operation, lengthening the
10245: execution time of the primitive considerably.
10246:
10247: The TOS optimization makes the automatic generation of primitives a
10248: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
10249: @code{TOS} is not sufficient. There are some special cases to
10250: consider:
10251: @itemize @bullet
10252: @item In the case of @code{dup ( w -- w w )} the generator must not
10253: eliminate the store to the original location of the item on the stack,
10254: if the TOS optimization is turned on.
10255: @item Primitives with stack effects of the form @code{--}
10256: @var{out1}...@var{outy} must store the TOS to the stack at the start.
10257: Likewise, primitives with the stack effect @var{in1}...@var{inx} @code{--}
10258: must load the TOS from the stack at the end. But for the null stack
10259: effect @code{--} no stores or loads should be generated.
10260: @end itemize
10261:
10262: @node Produced code, , TOS Optimization, Primitives
10263: @subsection Produced code
10264: @cindex primitives, assembly code listing
10265:
10266: @cindex @file{engine.s}
10267: To see what assembly code is produced for the primitives on your machine
10268: with your compiler and your flag settings, type @code{make engine.s} and
10269: look at the resulting file @file{engine.s}.
10270:
10271: @node Performance, , Primitives, Engine
10272: @section Performance
10273: @cindex performance of some Forth interpreters
10274: @cindex engine performance
10275: @cindex benchmarking Forth systems
10276: @cindex Gforth performance
10277:
10278: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
10279: impossible to write a significantly faster engine.
10280:
10281: On register-starved machines like the 386 architecture processors
10282: improvements are possible, because @code{gcc} does not utilize the
10283: registers as well as a human, even with explicit register declarations;
10284: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
10285: and hand-tuned it for the 486; this system is 1.19 times faster on the
10286: Sieve benchmark on a 486DX2/66 than Gforth compiled with
10287: @code{gcc-2.6.3} with @code{-DFORCE_REG}.
10288:
10289: @cindex Win32Forth performance
10290: @cindex NT Forth performance
10291: @cindex eforth performance
10292: @cindex ThisForth performance
10293: @cindex PFE performance
10294: @cindex TILE performance
10295: However, this potential advantage of assembly language implementations
10296: is not necessarily realized in complete Forth systems: We compared
10297: Gforth (direct threaded, compiled with @code{gcc-2.6.3} and
10298: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
10299: 1994) and Eforth (with and without peephole (aka pinhole) optimization
10300: of the threaded code); all these systems were written in assembly
10301: language. We also compared Gforth with three systems written in C:
10302: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
10303: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
1.21 crook 10304: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
10305: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
1.1 anton 10306: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
10307: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
10308: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
10309: 486DX2/66 with similar memory performance under Windows NT. Marcel
10310: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
10311: added the peephole optimizer, ran the benchmarks and reported the
10312: results.
10313:
10314: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
10315: matrix multiplication come from the Stanford integer benchmarks and have
10316: been translated into Forth by Martin Fraeman; we used the versions
10317: included in the TILE Forth package, but with bigger data set sizes; and
10318: a recursive Fibonacci number computation for benchmarking calling
10319: performance. The following table shows the time taken for the benchmarks
10320: scaled by the time taken by Gforth (in other words, it shows the speedup
10321: factor that Gforth achieved over the other systems).
10322:
10323: @example
10324: relative Win32- NT eforth This-
10325: time Gforth Forth Forth eforth +opt PFE Forth TILE
10326: sieve 1.00 1.39 1.14 1.39 0.85 1.58 3.18 8.58
10327: bubble 1.00 1.31 1.41 1.48 0.88 1.50 3.88
10328: matmul 1.00 1.47 1.35 1.46 0.74 1.58 4.09
10329: fib 1.00 1.52 1.34 1.22 0.86 1.74 2.99 4.30
10330: @end example
10331:
1.26 crook 10332: You may be quite surprised by the good performance of Gforth when
10333: compared with systems written in assembly language. One important reason
10334: for the disappointing performance of these other systems is probably
10335: that they are not written optimally for the 486 (e.g., they use the
10336: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
10337: but costly method for relocating the Forth image: like @code{cforth}, it
10338: computes the actual addresses at run time, resulting in two address
10339: computations per @code{NEXT} (@pxref{Image File Background}).
10340:
10341: Only Eforth with the peephole optimizer has a performance that is
10342: comparable to Gforth. The speedups achieved with peephole optimization
10343: of threaded code are quite remarkable. Adding a peephole optimizer to
10344: Gforth should cause similar speedups.
1.1 anton 10345:
10346: The speedup of Gforth over PFE, ThisForth and TILE can be easily
10347: explained with the self-imposed restriction of the latter systems to
10348: standard C, which makes efficient threading impossible (however, the
1.4 anton 10349: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 10350: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
10351: Moreover, current C compilers have a hard time optimizing other aspects
10352: of the ThisForth and the TILE source.
10353:
1.26 crook 10354: The performance of Gforth on 386 architecture processors varies widely
10355: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
10356: allocate any of the virtual machine registers into real machine
10357: registers by itself and would not work correctly with explicit register
10358: declarations, giving a 1.3 times slower engine (on a 486DX2/66 running
10359: the Sieve) than the one measured above.
1.1 anton 10360:
1.26 crook 10361: Note that there have been several releases of Win32Forth since the
10362: release presented here, so the results presented above may have little
1.1 anton 10363: predictive value for the performance of Win32Forth today.
10364:
10365: @cindex @file{Benchres}
10366: In @cite{Translating Forth to Efficient C} by M. Anton Ertl and Martin
10367: Maierhofer (presented at EuroForth '95), an indirect threaded version of
10368: Gforth is compared with Win32Forth, NT Forth, PFE, and ThisForth; that
10369: version of Gforth is 2%@minus{}8% slower on a 486 than the direct
10370: threaded version used here. The paper available at
10371: @*@url{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz};
10372: it also contains numbers for some native code systems. You can find a
10373: newer version of these measurements at
10374: @url{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
10375: find numbers for Gforth on various machines in @file{Benchres}.
10376:
1.26 crook 10377: @c ******************************************************************
1.13 pazsan 10378: @node Binding to System Library, Cross Compiler, Engine, Top
1.14 pazsan 10379: @chapter Binding to System Library
1.13 pazsan 10380:
10381: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14 pazsan 10382: @chapter Cross Compiler
1.13 pazsan 10383:
10384: Cross Compiler
10385:
10386: @menu
10387: * Using the Cross Compiler::
10388: * How the Cross Compiler Works::
10389: @end menu
10390:
1.21 crook 10391: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 10392: @section Using the Cross Compiler
1.13 pazsan 10393:
1.21 crook 10394: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 10395: @section How the Cross Compiler Works
1.13 pazsan 10396:
10397: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 10398: @appendix Bugs
1.1 anton 10399: @cindex bug reporting
10400:
1.21 crook 10401: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 10402:
10403: If you find a bug, please send a bug report to
1.21 crook 10404: @email{bug-gforth@@gnu.ai.mit.edu}. A bug report should include this
10405: information:
10406:
10407: @itemize @bullet
10408: @item
10409: The Gforth version used (it is announced at the start of an
10410: interactive Gforth session).
10411: @item
10412: The machine and operating system (on Unix
10413: systems @code{uname -a} will report this information).
10414: @item
10415: The installation options (send the file @file{config.status}).
10416: @item
10417: A complete list of changes (if any) you (or your installer) have made to the
10418: Gforth sources.
10419: @item
10420: A program (or a sequence of keyboard commands) that reproduces the bug.
10421: @item
10422: A description of what you think constitutes the buggy behaviour.
10423: @end itemize
1.1 anton 10424:
10425: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
10426: to Report Bugs, gcc.info, GNU C Manual}.
10427:
10428:
1.21 crook 10429: @node Origin, Forth-related information, Bugs, Top
10430: @appendix Authors and Ancestors of Gforth
1.1 anton 10431:
10432: @section Authors and Contributors
10433: @cindex authors of Gforth
10434: @cindex contributors to Gforth
10435:
10436: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
10437: Ertl. The third major author was Jens Wilke. Lennart Benschop (who was
10438: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
10439: with their continuous feedback. Lennart Benshop contributed
10440: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
10441: support for calling C libraries. Helpful comments also came from Paul
10442: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.12 anton 10443: Wavrik, Barrie Stott, Marc de Groot, and Jorge Acerada. Since the
10444: release of Gforth-0.2.1 there were also helpful comments from many
10445: others; thank you all, sorry for not listing you here (but digging
1.23 crook 10446: through my mailbox to extract your names is on my to-do list). Since the
10447: release of Gforth-0.4.0 Neal Crook worked on the manual.
1.1 anton 10448:
10449: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
10450: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 10451: was developed across the Internet, and its authors did not meet
1.20 pazsan 10452: physically for the first 4 years of development.
1.1 anton 10453:
10454: @section Pedigree
1.26 crook 10455: @cindex pedigree of Gforth
1.1 anton 10456:
1.20 pazsan 10457: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
1.1 anton 10458: Dirk Zoller) will cross-fertilize each other. Of course, a significant
10459: part of the design of Gforth was prescribed by ANS Forth.
10460:
1.20 pazsan 10461: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 10462: 32 bit native code version of VolksForth for the Atari ST, written
10463: mostly by Dietrich Weineck.
10464:
10465: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
10466: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
10467: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
10468:
10469: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
10470: Forth-83 standard. !! Pedigree? When?
10471:
10472: A team led by Bill Ragsdale implemented fig-Forth on many processors in
10473: 1979. Robert Selzer and Bill Ragsdale developed the original
10474: implementation of fig-Forth for the 6502 based on microForth.
10475:
10476: The principal architect of microForth was Dean Sanderson. microForth was
10477: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
10478: the 1802, and subsequently implemented on the 8080, the 6800 and the
10479: Z80.
10480:
10481: All earlier Forth systems were custom-made, usually by Charles Moore,
10482: who discovered (as he puts it) Forth during the late 60s. The first full
10483: Forth existed in 1971.
10484:
10485: A part of the information in this section comes from @cite{The Evolution
10486: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
10487: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
10488: Notices 28(3), 1993. You can find more historical and genealogical
10489: information about Forth there.
10490:
1.21 crook 10491: @node Forth-related information, Word Index, Origin, Top
10492: @appendix Other Forth-related information
10493: @cindex Forth-related information
10494:
10495: @menu
10496: * Internet resources::
10497: * Books::
10498: * The Forth Interest Group::
10499: * Conferences::
10500: @end menu
10501:
10502:
10503: @node Internet resources, Books, Forth-related information, Forth-related information
10504: @section Internet resources
1.26 crook 10505: @cindex internet resources
1.21 crook 10506:
10507: @cindex comp.lang.forth
10508: @cindex frequently asked questions
10509: There is an active newsgroup (comp.lang.forth) discussing Forth and
10510: Forth-related issues. A frequently-asked-questions (FAQ) list
10511: is posted to the newsgroup regulary, and archived at these sites:
10512:
10513: @itemize @bullet
10514: @item
10515: @url{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
10516: @item
10517: @url{ftp://ftp.forth.org/pub/Forth/FAQ/}
10518: @end itemize
10519:
10520: The FAQ list should be considered mandatory reading before posting to
10521: the newsgroup.
10522:
10523: Here are some other web sites holding Forth-related material:
10524:
10525: @itemize @bullet
10526: @item
10527: @url{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
10528: @item
10529: @url{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
10530: @item
10531: @url{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
10532: @item
10533: @url{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
10534: Research page, including links to the Journal of Forth Application and
10535: Research (JFAR) and a searchable Forth bibliography.
10536: @end itemize
10537:
10538:
10539: @node Books, The Forth Interest Group, Internet resources, Forth-related information
10540: @section Books
1.26 crook 10541: @cindex books on Forth
1.21 crook 10542:
10543: As the Standard is relatively new, there are not many books out yet. It
10544: is not recommended to learn Forth by using Gforth and a book that is not
10545: written for ANS Forth, as you will not know your mistakes from the
10546: deviations of the book. However, books based on the Forth-83 standard
10547: should be ok, because ANS Forth is primarily an extension of Forth-83.
10548:
10549: @cindex standard document for ANS Forth
10550: @cindex ANS Forth document
10551: The definite reference if you want to write ANS Forth programs is, of
1.26 crook 10552: course, the ANS Forth document. It is available in printed form from the
1.21 crook 10553: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
10554: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
10555: $200. You can also get it from Global Engineering Documents (Tel.: USA
10556: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
10557:
10558: @cite{dpANS6}, the last draft of the standard, which was then submitted
10559: to ANSI for publication is available electronically and for free in some
10560: MS Word format, and it has been converted to HTML
10561: (@url{http://www.taygeta.com/forth/dpans.html}; this is my favourite
10562: format); this HTML version also includes the answers to Requests for
10563: Interpretation (RFIs). Some pointers to these versions can be found
10564: through @*@url{http://www.complang.tuwien.ac.at/projects/forth.html}.
10565:
1.26 crook 10566: @cindex introductory book on Forth
10567: @cindex book on Forth, introductory
1.21 crook 10568: @cindex Woehr, Jack: @cite{Forth: The New Model}
10569: @cindex @cite{Forth: The new model} (book)
10570: @cite{Forth: The New Model} by Jack Woehr (Prentice-Hall, 1993) is an
10571: introductory book based on a draft version of the standard. It does not
10572: cover the whole standard. It also contains interesting background
10573: information (Jack Woehr was in the ANS Forth Technical Committee). It is
10574: not appropriate for complete newbies, but programmers experienced in
10575: other languages should find it ok.
10576:
10577: @cindex Conklin, Edward K., and Elizabeth Rather: @cite{Forth Programmer's Handbook}
10578: @cindex Rather, Elizabeth and Edward K. Conklin: @cite{Forth Programmer's Handbook}
10579: @cindex @cite{Forth Programmer's Handbook} (book)
10580: @cite{Forth Programmer's Handbook} by Edward K. Conklin, Elizabeth
10581: D. Rather and the technical staff of Forth, Inc. (Forth, Inc., 1997;
10582: ISBN 0-9662156-0-5) contains little introductory material. The majority
10583: of the book is similar to @ref{Words}, but the book covers most of the
10584: standard words and some non-standard words (whereas this manual is
10585: quite incomplete). In addition, the book contains a chapter on
10586: programming style. The major drawback of this book is that it usually
10587: does not identify what is standard and what is specific to the Forth
10588: system described in the book (probably one of Forth, Inc.'s systems).
10589: Fortunately, many of the non-standard programming practices described in
10590: the book work in Gforth, too. Still, this drawback makes the book
10591: hardly more useful than a pre-ANS book.
10592:
10593: @node The Forth Interest Group, Conferences, Books, Forth-related information
10594: @section The Forth Interest Group
10595: @cindex Forth interest group (FIG)
10596:
10597: The Forth Interest Group (FIG) is a world-wide, non-profit,
1.26 crook 10598: member-supported organisation. It publishes a regular magazine,
10599: @var{FORTH Dimensions}, and offers other benefits of membership. You can
10600: contact the FIG through their office email address:
10601: @email{office@@forth.org} or by visiting their web site at
10602: @url{http://www.forth.org/}. This web site also includes links to FIG
10603: chapters in other countries and American cities
1.21 crook 10604: (@url{http://www.forth.org/chapters.html}).
10605:
10606: @node Conferences, , The Forth Interest Group, Forth-related information
10607: @section Conferences
10608: @cindex Conferences
10609:
10610: There are several regular conferences related to Forth. They are all
1.26 crook 10611: well-publicised in @var{FORTH Dimensions} and on the comp.lang.forth
10612: news group:
1.21 crook 10613:
10614: @itemize @bullet
10615: @item
10616: FORML -- the Forth modification laboratory convenes every year near
10617: Monterey, California.
10618: @item
10619: The Rochester Forth Conference -- an annual conference traditionally
10620: held in Rochester, New York.
10621: @item
10622: EuroForth -- this European conference takes place annually.
10623: @end itemize
10624:
10625:
10626: @node Word Index, Concept Index, Forth-related information, Top
1.1 anton 10627: @unnumbered Word Index
10628:
1.26 crook 10629: This index is a list of Forth words that have ``glossary'' entries
10630: within this manual. Each word is listed with its stack effect and
10631: wordset.
1.1 anton 10632:
10633: @printindex fn
10634:
10635: @node Concept Index, , Word Index, Top
10636: @unnumbered Concept and Word Index
10637:
1.26 crook 10638: Not all entries listed in this index are present verbatim in the
10639: text. This index also duplicates, in abbreviated form, all of the words
10640: listed in the Word Index (only the names are listed for the words here).
1.1 anton 10641:
10642: @printindex cp
10643:
10644: @contents
10645: @bye
10646:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>