Annotation of gforth/doc/gforth.ds, revision 1.26
1.1 anton 1: \input texinfo @c -*-texinfo-*-
2: @comment The source is gforth.ds, from which gforth.texi is generated
1.21 crook 3: @comment TODO: nac29jan99 - a list of things to add in the next edit:
4: @comment 1. x-ref all ambiguous or implementation-defined features
5: @comment 2. refer to all environment strings
6: @comment 3. gloss and info in blocks section
7: @comment 4. move file and blocks to common sub-section?
8: @comment 5. command-line editing, command completion etc.
9: @comment 6. document more of the words in require.fs
10: @comment 7. document the include files process (Describe the list,
11: @comment including its scope)
12: @comment 8. Describe the use of Auser Avariable etc.
13: @comment 9. cross-compiler
14: @comment 10.words in miscellaneous section need a home.
15: @comment 11.Move structures and oof into their own chapters.
16: @comment 12.search for TODO for other minor works
1.1 anton 17: @comment %**start of header (This is for running Texinfo on a region.)
18: @setfilename gforth.info
19: @settitle Gforth Manual
20: @dircategory GNU programming tools
21: @direntry
22: * Gforth: (gforth). A fast interpreter for the Forth language.
23: @end direntry
24: @comment @setchapternewpage odd
1.12 anton 25: @macro progstyle {}
26: Programming style note:
1.3 anton 27: @end macro
1.1 anton 28: @comment %**end of header (This is for running Texinfo on a region.)
29:
1.10 anton 30: @include version.texi
31:
1.1 anton 32: @ifinfo
1.11 anton 33: This file documents Gforth @value{VERSION}
1.1 anton 34:
1.26 ! crook 35: Copyright @copyright{} 1995-1999 Free Software Foundation, Inc.
1.1 anton 36:
37: Permission is granted to make and distribute verbatim copies of
38: this manual provided the copyright notice and this permission notice
39: are preserved on all copies.
40:
41: @ignore
42: Permission is granted to process this file through TeX and print the
43: results, provided the printed document carries a copying permission
44: notice identical to this one except for the removal of this paragraph
45: (this paragraph not being relevant to the printed manual).
46:
47: @end ignore
48: Permission is granted to copy and distribute modified versions of this
49: manual under the conditions for verbatim copying, provided also that the
50: sections entitled "Distribution" and "General Public License" are
51: included exactly as in the original, and provided that the entire
52: resulting derived work is distributed under the terms of a permission
53: notice identical to this one.
54:
55: Permission is granted to copy and distribute translations of this manual
56: into another language, under the above conditions for modified versions,
57: except that the sections entitled "Distribution" and "General Public
58: License" may be included in a translation approved by the author instead
59: of in the original English.
60: @end ifinfo
61:
62: @finalout
63: @titlepage
64: @sp 10
65: @center @titlefont{Gforth Manual}
66: @sp 2
1.11 anton 67: @center for version @value{VERSION}
1.1 anton 68: @sp 2
69: @center Anton Ertl
1.6 pazsan 70: @center Bernd Paysan
1.5 anton 71: @center Jens Wilke
1.23 crook 72: @center Neal Crook
1.1 anton 73: @sp 3
1.26 ! crook 74: @center This manual is permanently under construction and was last updated on 23-Mar-1999
1.1 anton 75:
76: @comment The following two commands start the copyright page.
77: @page
78: @vskip 0pt plus 1filll
1.13 pazsan 79: Copyright @copyright{} 1995--1998 Free Software Foundation, Inc.
1.1 anton 80:
81: @comment !! Published by ... or You can get a copy of this manual ...
82:
83: Permission is granted to make and distribute verbatim copies of
84: this manual provided the copyright notice and this permission notice
85: are preserved on all copies.
86:
87: Permission is granted to copy and distribute modified versions of this
88: manual under the conditions for verbatim copying, provided also that the
89: sections entitled "Distribution" and "General Public License" are
90: included exactly as in the original, and provided that the entire
91: resulting derived work is distributed under the terms of a permission
92: notice identical to this one.
93:
94: Permission is granted to copy and distribute translations of this manual
95: into another language, under the above conditions for modified versions,
96: except that the sections entitled "Distribution" and "General Public
97: License" may be included in a translation approved by the author instead
98: of in the original English.
99: @end titlepage
100:
101:
102: @node Top, License, (dir), (dir)
103: @ifinfo
104: Gforth is a free implementation of ANS Forth available on many
1.11 anton 105: personal machines. This manual corresponds to version @value{VERSION}.
1.1 anton 106: @end ifinfo
107:
108: @menu
1.21 crook 109: * License:: The GPL
1.26 ! crook 110: * Goals:: About the Gforth Project
1.21 crook 111: * Introduction:: An introduction to ANS Forth
112: * Invoking Gforth:: Starting (and exiting) Gforth
1.1 anton 113: * Words:: Forth words available in Gforth
1.24 anton 114: * Error messages:: How to interpret them
1.1 anton 115: * Tools:: Programming tools
116: * ANS conformance:: Implementation-defined options etc.
117: * Model:: The abstract machine of Gforth
118: * Integrating Gforth:: Forth as scripting language for applications
119: * Emacs and Gforth:: The Gforth Mode
120: * Image Files:: @code{.fi} files contain compiled code
121: * Engine:: The inner interpreter and the primitives
1.24 anton 122: * Binding to System Library::
1.13 pazsan 123: * Cross Compiler:: The Cross Compiler
1.1 anton 124: * Bugs:: How to report them
125: * Origin:: Authors and ancestors of Gforth
1.21 crook 126: * Forth-related information:: Books and places to look on the WWW
1.1 anton 127: * Word Index:: An item for each Forth word
128: * Concept Index:: A menu covering many topics
1.12 anton 129:
1.24 anton 130: @detailmenu --- The Detailed Node Listing ---
1.12 anton 131:
1.26 ! crook 132: Goals of Gforth
! 133:
! 134: * Gforth Extensions Sinful?::
! 135:
1.24 anton 136: An Introduction to ANS Forth
137:
138: * Introducing the Text Interpreter::
139: * Stacks and Postfix notation::
140: * Your first definition::
141: * How does that work?::
142: * Forth is written in Forth::
143: * Review - elements of a Forth system::
144: * Exercises::
145:
1.12 anton 146: Forth Words
147:
148: * Notation::
1.21 crook 149: * Comments::
150: * Boolean Flags::
1.12 anton 151: * Arithmetic::
152: * Stack Manipulation::
153: * Memory::
154: * Control Structures::
155: * Defining Words::
1.21 crook 156: * The Text Interpreter::
1.12 anton 157: * Tokens for Words::
1.21 crook 158: * Word Lists::
159: * Environmental Queries::
1.12 anton 160: * Files::
161: * Blocks::
162: * Other I/O::
163: * Programming Tools::
164: * Assembler and Code Words::
165: * Threading Words::
1.26 ! crook 166: * Locals::
! 167: * Structures::
! 168: * Object-oriented Forth::
1.21 crook 169: * Passing Commands to the OS::
170: * Miscellaneous Words::
1.12 anton 171:
172: Arithmetic
173:
174: * Single precision::
175: * Bitwise operations::
1.21 crook 176: * Double precision:: Double-cell integer arithmetic
177: * Numeric comparison::
1.12 anton 178: * Mixed precision:: operations with single and double-cell integers
179: * Floating Point::
180:
181: Stack Manipulation
182:
183: * Data stack::
184: * Floating point stack::
185: * Return stack::
186: * Locals stack::
187: * Stack pointer manipulation::
188:
189: Memory
190:
191: * Memory Access::
192: * Address arithmetic::
193: * Memory Blocks::
194:
195: Control Structures
196:
197: * Selection::
198: * Simple Loops::
199: * Counted Loops::
200: * Arbitrary control structures::
201: * Calls and returns::
202: * Exception Handling::
203:
204: Defining Words
205:
206: * Simple Defining Words::
207: * Colon Definitions::
208: * User-defined Defining Words::
209: * Supplying names::
210: * Interpretation and Compilation Semantics::
211:
1.21 crook 212: The Text Interpreter
213:
214: * Number Conversion::
215: * Interpret/Compile states::
216: * Literals::
217: * Interpreter Directives::
218:
1.26 ! crook 219: Word Lists
! 220:
! 221: * Why use word lists?::
! 222: * Word list examples::
! 223:
! 224: Files
! 225:
! 226: * Forth source files::
! 227: * General files::
! 228: * Search Paths::
! 229: * Forth Search Paths::
! 230: * General Search Paths::
! 231:
! 232: Other I/O
! 233:
! 234: * Simple numeric output::
! 235: * Formatted numeric output::
! 236: * String Formats::
! 237: * Displaying characters and strings::
! 238: * Input::
! 239:
! 240: Programming Tools
! 241:
! 242: * Debugging:: Simple and quick.
! 243: * Assertions:: Making your programs self-checking.
! 244: * Singlestep Debugger:: Executing your program word by word.
! 245:
! 246: Locals
! 247:
! 248: * Gforth locals::
! 249: * ANS Forth locals::
! 250:
! 251: Gforth locals
! 252:
! 253: * Where are locals visible by name?::
! 254: * How long do locals live?::
! 255: * Programming Style::
! 256: * Implementation::
! 257:
1.12 anton 258: Structures
259:
260: * Why explicit structure support?::
261: * Structure Usage::
262: * Structure Naming Convention::
263: * Structure Implementation::
264: * Structure Glossary::
265:
266: Object-oriented Forth
267:
1.24 anton 268: * Why object-oriented programming?::
269: * Object-Oriented Terminology::
270: * Objects::
271: * OOF::
272: * Mini-OOF::
1.23 crook 273: * Comparison with other object models::
1.12 anton 274:
1.24 anton 275: The @file{objects.fs} model
1.12 anton 276:
277: * Properties of the Objects model::
278: * Basic Objects Usage::
1.23 crook 279: * The Objects base class::
1.12 anton 280: * Creating objects::
281: * Object-Oriented Programming Style::
282: * Class Binding::
283: * Method conveniences::
284: * Classes and Scoping::
285: * Object Interfaces::
286: * Objects Implementation::
287: * Objects Glossary::
288:
1.24 anton 289: The @file{oof.fs} model
1.12 anton 290:
291: * Properties of the OOF model::
292: * Basic OOF Usage::
1.23 crook 293: * The OOF base class::
1.12 anton 294: * Class Declaration::
295: * Class Implementation::
296:
1.24 anton 297: The @file{mini-oof.fs} model
1.23 crook 298:
299: * Basic Mini-OOF Usage::
300: * Mini-OOF Example::
301: * Mini-OOF Implementation::
302:
1.12 anton 303: Tools
304:
305: * ANS Report:: Report the words used, sorted by wordset.
306:
307: ANS conformance
308:
309: * The Core Words::
310: * The optional Block word set::
311: * The optional Double Number word set::
312: * The optional Exception word set::
313: * The optional Facility word set::
314: * The optional File-Access word set::
315: * The optional Floating-Point word set::
316: * The optional Locals word set::
317: * The optional Memory-Allocation word set::
318: * The optional Programming-Tools word set::
319: * The optional Search-Order word set::
320:
321: The Core Words
322:
323: * core-idef:: Implementation Defined Options
324: * core-ambcond:: Ambiguous Conditions
325: * core-other:: Other System Documentation
326:
327: The optional Block word set
328:
329: * block-idef:: Implementation Defined Options
330: * block-ambcond:: Ambiguous Conditions
331: * block-other:: Other System Documentation
332:
333: The optional Double Number word set
334:
335: * double-ambcond:: Ambiguous Conditions
336:
337: The optional Exception word set
338:
339: * exception-idef:: Implementation Defined Options
340:
341: The optional Facility word set
342:
343: * facility-idef:: Implementation Defined Options
344: * facility-ambcond:: Ambiguous Conditions
345:
346: The optional File-Access word set
347:
348: * file-idef:: Implementation Defined Options
349: * file-ambcond:: Ambiguous Conditions
350:
351: The optional Floating-Point word set
352:
353: * floating-idef:: Implementation Defined Options
354: * floating-ambcond:: Ambiguous Conditions
355:
356: The optional Locals word set
357:
358: * locals-idef:: Implementation Defined Options
359: * locals-ambcond:: Ambiguous Conditions
360:
361: The optional Memory-Allocation word set
362:
363: * memory-idef:: Implementation Defined Options
364:
365: The optional Programming-Tools word set
366:
367: * programming-idef:: Implementation Defined Options
368: * programming-ambcond:: Ambiguous Conditions
369:
370: The optional Search-Order word set
371:
372: * search-idef:: Implementation Defined Options
373: * search-ambcond:: Ambiguous Conditions
374:
375: Image Files
376:
1.24 anton 377: * Image Licensing Issues:: Distribution terms for images.
378: * Image File Background:: Why have image files?
379: * Non-Relocatable Image Files:: don't always work.
380: * Data-Relocatable Image Files:: are better.
1.12 anton 381: * Fully Relocatable Image Files:: better yet.
1.24 anton 382: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
383: * Running Image Files:: @code{gforth -i @var{file}} or @var{file}.
384: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 385:
386: Fully Relocatable Image Files
387:
1.24 anton 388: * gforthmi:: The normal way
1.12 anton 389: * cross.fs:: The hard way
390:
391: Engine
392:
393: * Portability::
394: * Threading::
395: * Primitives::
396: * Performance::
397:
398: Threading
399:
400: * Scheduling::
401: * Direct or Indirect Threaded?::
402: * DOES>::
403:
404: Primitives
405:
406: * Automatic Generation::
407: * TOS Optimization::
408: * Produced code::
1.13 pazsan 409:
410: Cross Compiler
411:
412: * Using the Cross Compiler::
413: * How the Cross Compiler Works::
414:
1.24 anton 415: Other Forth-related information
1.21 crook 416:
417: * Internet resources::
418: * Books::
419: * The Forth Interest Group::
420: * Conferences::
421:
1.24 anton 422: @end detailmenu
1.1 anton 423: @end menu
424:
1.26 ! crook 425: @node License, Goals, Top, Top
1.1 anton 426: @unnumbered GNU GENERAL PUBLIC LICENSE
427: @center Version 2, June 1991
428:
429: @display
430: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
431: 675 Mass Ave, Cambridge, MA 02139, USA
432:
433: Everyone is permitted to copy and distribute verbatim copies
434: of this license document, but changing it is not allowed.
435: @end display
436:
437: @unnumberedsec Preamble
438:
439: The licenses for most software are designed to take away your
440: freedom to share and change it. By contrast, the GNU General Public
441: License is intended to guarantee your freedom to share and change free
442: software---to make sure the software is free for all its users. This
443: General Public License applies to most of the Free Software
444: Foundation's software and to any other program whose authors commit to
445: using it. (Some other Free Software Foundation software is covered by
446: the GNU Library General Public License instead.) You can apply it to
447: your programs, too.
448:
449: When we speak of free software, we are referring to freedom, not
450: price. Our General Public Licenses are designed to make sure that you
451: have the freedom to distribute copies of free software (and charge for
452: this service if you wish), that you receive source code or can get it
453: if you want it, that you can change the software or use pieces of it
454: in new free programs; and that you know you can do these things.
455:
456: To protect your rights, we need to make restrictions that forbid
457: anyone to deny you these rights or to ask you to surrender the rights.
458: These restrictions translate to certain responsibilities for you if you
459: distribute copies of the software, or if you modify it.
460:
461: For example, if you distribute copies of such a program, whether
462: gratis or for a fee, you must give the recipients all the rights that
463: you have. You must make sure that they, too, receive or can get the
464: source code. And you must show them these terms so they know their
465: rights.
466:
467: We protect your rights with two steps: (1) copyright the software, and
468: (2) offer you this license which gives you legal permission to copy,
469: distribute and/or modify the software.
470:
471: Also, for each author's protection and ours, we want to make certain
472: that everyone understands that there is no warranty for this free
473: software. If the software is modified by someone else and passed on, we
474: want its recipients to know that what they have is not the original, so
475: that any problems introduced by others will not reflect on the original
476: authors' reputations.
477:
478: Finally, any free program is threatened constantly by software
479: patents. We wish to avoid the danger that redistributors of a free
480: program will individually obtain patent licenses, in effect making the
481: program proprietary. To prevent this, we have made it clear that any
482: patent must be licensed for everyone's free use or not licensed at all.
483:
484: The precise terms and conditions for copying, distribution and
485: modification follow.
486:
487: @iftex
488: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
489: @end iftex
490: @ifinfo
491: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
492: @end ifinfo
493:
494: @enumerate 0
495: @item
496: This License applies to any program or other work which contains
497: a notice placed by the copyright holder saying it may be distributed
498: under the terms of this General Public License. The ``Program'', below,
499: refers to any such program or work, and a ``work based on the Program''
500: means either the Program or any derivative work under copyright law:
501: that is to say, a work containing the Program or a portion of it,
502: either verbatim or with modifications and/or translated into another
503: language. (Hereinafter, translation is included without limitation in
504: the term ``modification''.) Each licensee is addressed as ``you''.
505:
506: Activities other than copying, distribution and modification are not
507: covered by this License; they are outside its scope. The act of
508: running the Program is not restricted, and the output from the Program
509: is covered only if its contents constitute a work based on the
510: Program (independent of having been made by running the Program).
511: Whether that is true depends on what the Program does.
512:
513: @item
514: You may copy and distribute verbatim copies of the Program's
515: source code as you receive it, in any medium, provided that you
516: conspicuously and appropriately publish on each copy an appropriate
517: copyright notice and disclaimer of warranty; keep intact all the
518: notices that refer to this License and to the absence of any warranty;
519: and give any other recipients of the Program a copy of this License
520: along with the Program.
521:
522: You may charge a fee for the physical act of transferring a copy, and
523: you may at your option offer warranty protection in exchange for a fee.
524:
525: @item
526: You may modify your copy or copies of the Program or any portion
527: of it, thus forming a work based on the Program, and copy and
528: distribute such modifications or work under the terms of Section 1
529: above, provided that you also meet all of these conditions:
530:
531: @enumerate a
532: @item
533: You must cause the modified files to carry prominent notices
534: stating that you changed the files and the date of any change.
535:
536: @item
537: You must cause any work that you distribute or publish, that in
538: whole or in part contains or is derived from the Program or any
539: part thereof, to be licensed as a whole at no charge to all third
540: parties under the terms of this License.
541:
542: @item
543: If the modified program normally reads commands interactively
544: when run, you must cause it, when started running for such
545: interactive use in the most ordinary way, to print or display an
546: announcement including an appropriate copyright notice and a
547: notice that there is no warranty (or else, saying that you provide
548: a warranty) and that users may redistribute the program under
549: these conditions, and telling the user how to view a copy of this
550: License. (Exception: if the Program itself is interactive but
551: does not normally print such an announcement, your work based on
552: the Program is not required to print an announcement.)
553: @end enumerate
554:
555: These requirements apply to the modified work as a whole. If
556: identifiable sections of that work are not derived from the Program,
557: and can be reasonably considered independent and separate works in
558: themselves, then this License, and its terms, do not apply to those
559: sections when you distribute them as separate works. But when you
560: distribute the same sections as part of a whole which is a work based
561: on the Program, the distribution of the whole must be on the terms of
562: this License, whose permissions for other licensees extend to the
563: entire whole, and thus to each and every part regardless of who wrote it.
564:
565: Thus, it is not the intent of this section to claim rights or contest
566: your rights to work written entirely by you; rather, the intent is to
567: exercise the right to control the distribution of derivative or
568: collective works based on the Program.
569:
570: In addition, mere aggregation of another work not based on the Program
571: with the Program (or with a work based on the Program) on a volume of
572: a storage or distribution medium does not bring the other work under
573: the scope of this License.
574:
575: @item
576: You may copy and distribute the Program (or a work based on it,
577: under Section 2) in object code or executable form under the terms of
578: Sections 1 and 2 above provided that you also do one of the following:
579:
580: @enumerate a
581: @item
582: Accompany it with the complete corresponding machine-readable
583: source code, which must be distributed under the terms of Sections
584: 1 and 2 above on a medium customarily used for software interchange; or,
585:
586: @item
587: Accompany it with a written offer, valid for at least three
588: years, to give any third party, for a charge no more than your
589: cost of physically performing source distribution, a complete
590: machine-readable copy of the corresponding source code, to be
591: distributed under the terms of Sections 1 and 2 above on a medium
592: customarily used for software interchange; or,
593:
594: @item
595: Accompany it with the information you received as to the offer
596: to distribute corresponding source code. (This alternative is
597: allowed only for noncommercial distribution and only if you
598: received the program in object code or executable form with such
599: an offer, in accord with Subsection b above.)
600: @end enumerate
601:
602: The source code for a work means the preferred form of the work for
603: making modifications to it. For an executable work, complete source
604: code means all the source code for all modules it contains, plus any
605: associated interface definition files, plus the scripts used to
606: control compilation and installation of the executable. However, as a
607: special exception, the source code distributed need not include
608: anything that is normally distributed (in either source or binary
609: form) with the major components (compiler, kernel, and so on) of the
610: operating system on which the executable runs, unless that component
611: itself accompanies the executable.
612:
613: If distribution of executable or object code is made by offering
614: access to copy from a designated place, then offering equivalent
615: access to copy the source code from the same place counts as
616: distribution of the source code, even though third parties are not
617: compelled to copy the source along with the object code.
618:
619: @item
620: You may not copy, modify, sublicense, or distribute the Program
621: except as expressly provided under this License. Any attempt
622: otherwise to copy, modify, sublicense or distribute the Program is
623: void, and will automatically terminate your rights under this License.
624: However, parties who have received copies, or rights, from you under
625: this License will not have their licenses terminated so long as such
626: parties remain in full compliance.
627:
628: @item
629: You are not required to accept this License, since you have not
630: signed it. However, nothing else grants you permission to modify or
631: distribute the Program or its derivative works. These actions are
632: prohibited by law if you do not accept this License. Therefore, by
633: modifying or distributing the Program (or any work based on the
634: Program), you indicate your acceptance of this License to do so, and
635: all its terms and conditions for copying, distributing or modifying
636: the Program or works based on it.
637:
638: @item
639: Each time you redistribute the Program (or any work based on the
640: Program), the recipient automatically receives a license from the
641: original licensor to copy, distribute or modify the Program subject to
642: these terms and conditions. You may not impose any further
643: restrictions on the recipients' exercise of the rights granted herein.
644: You are not responsible for enforcing compliance by third parties to
645: this License.
646:
647: @item
648: If, as a consequence of a court judgment or allegation of patent
649: infringement or for any other reason (not limited to patent issues),
650: conditions are imposed on you (whether by court order, agreement or
651: otherwise) that contradict the conditions of this License, they do not
652: excuse you from the conditions of this License. If you cannot
653: distribute so as to satisfy simultaneously your obligations under this
654: License and any other pertinent obligations, then as a consequence you
655: may not distribute the Program at all. For example, if a patent
656: license would not permit royalty-free redistribution of the Program by
657: all those who receive copies directly or indirectly through you, then
658: the only way you could satisfy both it and this License would be to
659: refrain entirely from distribution of the Program.
660:
661: If any portion of this section is held invalid or unenforceable under
662: any particular circumstance, the balance of the section is intended to
663: apply and the section as a whole is intended to apply in other
664: circumstances.
665:
666: It is not the purpose of this section to induce you to infringe any
667: patents or other property right claims or to contest validity of any
668: such claims; this section has the sole purpose of protecting the
669: integrity of the free software distribution system, which is
670: implemented by public license practices. Many people have made
671: generous contributions to the wide range of software distributed
672: through that system in reliance on consistent application of that
673: system; it is up to the author/donor to decide if he or she is willing
674: to distribute software through any other system and a licensee cannot
675: impose that choice.
676:
677: This section is intended to make thoroughly clear what is believed to
678: be a consequence of the rest of this License.
679:
680: @item
681: If the distribution and/or use of the Program is restricted in
682: certain countries either by patents or by copyrighted interfaces, the
683: original copyright holder who places the Program under this License
684: may add an explicit geographical distribution limitation excluding
685: those countries, so that distribution is permitted only in or among
686: countries not thus excluded. In such case, this License incorporates
687: the limitation as if written in the body of this License.
688:
689: @item
690: The Free Software Foundation may publish revised and/or new versions
691: of the General Public License from time to time. Such new versions will
692: be similar in spirit to the present version, but may differ in detail to
693: address new problems or concerns.
694:
695: Each version is given a distinguishing version number. If the Program
696: specifies a version number of this License which applies to it and ``any
697: later version'', you have the option of following the terms and conditions
698: either of that version or of any later version published by the Free
699: Software Foundation. If the Program does not specify a version number of
700: this License, you may choose any version ever published by the Free Software
701: Foundation.
702:
703: @item
704: If you wish to incorporate parts of the Program into other free
705: programs whose distribution conditions are different, write to the author
706: to ask for permission. For software which is copyrighted by the Free
707: Software Foundation, write to the Free Software Foundation; we sometimes
708: make exceptions for this. Our decision will be guided by the two goals
709: of preserving the free status of all derivatives of our free software and
710: of promoting the sharing and reuse of software generally.
711:
712: @iftex
713: @heading NO WARRANTY
714: @end iftex
715: @ifinfo
716: @center NO WARRANTY
717: @end ifinfo
718:
719: @item
720: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
721: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
722: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
723: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
724: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
725: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
726: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
727: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
728: REPAIR OR CORRECTION.
729:
730: @item
731: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
732: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
733: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
734: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
735: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
736: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
737: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
738: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
739: POSSIBILITY OF SUCH DAMAGES.
740: @end enumerate
741:
742: @iftex
743: @heading END OF TERMS AND CONDITIONS
744: @end iftex
745: @ifinfo
746: @center END OF TERMS AND CONDITIONS
747: @end ifinfo
748:
749: @page
750: @unnumberedsec How to Apply These Terms to Your New Programs
751:
752: If you develop a new program, and you want it to be of the greatest
753: possible use to the public, the best way to achieve this is to make it
754: free software which everyone can redistribute and change under these terms.
755:
756: To do so, attach the following notices to the program. It is safest
757: to attach them to the start of each source file to most effectively
758: convey the exclusion of warranty; and each file should have at least
759: the ``copyright'' line and a pointer to where the full notice is found.
760:
761: @smallexample
762: @var{one line to give the program's name and a brief idea of what it does.}
763: Copyright (C) 19@var{yy} @var{name of author}
764:
765: This program is free software; you can redistribute it and/or modify
766: it under the terms of the GNU General Public License as published by
767: the Free Software Foundation; either version 2 of the License, or
768: (at your option) any later version.
769:
770: This program is distributed in the hope that it will be useful,
771: but WITHOUT ANY WARRANTY; without even the implied warranty of
772: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
773: GNU General Public License for more details.
774:
775: You should have received a copy of the GNU General Public License
776: along with this program; if not, write to the Free Software
777: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
778: @end smallexample
779:
780: Also add information on how to contact you by electronic and paper mail.
781:
782: If the program is interactive, make it output a short notice like this
783: when it starts in an interactive mode:
784:
785: @smallexample
786: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
787: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
788: type `show w'.
789: This is free software, and you are welcome to redistribute it
790: under certain conditions; type `show c' for details.
791: @end smallexample
792:
793: The hypothetical commands @samp{show w} and @samp{show c} should show
794: the appropriate parts of the General Public License. Of course, the
795: commands you use may be called something other than @samp{show w} and
796: @samp{show c}; they could even be mouse-clicks or menu items---whatever
797: suits your program.
798:
799: You should also get your employer (if you work as a programmer) or your
800: school, if any, to sign a ``copyright disclaimer'' for the program, if
801: necessary. Here is a sample; alter the names:
802:
803: @smallexample
804: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
805: `Gnomovision' (which makes passes at compilers) written by James Hacker.
806:
807: @var{signature of Ty Coon}, 1 April 1989
808: Ty Coon, President of Vice
809: @end smallexample
810:
811: This General Public License does not permit incorporating your program into
812: proprietary programs. If your program is a subroutine library, you may
813: consider it more useful to permit linking proprietary applications with the
814: library. If this is what you want to do, use the GNU Library General
815: Public License instead of this License.
816:
817: @iftex
818: @unnumbered Preface
819: @cindex Preface
1.21 crook 820: This manual documents Gforth. Some introductory material is provided for
821: readers who are unfamiliar with Forth or who are migrating to Gforth
822: from other Forth compilers. However, this manual is primarily a
823: reference manual.
1.1 anton 824: @end iftex
825:
1.26 ! crook 826:
! 827: @c ******************************************************************
! 828: @node Goals, Introduction, License, Top
! 829: @comment node-name, next, previous, up
! 830: @chapter Goals of Gforth
! 831: @cindex goals of the Gforth project
! 832: The goal of the Gforth Project is to develop a standard model for
! 833: ANS Forth. This can be split into several subgoals:
! 834:
! 835: @itemize @bullet
! 836: @item
! 837: Gforth should conform to the ANS Forth Standard.
! 838: @item
! 839: It should be a model, i.e. it should define all the
! 840: implementation-dependent things.
! 841: @item
! 842: It should become standard, i.e. widely accepted and used. This goal
! 843: is the most difficult one.
! 844: @end itemize
! 845:
! 846: To achieve these goals Gforth should be
! 847: @itemize @bullet
! 848: @item
! 849: Similar to previous models (fig-Forth, F83)
! 850: @item
! 851: Powerful. It should provide for all the things that are considered
! 852: necessary today and even some that are not yet considered necessary.
! 853: @item
! 854: Efficient. It should not get the reputation of being exceptionally
! 855: slow.
! 856: @item
! 857: Free.
! 858: @item
! 859: Available on many machines/easy to port.
! 860: @end itemize
! 861:
! 862: Have we achieved these goals? Gforth conforms to the ANS Forth
! 863: standard. It may be considered a model, but we have not yet documented
! 864: which parts of the model are stable and which parts we are likely to
! 865: change. It certainly has not yet become a de facto standard, but it
! 866: appears to be quite popular. It has some similarities to and some
! 867: differences from previous models. It has some powerful features, but not
! 868: yet everything that we envisioned. We certainly have achieved our
! 869: execution speed goals (@pxref{Performance}). It is free and available
! 870: on many machines.
! 871:
! 872: @menu
! 873: * Gforth Extensions Sinful?::
! 874: @end menu
! 875:
! 876: @node Gforth Extensions Sinful?, , Goals, Goals
! 877: @comment node-name, next, previous, up
! 878: @section Is it a Sin to use Gforth Extensions?
! 879: @cindex Gforth extensions
! 880:
! 881: If you've been paying attention, you will have realised that there is an
! 882: ANS (American National Standard) for Forth. As you read through the rest
! 883: of this manual, you will see documentation for @var{Standard} words, and
! 884: documentation for some appealing Gforth @var{extensions}. You might ask
! 885: yourself the question: @var{``Given that there is a standard, would I be
! 886: committing a sin to use (non-Standard) Gforth extensions?''}
! 887:
! 888: The answer to that question is somewhat pragmatic and somewhat
! 889: philosophical. Consider these points:
! 890:
! 891: @itemize @bullet
! 892: @item
! 893: A number of the Gforth extensions can be implemented in ANS Forth using
! 894: files provided in the @file{compat/} directory. These are mentioned in
! 895: the text in passing.
! 896: @item
! 897: Forth has a rich historical precedent for programmers taking advantage
! 898: of implementation-dependent features of their tools (for example,
! 899: relying on a knowledge of the dictionary structure). Sometimes these
! 900: techniques are necessary to extract every last bit of performance from
! 901: the hardware, sometimes they are just a programming shorthand.
! 902: @item
! 903: The best way to break the rules is to know what the rules are. To learn
! 904: the rules, there is no substitute for studying the text of the Standard
! 905: itself. In particular, Appendix A of the Standard (@var{Rationale})
! 906: provides a valuable insight into the thought processes of the technical
! 907: committee.
! 908: @item
! 909: The best reason to break a rule is because you have to; because it's
! 910: more productive to do that, because it makes your code run fast enough
! 911: or because you can see no Standard way to achieve what you want to
! 912: achieve.
! 913: @end itemize
! 914:
! 915: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
! 916: analyse your program and determine what non-Standard definitions it
! 917: relies upon.
! 918:
! 919: @c ******************************************************************
! 920: @node Introduction, Invoking Gforth, Goals, Top
1.21 crook 921: @comment node-name, next, previous, up
922: @chapter An Introduction to ANS Forth
923: @cindex Forth - an introduction
924:
925: The primary purpose of this manual is to document Gforth. However, since
926: Forth is not a widely-known language and there is a lack of up-to-date
927: teaching material, it seems worthwhile to provide some introductory
928: material. @xref{Forth-related information} for other sources of Forth-related
929: information.
930:
1.26 ! crook 931: The examples in this section should work on any ANS Forth; the
! 932: output shown was produced using Gforth. Each example attempts to
1.21 crook 933: reproduce the exact output that Gforth produces. If you try out the
934: examples (and you should), what you should type is shown @kbd{like this}
935: and Gforth's response is shown @code{like this}. The single exception is
936: that, where the example shows @kbd{<return>} it means that you should
1.26 ! crook 937: press the ``carriage return'' key. Unfortunately, some output formats for
1.21 crook 938: this manual cannot show the difference between @kbd{this} and
939: @code{this} which will make trying out the examples harder (but not
940: impossible).
941:
942: Forth is an unusual language. It provides an interactive development
943: environment which includes both an interpreter and compiler. Forth
944: programming style encourages you to break a problem down into many
945: @cindex factoring
946: small fragments (@var{factoring}), and then to develop and test each
947: fragment interactively. Forth advocates assert that breaking the
948: edit-compile-test cycle used by conventional programming languages can
949: lead to great productivity improvements.
950:
951: @menu
952: * Introducing the Text Interpreter::
953: * Stacks and Postfix notation::
954: * Your first definition::
955: * How does that work?::
956: * Forth is written in Forth::
957: * Review - elements of a Forth system::
958: * Exercises::
959: @end menu
960:
961: @comment ----------------------------------------------
962: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
963: @section Introducing the Text Interpreter
964: @cindex text interpreter
965: @cindex outer interpreter
966:
967: When you invoke the Forth image, you will see a startup banner printed
968: and nothing else (if you have Gforth installed on your system, try
969: invoking it now, by typing @kbd{gforth<return>}). Forth is now running
970: its command line interpreter, which is called the @var{Text Interpreter}
1.26 ! crook 971: (also known as the @var{Outer Interpreter}). (You will learn a lot
! 972: about the text interpreter as you read through this chapter,
! 973: but @pxref{The Text Interpreter} for more detail).
1.21 crook 974:
1.26 ! crook 975: Although it's not obvious, Forth is actually waiting for your
1.21 crook 976: input. Type a number and press the <return> key:
977:
978: @example
979: @kbd{45<return>} ok
980: @end example
981:
982: Rather than give you a prompt to invite you to input something, the text
983: interpreter prints a status message @var{after} it has processed a line
1.26 ! crook 984: of input. The status message in this case (``@code{ ok}'' followed by
1.21 crook 985: carriage-return) indicates that the text interpreter was able to process
986: all of your input successfully. Now type something illegal:
987:
988: @example
989: @kbd{qwer341<return>}
1.26 ! crook 990: :1: Undefined word
! 991: qwer341
1.21 crook 992: ^^^^^^^
1.26 ! crook 993: $400D2BA8 Bounce
! 994: $400DBDA8 no.extensions
1.21 crook 995: @end example
996:
1.26 ! crook 997: The exact text, other than the ``Undefined word'' may differ slightly on
! 998: your system, but the effect is the same; when the text interpreter
! 999: detects an error, it discards any remaining text on a line, resets
! 1000: certain internal state and prints an error message.
! 1001:
! 1002: The text interpreter waits for you to press carrage-return, and then
! 1003: processes your input line. Starting at the beginning of the line, it
! 1004: breaks the line into groups of characters separated by spaces. For each
! 1005: group of characters in turn, it makes two attempts to do something:
1.21 crook 1006:
1007: @itemize @bullet
1008: @item
1009: It tries to treat it as a command. It does this by searching a @var{name
1010: dictionary}. If the group of characters matches an entry in the name
1011: dictionary, the name dictionary provides the text interpreter with
1012: information that allows the text interpreter perform some actions. In
1013: Forth jargon, we say that the group
1014: @cindex word
1015: @cindex definition
1016: @cindex execution token
1017: @cindex xt
1018: of characters names a @var{word}, that the dictionary search returns an
1019: @var{execution token (xt)} corresponding to the @var{definition} of the
1020: word, and that the text interpreter executes the xt. Often, the terms
1021: @var{word} and @var{definition} are used interchangeably.
1022: @item
1023: If the text interpreter fails to find a match in the name dictionary, it
1024: tries to treat the group of characters as a number in the current number
1025: base (when you start up Forth, the current number base is base 10). If
1026: the group of characters legitimately represents a number, the text
1027: interpreter pushes the number onto a stack (we'll learn more about that
1028: in the next section).
1029: @end itemize
1030:
1031: If the text interpreter is unable to do either of these things with any
1.26 ! crook 1032: group of characters, it discards the group of characters and the rest of
! 1033: the line, then prints an error message. If the text interpreter reaches
! 1034: the end of the line without error, it prints the status message ``@code{ ok}''
! 1035: followed by carriage-return.
1.21 crook 1036:
1037: This is the simplest command we can give to the text interpreter:
1038:
1039: @example
1040: @kbd{<return>} ok
1041: @end example
1042:
1043: The text interpreter did everything we asked it to do (nothing) without
1.26 ! crook 1044: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
1.21 crook 1045: command:
1046:
1047: @example
1048: @kbd{12 dup fred dup<return>}
1.26 ! crook 1049: :1: Undefined word
! 1050: 12 dup fred dup
1.21 crook 1051: ^^^^
1.26 ! crook 1052: $400D2BA8 Bounce
! 1053: $400DBDA8 no.extensions
1.21 crook 1054: @end example
1055:
1.26 ! crook 1056: When you press the carriage-return key, the text interpreter starts to
! 1057: work its way along the line:
1.21 crook 1058:
1059: @itemize @bullet
1060: @item
1061: When it gets to the space after the @code{2}, it takes the group of
1062: characters @code{12} and looks them up in the name
1063: dictionary@footnote{We can't tell if it found them or not, but assume
1064: for now that it did not}. There is no match for this group of characters
1065: in the name dictionary, so it tries to treat them as a number. It is
1.26 ! crook 1066: able to do this successfully, so it puts the number, 12, ``on the stack''
1.21 crook 1067: (whatever that means).
1068: @item
1069: The text interpreter resumes scanning the line and gets the next group
1.26 ! crook 1070: of characters, @code{dup}. It looks it up in the name dictionary and
! 1071: (you'll have to take my word for this) finds it, and executes the word
1.21 crook 1072: @code{dup} (whatever that means).
1073: @item
1074: Once again, the text interpreter resumes scanning the line and gets the
1075: group of characters @code{fred}. It looks them up in the name
1076: dictionary, but can't find them. It tries to treat them as a number, but
1077: they don't represent any legal number.
1078: @end itemize
1079:
1080: At this point, the text interpreter gives up and prints an error
1081: message. The error message shows exactly how far the text interpreter
1082: got in processing the line. In particular, it shows that the text
1083: interpreter made no attempt to do anything with the final character
1084: group, @code{dup}, even though we have good reason to believe that the
1085: text interpreter would have had no problems with looking that word up
1086: and executing it a second time.
1087:
1088:
1089: @comment ----------------------------------------------
1090: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
1091: @section Stacks, postfix notation and parameter passing
1092: @cindex text interpreter
1093: @cindex outer interpreter
1094:
1095: In procedural programming languages (like C and Pascal), the
1.26 ! crook 1096: building-block of programs is the @var{function} or @var{procedure}. These
! 1097: functions or procedures are called with @var{explicit parameters}. For
1.21 crook 1098: example, in C we might write:
1099:
1100: @example
1101: total = total + new_volume(length,height,depth);
1102: @end example
1103:
1.26 ! crook 1104: @noindent
! 1105: where new_volume is a function-call to another piece of code, and total,
! 1106: length, height and depth are all variables. length, height and depth are
! 1107: parameters to the function-call.
1.21 crook 1108:
1.26 ! crook 1109: In Forth, the equivalent of the function or procedure is the
1.21 crook 1110: @var{definition} and parameters are implicitly passed between
1111: definitions using a shared stack that is visible to the
1112: programmer. Although Forth does support variables, the existence of the
1113: stack means that they are used far less often than in most other
1114: programming languages. When the text interpreter encounters a number, it
1115: will place (@var{push}) it on the stack. There are several stacks (the
1116: actual number is implementation-dependent ..) and the particular stack
1117: used for any operation is implied unambiguously by the operation being
1118: performed. The stack used for all integer operations is called the @var{data
1119: stack} and, since this is the stack used most commonly, references to
1.26 ! crook 1120: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 1121:
1122: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1123:
1124: @example
1125: @kbd{1 2 3<return>} ok
1126: @end example
1127:
1.26 ! crook 1128: Then this instructs the text interpreter to placed three numbers on the
! 1129: (data) stack. An analogy for the behaviour of the stack is to take a
! 1130: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
! 1131: the table. The 3 was the last card onto the pile (``last-in'') and if
! 1132: you take a card off the pile then, unless you're prepared to fiddle a
! 1133: bit, the card that you take off will be the 3 (``first-out''). The
! 1134: number that will be first-out of the stack is called the @var{top of
! 1135: stack}, which
! 1136: @cindex TOS definition
1.21 crook 1137: is often abbreviated to @var{TOS}.
1138:
1.26 ! crook 1139: To understand how parameters are passed in Forth, consider the
! 1140: behaviour of the definition @code{+} (pronounced ``plus''). You will not
! 1141: be surprised to learn that this definition performs addition. More
1.21 crook 1142: precisely, it adds two number together and produces a result. Where does
1.26 ! crook 1143: it get the two numbers from? It takes the top two numbers off the
1.21 crook 1144: stack. Where does it place the result? On the stack. You can act-out the
1145: behaviour of @code{+} with your playing cards like this:
1146:
1147: @itemize @bullet
1148: @item
1.26 ! crook 1149: Pick up two cards from the stack on the table
1.21 crook 1150: @item
1.26 ! crook 1151: Stare at them intently and ask yourself ``what @var{is} the sum of these two
! 1152: numbers''
1.21 crook 1153: @item
1154: Decide that the answer is 5
1155: @item
1156: Shuffle the two cards back into the pack and find a 5
1157: @item
1158: Put a 5 on the remaining ace that's on the table.
1159: @end itemize
1160:
1161: If you don't have a pack of cards handy but you do have Forth running,
1.26 ! crook 1162: you can use the definition @code{.s} to show the current state of the stack,
1.21 crook 1163: without affecting the stack. Type:
1164:
1165: @example
1166: @kbd{clearstack 1 2 3<return>} ok
1.26 ! crook 1167: @kbd{.s<return>} <3> 1 2 3 ok
1.21 crook 1168: @end example
1169:
1170: The text interpreter looks up the word @code{clearstack} and executes
1171: it; it tidies up the stack and removes any entries that may have been
1172: left on it by earlier examples. The text interpreter pushes each of the
1173: three numbers in turn onto the stack. Finally, the text interpreter
1174: looks up the word @code{.s} and executes it. The effect of executing
1.26 ! crook 1175: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
! 1176: followed by a list of all the items on the stack; the item on the far
! 1177: right-hand side is the TOS.
1.21 crook 1178:
1179: You can now type:
1180:
1.26 ! crook 1181: @example
! 1182: @kbd{+ .s<return>} <2> 1 5 ok
! 1183: @end example
1.21 crook 1184:
1.26 ! crook 1185: @noindent
1.21 crook 1186: which is correct; there are now 2 items on the stack and the result of
1187: the addition is 5.
1188:
1.26 ! crook 1189: If you're playing with cards, try doing a second addition: pick up the
1.21 crook 1190: two cards, work out that their sum is 6, shuffle them into the pack,
1.26 ! crook 1191: look for a 6 and place that on the table. You now have just one item on
! 1192: the stack. What happens if you try to do a third addition? Pick up the
! 1193: first card, pick up the second card -- ah! There is no second card. This
! 1194: is called a @var{stack underflow} and consitutes an error. If you try to
! 1195: do the same thing with Forth it will report an error (probably a Stack
! 1196: Underflow or an Invalid Memory Address error).
! 1197:
! 1198: The opposite situation to a stack underflow is a @var{stack overflow},
! 1199: which simply accepts that there is a finite amount of storage space
! 1200: reserved for the stack. To stretch the playing card analogy, if you had
! 1201: enough packs of cards and you piled the cards up on the table, you would
! 1202: eventually be unable to add another card; you'd hit the ceiling. Gforth
! 1203: allows you to set the maximum size of the stacks. In general, the only
! 1204: time that you will get a stack overflow is because a definition has a
! 1205: bug in it and is generating data on the stack uncontrollably.
1.21 crook 1206:
1207: There's one final use for the playing card analogy. If you model your
1208: stack using a pack of playing cards, the maximum number of items on
1209: your stack will be 52 (I assume you didn't use the Joker). The maximum
1.26 ! crook 1210: @var{value} of any item on the stack is 13 (the King). In fact, the only
1.21 crook 1211: possible numbers are positive integer numbers 1 through 13; you can't
1212: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
1213: think about some of the cards, you can accommodate different
1214: numbers. For example, you could think of the Jack as representing 0,
1215: the Queen as representing -1 and the King as representing -2. Your
1216: *range* remains unchanged (you can still only represent a total of 13
1217: numbers) but the numbers that you can represent are -2 through 10.
1218:
1219: In that analogy, the limit was the amount of information that a single
1220: stack entry could hold, and Forth has a similar limit. In Forth, the
1.26 ! crook 1221: size of a stack entry is called a @var{cell}. The actual size of a cell is
1.21 crook 1222: implementation dependent and affects the maximum value that a stack
1223: entry can hold. A Standard Forth provides a cell size of at least
1224: 16-bits, and most desktop systems use a cell size of 32-bits.
1225:
1226: Forth does not do any type checking for you, so you are free to
1227: manipulate and combine stack items in any way you wish. A convenient
1228: ways of treating stack items is as 2's complement signed integers, and
1.26 ! crook 1229: that is what Standard words like ``+'' do. Therefore you can type:
1.21 crook 1230:
1.26 ! crook 1231: @example
! 1232: @kbd{-5 12 + .s<return>} <1> 7 ok
! 1233: @end example
1.21 crook 1234:
1.26 ! crook 1235: If you use numbers and definitions like ``+'' in order to turn Forth
1.21 crook 1236: into a great big pocket calculator, you will realise that it's rather
1237: different from a normal calculator. Rather than typing 2 + 3 = you had
1.26 ! crook 1238: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
1.21 crook 1239: result). The terminology used to describe this difference is to say
1.26 ! crook 1240: that your calculator uses @var{Infix Notation} (parameters and operators
! 1241: are mixed) whilst Forth uses @var{Postfix Notation} (parameters and
! 1242: operators are separate), also called @var{Reverse Polish Notation}.
1.21 crook 1243:
1244: Whilst postfix notation might look confusing to begin with, it has
1245: several important advantages:
1246:
1.26 ! crook 1247: @itemize @bullet
! 1248: @item
! 1249: it is unambiguous
! 1250: @item
! 1251: it is more concise
! 1252: @item
! 1253: it fits naturally with a stack-based system
! 1254: @end itemize
1.21 crook 1255:
1256: To examine these claims in more detail, consider these sums:
1257:
1.26 ! crook 1258: @example
1.21 crook 1259: 6 + 5 * 4 =
1260: 4 * 5 + 6 =
1.26 ! crook 1261: @end example
1.21 crook 1262:
1263: If you're just learning maths or your maths is very rusty, you will
1264: probably come up with the answer 44 for the first and 26 for the
1265: second. If you are a bit of a whizz at maths you will remember the
1.26 ! crook 1266: @var{convention} that multiplication takes precendence over addition, and
1.21 crook 1267: you'd come up with the answer 26 both times. To explain the answer 26
1268: to someone who got the answer 44, you'd probably rewrite the first sum
1269: like this:
1270:
1.26 ! crook 1271: @example
1.21 crook 1272: 6 + (5 * 4) =
1.26 ! crook 1273: @end example
1.21 crook 1274:
1275: If what you really wanted was to perform the addition before the
1276: multiplication, you would have to use parentheses to force it.
1277:
1278: If you did the first two sums on a pocket calculator you would probably
1279: get the right answers, unless you were very cautious and entered them using
1280: these keystroke sequences:
1281:
1282: 6 + 5 = * 4 =
1283: 4 * 5 = + 6 =
1284:
1285: Postfix notation is unambiguous because the order that the operators
1286: are applied is always explicit; that also means that parentheses are
1.26 ! crook 1287: never required. The operators are @var{active} (the act of quoting the
! 1288: operator makes the operation occur) which removes the need for ``=''.
1.21 crook 1289:
1290: The sum 6 + 5 * 4 can be written (in postfix notation) in two
1291: equivalent ways:
1292:
1.26 ! crook 1293: @example
1.21 crook 1294: 6 5 4 * + or:
1295: 5 4 * 6 +
1.26 ! crook 1296: @end example
1.21 crook 1297:
1.23 crook 1298: An important thing that you should notice about this notation is that
1299: the @var{order} of the numbers does not change; if you want to subtract
1300: 2 from 10 you type @code{10 2 -}.
1301:
1.26 ! crook 1302: The reason that Forth uses postfix notation is very simple to explain: it
1.23 crook 1303: makes the implementation extremely simple, and it follows naturally from
1304: using the stack as a mechanism for passing parameters. Another way of
1305: thinking about this is to realise that all Forth definitions are
1306: @var{active}; they execute as they are encountered by the text
1.26 ! crook 1307: interpreter. The result of this is that the syntax of Forth is trivially
! 1308: simple.
1.23 crook 1309:
1310:
1311:
1312: @comment ----------------------------------------------
1313: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
1314: @section Your first Forth definition
1315: @cindex first definition
1.21 crook 1316:
1.23 crook 1317: Until now, the examples we've seen have been trivial; we've just been
1318: using Forth an a bigger-than-pocket calculator. Also, each calculation
1.26 ! crook 1319: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
1.23 crook 1320: again@footnote{That's not quite true. If you press the up-arrow key on
1321: your keyboard you should be able to scroll back to any earlier command,
1322: edit it and re-enter it.} In this section we'll see how to add new
1323: word to Forth's vocabulary.
1324:
1.26 ! crook 1325: The easiest way to create a new word is to use a @var{colon
! 1326: definition}. We'll define a few and try them out before we worry too
1.23 crook 1327: much about how they work. Try typing in these examples; be careful to
1328: copy the spaces accurately:
1329:
1330: @example
1331: : add-two 2 + . ;
1332: : greet ." Hello and welcome" ;
1333: : demo 5 add-two ;
1334: @end example
1.21 crook 1335:
1.23 crook 1336: @noindent
1337: Now try them out:
1.21 crook 1338:
1.23 crook 1339: @example
1340: @kbd{greet<return>} Hello and welcome ok
1341: @kbd{greet greet<return>} Hello and welcomeHello and welcome ok
1342: @kbd{4 add-two<return>} 6 ok
1343: @kbd{demo<return>} 7 ok
1344: @kbd{9 greet demo add-two<return>} Hello and welcome7 11 ok
1345: @end example
1.21 crook 1346:
1.23 crook 1347: The first new thing that we've introduced here is the pair of words
1348: @code{:} and @code{;}. These are used to start and terminate a new
1349: definition, respectively. The first word after the @code{:} is the name
1350: for the new definition.
1.21 crook 1351:
1.23 crook 1352: As you can see from the examples, a definition is built up of words that
1353: have already been defined; Forth makes no distinction between
1354: definitions that existed when you started the system up, and those that
1355: you define yourself.
1.21 crook 1356:
1.23 crook 1357: The examples also introduce the words @code{.} (dot), @code{."} (dot-quote)
1358: and @code{dup} (dewp). Dot takes the value from the top of the stack and
1359: displays it. It's like @code{.s} except that it only displays the top
1360: item of the stack and it is destructive; after it has executed the
1361: number is no longer on the top of the stack. There is always one space
1362: printed after the number, and no spaces before it. Dot-quote defines a
1363: string (a sequence of characters) that will be printed when the word is
1364: executed. The string can contain any printable characters except
1365: @code{"}. A @code{"} has a special function; it is not itself a Forth
1366: word but it acts as a delimiter. The way that it works is described in
1367: the next section. Finally, @code{dup} duplicates the value at the top of
1368: the stack. Try typing @code{5 dup .s} to see what it does.
1.21 crook 1369:
1.23 crook 1370: We already know that the text interpreter searches through the
1371: dictionary to locate names. If you've followed the examples earlier, you
1372: will already have a definition called @code{add-two}. Lets try modifying
1373: it by typing in a new definition:
1.21 crook 1374:
1.23 crook 1375: @example
1376: @kbd{: add-two dup . ." + 2 =" 2 + . ;<return>} redefined add-two ok
1377: @end example
1.21 crook 1378:
1.23 crook 1379: Forth recognised that we were defining a word that already exists, and
1380: printed a message to warn us of that fact. Let's try out the new
1381: definition:
1.21 crook 1382:
1.23 crook 1383: @example
1384: @kbd{9 add-two<return>} 9 + 2 =11 ok
1385: @end example
1.21 crook 1386:
1.23 crook 1387: @noindent
1388: All that we've actually done here, though, is to create a new
1389: definition, with a particular name. The fact that there was already a
1390: definition with the same name did not make any difference to the way
1391: that the new definition was created (except that Forth printed a warning
1392: message). The old definition of add-two still exists (try @code{demo}
1393: again to see that this is true). Any new definition will use the new
1394: definition of @code{add-two}, but old definitions continue to use the
1395: version that already existed at the time that they were @code{compiled}.
1.21 crook 1396:
1.23 crook 1397: Before you go on to the next section, try defining and redefining some
1398: words of your own.
1.21 crook 1399:
1400: @comment ----------------------------------------------
1401: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
1402: @section How does that work?
1403: @cindex parsing words
1404:
1.23 crook 1405: Now we're going to take another look at the definition of @code{add-two}
1406: from the previous section. From our knowledge of the way that the text
1407: interpreter works, we would have expected this result when we tried to
1408: define @code{add-two}:
1.21 crook 1409:
1.23 crook 1410: @example
1411: @kbd{: add-two 2 + . " ;<return>}
1412: ^^^^^^^
1413: Error: Undefined word
1414: @end example
1.21 crook 1415:
1.23 crook 1416: The reason that this didn't happen is bound up in the way that @code{:}
1417: works. The word @code{:} does two special things. The first special
1418: thing that it does prevents the text interpreter from ever seeing the
1419: characters @code{add-two}. The text interpreter uses a variable called
1420: @cindex modifying >IN
1421: @code{>IN} (pronounced ''to-in'') to keep track of where it is in the
1422: input line. When it encounters the word @code{:} it behaves in exactly
1423: the same way as it does for any other word; it looks it up in the name
1424: dictionary, finds its xt and executes it. When @code{:} executes, it
1425: looks at the input buffer, finds the word @code{add-two} and advances the
1426: value of @code{>IN} to point past it. It then does some other stuff
1427: associated with creating the new definition (including creating an entry
1428: for @code{add-two} in the name dictionary). When the execution of @code{:}
1429: completes, control returns to the text interpreter, which is oblivious
1430: to the fact that it has been tricked into ignoring part of the input
1431: line.
1.21 crook 1432:
1.23 crook 1433: @cindex parsing words
1434: Words like @code{:} -- words that advance the value of @code{>IN} and so
1435: prevent the text interpreter from acting on the whole of the input line
1436: -- are called @var{parsing words}.
1437:
1438: @cindex state - effect on the text interpreter
1439: @cindex text interpreter - effect of state
1440: The second special thing that @code{:} does is to change the value of a
1441: variable called @code{state}, which affects the way that the text
1442: interpreter behaves. When Gforth starts up, @code{state} has the value
1443: 0, and the text interpreter is said to be in @var{interpret}
1444: mode. During a colon definition (started with @code{:}), @code{state} is
1445: set to -1 and the text interpreter is said to be in @var{compile}
1446: mode. The word @code{;} ends the definition -- one of the things that it
1447: does is to change the value of @code{state} back to 0.
1448:
1449: When the text interpreter is in @var{interpret} mode, we already know
1450: how it behaves; it looks for each character sequence in the dictionary,
1451: finds its xt and executes it, or it converts it to a number and pushes
1452: it onto the stack, or it fails to do either and generates an error.
1453:
1454: When the text interpreter is in @var{compile} mode, its behaviour is
1455: slightly different; it still looks for each character sequence in the
1456: dictionary and finds its xt, or converts it to a number, or fails to do
1457: either and generates an error. However, instead of executing the xt or
1458: pushing the number onto the stack it lays down (@var{compiles}) some
1459: magic to make that xt or number get executed or pushed at a later time;
1460: at the time that @code{add-two} is @var{executed}. Therefore, when you
1461: execute @code{add-two} its @var{run-time effect} is exactly the same as
1462: if you had typed @code{2 + .} outside of a definition, and pressed
1.26 ! crook 1463: carriage-return.
1.21 crook 1464:
1.23 crook 1465: In Forth, every word or number can be described in terms of three
1466: properties:
1.21 crook 1467:
1468: @itemize @bullet
1469: @item
1.23 crook 1470: Its behaviour at @var{compile} time
1.21 crook 1471: @item
1.23 crook 1472: Its behaviour at @var{interpret} time
1.21 crook 1473: @item
1.23 crook 1474: Its behaviour at @var{execution} time.
1.21 crook 1475: @end itemize
1476:
1.23 crook 1477: These behaviours are called the @var{semantics} of the word or
1478: number. The value of @var{state} determines whether the text
1479: interpreter will use the compile or interpret semantics of a word or
1480: number that it encounters.
1.21 crook 1481:
1482: @itemize @bullet
1483: @item
1.23 crook 1484: @cindex interpretation semantics
1485: When the text interpreter encounters a word or number in @var{interpret}
1486: state, it performs the @var{interpretation semantics} of the word or
1487: number.
1.21 crook 1488: @item
1.23 crook 1489: @cindex compilation semantics
1490: When the text interpreter encounters a word or number in @var{compile}
1491: state, it performs the @var{compilation semantics} of the word or
1492: number.
1.21 crook 1493: @end itemize
1494:
1.23 crook 1495: The behaviour of numbers is always the same:
1.21 crook 1496:
1497: @itemize @bullet
1498: @item
1.23 crook 1499: When the number is @var{compiled}, it is appended to the current
1500: definition so that its run-time behaviour is to execute. (In other
1501: words, the compilation semantics of a number are to postpone its
1502: execution semantics until the run-time of the definition that it is
1503: being compiled into.)
1504: @item
1505: When the number is @var{interpreted}, its behaviour is to execute. (In
1506: other words, the interpretation semantics of a number are to perform its
1507: execution semantics.)
1.21 crook 1508: @item
1.23 crook 1509: @cindex execution semantics
1510: When the number is @var{executed}, its behaviour is to push its value
1511: onto the stack. (In other words, the execution semantics of a number are
1512: to push its value onto the stack.)
1.21 crook 1513: @end itemize
1514:
1.23 crook 1515: The behaviour of a word is not so regular, but the vast majority behave
1516: like this:
1.21 crook 1517:
1518: @itemize @bullet
1519: @item
1.23 crook 1520: The @var{compilation semantics} of the word are to append its
1521: @var{execution semantics} to the current definition (so that its
1522: run-time behaviour is to execute).
1.21 crook 1523: @item
1.23 crook 1524: The @var{interpretation semantics} of the word are to execute.
1525: @item
1526: The @var{execution semantics} of the word are to do something useful.
1.21 crook 1527: @end itemize
1528:
1529:
1.23 crook 1530: The actual behaviour of any particular word depends upon the way in
1531: which it was defined. In all cases, the text interpreter decides what to
1532: do with the word; when it searches the name dictionary for a definition,
1533: it not only retrieves the xt for the word, it also retrieves a flag
1534: called the @var{immediate flag}. If the flag is set, the text
1535: interpreter will @var{execute} the word rather than @var{compiling}
1536: @cindex immediate words
1537: it. In other words, these so-called @var{immediate} words behave like
1538: this:
1.21 crook 1539:
1540: @itemize @bullet
1541: @item
1.23 crook 1542: The @var{compilation semantics} of the word are to perform its
1543: @var{execution semantics} (so that its compile-time behaviour is to
1544: execute).
1.21 crook 1545: @item
1.23 crook 1546: The @var{interpretation semantics} of the word are to execute.
1547: @item
1548: The @var{execution semantics} of the word are to do something useful.
1.21 crook 1549: @end itemize
1550:
1.23 crook 1551: This example shows the difference between an immediate and a
1552: non-immediate word:
1.21 crook 1553:
1554: @example
1.23 crook 1555: : show-state state @ . ;
1556: : show-state-now show-state ; immediate
1557: : word1 show-state ;
1558: : word2 show-state-now ;
1559: @end example
1560:
1561: The word @code{immediate} after the definition of @code{show-state-now}
1562: makes that word an immediate word. These definitions introduce a new
1563: word: @code{@@} (pronounced ''at''). This word fetches the value of a
1564: variable, and leaves it on the stack. Therefore, the behaviour of
1565: @code{show-state} is to print a number that represents the current value
1566: of @code{state}.
1567:
1568: When you execute @code{word1}, it prints the number 0, indicating
1569: that the system is in interpret state. When the text interpreter
1570: compiled the definition of @code{word1}, it encountered
1571: @code{show-state} whose compilation semantics are to append its
1572: execution semantics to the current definition. When you execute
1573: @code{word1}, it performs the execution semantics of @code{show-state}.
1574: At the time that @code{word1} (and therefore @code{show-state}) are
1575: executed, the system is in interpret state.
1576:
1577: When you pressed <return> after entering the definition of @code{word2},
1578: you should have seen the number -1 printed, followed by @code{ ok}. When
1579: the text interpreter compiled the definition of @code{word2}, it
1580: encountered @code{show-state-now}, an immediate word, whose compilation
1581: semantics are therefore to perform its execution semantics. It is
1582: executed straight away (even before the text interpreter has moved on
1583: to process another group of characters; the @code{;} in this
1584: example). The effect of executing it are to display the value of
1585: @code{state} @var{at the time that the definition of} @code{word2}
1586: @var{is being defined}. Printing -1 demonstrates that the system is in
1587: compilation state at this time. If you execute @code{word2} it does
1588: nothing at all.
1589:
1.26 ! crook 1590: @cindex @code{."}, how it works
1.23 crook 1591: Before leaving the subject of immediate words, consider the behaviour of
1592: @code{."} in the definition of @code{greet}, in the previous
1593: section. This word is both a parsing word and an immediate word. Notice
1594: that there is a space between @code{."} and the start of the text
1595: @code{Hello and welcome}, but that there is no space between the last
1596: letter of @code{welcome} and the @code{"} character. The reason for this
1597: is that @code{."} is a Forth word; it must have a space after it so that
1598: the text interpreter can identify it. The @code{"} is not a Forth word;
1599: it is a @var{delimiter}. The examples earlier show that, when the string
1600: is displayed, there is neither a space before the @code{H} nor after the
1601: @code{e}. Since @code{."} is an immediate word, it executes at the time
1.26 ! crook 1602: that @code{greet} is defined. When it executes, it searches forward in
1.23 crook 1603: the input line looking for the delimiter. When it finds the delimiter,
1604: it updates @code{>in} to point past the delimiter. It also compiles some
1605: magic code into the definition of @code{greet}; the xt of a run-time
1606: routine that prints a text string. It compiles the string @code{Hello
1607: and welcome} into memory so that it is available to be printed
1608: later. When the text interpreter gains control, the next word it finds
1609: in the input stream is @code{;} and so it terminates the definition of
1610: @code{greet}.
1.21 crook 1611:
1612:
1.23 crook 1613: @comment ----------------------------------------------
1614: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
1615: @section Forth is written in Forth
1616: @cindex structure of Forth programs
1.21 crook 1617:
1.23 crook 1618: When you start up a Forth compiler, a large number of definitions
1619: already exist. In Forth, you develop a new application using bottom-up
1620: programming techniques to create new definitions that are defined in
1621: terms of existing definitions. As you create each definition you can
1622: test and debug it interactively.
1623:
1624: If you have tried out the examples in this section, you will probably
1625: have typed them in by hand; when you leave Gforth, your definitions will
1626: be deleted. You can avoid this by using a text editor to enter Forth
1627: source code into a file, and then load all of the code from the file
1.26 ! crook 1628: using @code{include} (@xref{Forth source files}). A Forth source
1.23 crook 1629: file is processed by the text interpreter, just as though you had typed
1630: it in by hand@footnote{Actually, there are some subtle differences, like
1631: the fact that it doesn't print @code{ ok} at the end of each line}.
1632:
1633: Gforth also supports the traditional Forth alternative to using text
1634: files for program entry (@xref{Blocks}).
1635:
1636: In common with many, if not most, Forth compilers, most of Gforth is
1637: actually written in Forth. All of the @code{.fs} files in the
1638: installation directory are Forth source files, and you can look at them
1639: to see examples of Forth programming.
1640:
1641: Gforth maintains a history file that records every line that you
1642: type to the text interpreter. This file is preserved between sessions,
1643: and is used to provide the command-line recall facility. If you enter
1644: long definitions by hand, you can use a text editor to paste them out of
1645: the history file into a Forth source file for reuse at a later time.
1646:
1647: @cindex history file
1.26 ! crook 1648: @cindex @file{.gforth-history}
! 1649: @cindex @code{GFORTHHIST} environment variable
! 1650: @cindex environment variables
1.23 crook 1651: You can find out the name of your history file using @code{history-file
1652: type }. On non-Unix systems you can find the location of the file using
1.26 ! crook 1653: @code{history-dir type }@footnote{The environment variable @code{GFORTHHIST}
1.23 crook 1654: determines the location of the file.}
1.21 crook 1655:
1656:
1657:
1.23 crook 1658: @comment ----------------------------------------------
1659: @node Review - elements of a Forth system, Exercises, Forth is written in Forth, Introduction
1660: @section Review - elements of a Forth system
1661: @cindex elements of a Forth system
1.21 crook 1662:
1.23 crook 1663: To summarise this chapter:
1.21 crook 1664:
1665:
1.23 crook 1666: @itemize @bullet
1667: @item
1668: Forth programs use @var{factoring} to break a problem down into small
1669: fragments called @var{words} or @var{definitions}.
1670: @item
1671: Forth program development is an interactive process.
1672: @item
1673: The main command loop that accepts input, and controls both
1674: interpretation and compilation, is called the @var{text interpreter}
1.26 ! crook 1675: (also known as the @var{outer interpreter}).
1.23 crook 1676: @item
1677: Forth has a very simple syntax, consisting of words and numbers
1678: separated by spaces or carriage-return characters. Any additional syntax
1679: is imposed by @var{parsing words}.
1680: @item
1681: Forth uses a stack to pass parameters between words. As a result, it
1682: uses postfix notation.
1683: @item
1684: To use a word that has previously been defined, the text interpreter
1685: searches for the word in the @var{name dictionary}.
1686: @item
1687: Words have @var{interpretation semantics}, @var{compilation semantics}
1688: and @var{execution semantics}.
1689: @item
1690: The text interpreter uses the value of @code{state} to select between
1691: the use of the @var{interpretation semantics} and the @var{compilation
1692: semantics} of a word that it encounters.
1693: @item
1694: The relationship between the @var{interpretation semantics}, @var{compilation semantics}
1695: and @var{execution semantics} for a word depend upon the way in which
1.26 ! crook 1696: the word was defined (for example, whether it is an @var{immediate} word).
1.23 crook 1697: @item
1698: Forth definitions can be implemented in Forth (called @var{high-level
1699: definitions}) or in some other way (usually a lower-level language and
1700: as a result often called @var{low-level definitions}, @var{code
1701: definitions} or @var{primitives}).
1702: @item
1703: Many Forth systems are implemented mainly in Forth.
1704: @item
1705: You now know enough to read and understand the rest of this manual and
1.26 ! crook 1706: the ANS Forth document.
1.23 crook 1707: @end itemize
1.21 crook 1708:
1709:
1.23 crook 1710: @comment TODO - other defining words
1711: @comment other parsing words
1712: @comment Your first loop
1713: @comment syntax and semantics
1714: @comment DOES>
1715: @comment taste of other elements of Forth
1.21 crook 1716:
1717:
1718:
1719: @comment ----------------------------------------------
1.23 crook 1720: @node Exercises, ,Review - elements of a Forth system, Introduction
1721: @section Exercises
1.21 crook 1722: @cindex elements of a Forth system
1723:
1.23 crook 1724: Amazing as it may seem, if you have read (and understood) this far, you
1725: know almost all the fundamentals about the inner workings of a Forth
1726: system. You certainly know enough to be able to read and understand the
1727: rest of this manual, to learn more about the facilities that Gforth
1728: provides. Even scarier, you know almost enough to implement your own Forth
1729: system. However, that's not a good idea just yet.. better to try writing
1730: some programs in Gforth.
1731:
1.26 ! crook 1732: The large number of Forth words available in ANS Forth and
1.23 crook 1733: Gforth make learning Forth somewhat daunting. To make the problem
1734: easier, use the index of this manual to learn more about these words:
1.21 crook 1735:
1.23 crook 1736: ..levels of Forth words.
1.21 crook 1737:
1738:
1739: Ideally, provide a set of programming excercises linked into the stuff
1740: done already and into other sections of the manual. Provide solutions to
1741: all the exercises in a .fs file in the distribution. Get some
1742: inspiration from Starting Forth and Kelly&Spies.
1743:
1744:
1.26 ! crook 1745: @c ******************************************************************
! 1746: @node Invoking Gforth, Words, Introduction, Top
! 1747: @chapter Invoking Gforth
! 1748: @cindex Gforth - invoking
! 1749: @cindex invoking Gforth
! 1750: @cindex running Gforth
! 1751: @cindex command-line options
! 1752: @cindex options on the command line
! 1753: @cindex flags on the command line
! 1754:
! 1755: You will usually just say @code{gforth}. In many other cases the default
! 1756: Gforth image will be invoked like this:
! 1757: @example
! 1758: gforth [files] [-e forth-code]
! 1759: @end example
! 1760: This interprets the contents of the files and the Forth code in the order they
! 1761: are given.
1.23 crook 1762:
1.26 ! crook 1763: In general, the command line looks like this:
1.1 anton 1764:
1.26 ! crook 1765: @example
! 1766: gforth [initialization options] [image-specific options]
! 1767: @end example
1.1 anton 1768:
1.26 ! crook 1769: The initialization options must come before the rest of the command
! 1770: line. They are:
1.1 anton 1771:
1.26 ! crook 1772: @table @code
! 1773: @cindex -i, command-line option
! 1774: @cindex --image-file, command-line option
! 1775: @item --image-file @var{file}
! 1776: @itemx -i @var{file}
! 1777: Loads the Forth image @var{file} instead of the default
! 1778: @file{gforth.fi} (@pxref{Image Files}).
1.1 anton 1779:
1.26 ! crook 1780: @cindex --path, command-line option
1.1 anton 1781: @cindex -p, command-line option
1782: @item --path @var{path}
1783: @itemx -p @var{path}
1784: Uses @var{path} for searching the image file and Forth source code files
1785: instead of the default in the environment variable @code{GFORTHPATH} or
1786: the path specified at installation time (e.g.,
1787: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
1788: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1789:
1790: @cindex --dictionary-size, command-line option
1791: @cindex -m, command-line option
1792: @cindex @var{size} parameters for command-line options
1793: @cindex size of the dictionary and the stacks
1794: @item --dictionary-size @var{size}
1795: @itemx -m @var{size}
1796: Allocate @var{size} space for the Forth dictionary space instead of
1797: using the default specified in the image (typically 256K). The
1.21 crook 1798: @var{size} specification for this and subsequent options consists of
1799: an integer and a unit (e.g.,
1.1 anton 1800: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
1.12 anton 1801: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
1802: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
1803: @code{e} is used.
1.1 anton 1804:
1805: @cindex --data-stack-size, command-line option
1806: @cindex -d, command-line option
1807: @item --data-stack-size @var{size}
1808: @itemx -d @var{size}
1809: Allocate @var{size} space for the data stack instead of using the
1810: default specified in the image (typically 16K).
1811:
1812: @cindex --return-stack-size, command-line option
1813: @cindex -r, command-line option
1814: @item --return-stack-size @var{size}
1815: @itemx -r @var{size}
1816: Allocate @var{size} space for the return stack instead of using the
1817: default specified in the image (typically 15K).
1818:
1819: @cindex --fp-stack-size, command-line option
1820: @cindex -f, command-line option
1821: @item --fp-stack-size @var{size}
1822: @itemx -f @var{size}
1823: Allocate @var{size} space for the floating point stack instead of
1824: using the default specified in the image (typically 15.5K). In this case
1825: the unit specifier @code{e} refers to floating point numbers.
1826:
1827: @cindex --locals-stack-size, command-line option
1828: @cindex -l, command-line option
1829: @item --locals-stack-size @var{size}
1830: @itemx -l @var{size}
1831: Allocate @var{size} space for the locals stack instead of using the
1832: default specified in the image (typically 14.5K).
1833:
1834: @cindex -h, command-line option
1835: @cindex --help, command-line option
1836: @item --help
1837: @itemx -h
1838: Print a message about the command-line options
1839:
1840: @cindex -v, command-line option
1841: @cindex --version, command-line option
1842: @item --version
1843: @itemx -v
1844: Print version and exit
1845:
1846: @cindex --debug, command-line option
1847: @item --debug
1848: Print some information useful for debugging on startup.
1849:
1850: @cindex --offset-image, command-line option
1851: @item --offset-image
1852: Start the dictionary at a slightly different position than would be used
1853: otherwise (useful for creating data-relocatable images,
1854: @pxref{Data-Relocatable Image Files}).
1855:
1.5 anton 1856: @cindex --no-offset-im, command-line option
1857: @item --no-offset-im
1858: Start the dictionary at the normal position.
1859:
1.1 anton 1860: @cindex --clear-dictionary, command-line option
1861: @item --clear-dictionary
1862: Initialize all bytes in the dictionary to 0 before loading the image
1863: (@pxref{Data-Relocatable Image Files}).
1.5 anton 1864:
1865: @cindex --die-on-signal, command-line-option
1866: @item --die-on-signal
1867: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
1868: or the segmentation violation SIGSEGV) by translating it into a Forth
1869: @code{THROW}. With this option, Gforth exits if it receives such a
1870: signal. This option is useful when the engine and/or the image might be
1871: severely broken (such that it causes another signal before recovering
1872: from the first); this option avoids endless loops in such cases.
1.1 anton 1873: @end table
1874:
1875: @cindex loading files at startup
1876: @cindex executing code on startup
1877: @cindex batch processing with Gforth
1878: As explained above, the image-specific command-line arguments for the
1879: default image @file{gforth.fi} consist of a sequence of filenames and
1880: @code{-e @var{forth-code}} options that are interpreted in the sequence
1881: in which they are given. The @code{-e @var{forth-code}} or
1.21 crook 1882: @code{--evaluate @var{forth-code}} option evaluates the Forth
1.1 anton 1883: code. This option takes only one argument; if you want to evaluate more
1.26 ! crook 1884: Forth words, you have to quote them or use @code{-e} several times. To exit
1.1 anton 1885: after processing the command line (instead of entering interactive mode)
1886: append @code{-e bye} to the command line.
1887:
1888: @cindex versions, invoking other versions of Gforth
1889: If you have several versions of Gforth installed, @code{gforth} will
1890: invoke the version that was installed last. @code{gforth-@var{version}}
1891: invokes a specific version. You may want to use the option
1892: @code{--path}, if your environment contains the variable
1893: @code{GFORTHPATH}.
1894:
1895: Not yet implemented:
1896: On startup the system first executes the system initialization file
1897: (unless the option @code{--no-init-file} is given; note that the system
1898: resulting from using this option may not be ANS Forth conformant). Then
1899: the user initialization file @file{.gforth.fs} is executed, unless the
1900: option @code{--no-rc} is given; this file is first searched in @file{.},
1901: then in @file{~}, then in the normal path (see above).
1902:
1.21 crook 1903:
1904: @cindex Gforth - leaving
1905: @cindex leaving Gforth
1906:
1907: You can leave Gforth by typing @code{bye} or (if you invoked Gforth with
1908: the @code{--die-on-signal} option) Ctrl-C. When you leave Gforth, all of
1909: your definitions and data are discarded. @xref{Image Files} for ways
1910: of saving the state of the system before leaving Gforth.
1911:
1912: doc-bye
1913:
1914:
1.23 crook 1915: @comment TODO add section on environment variables.. find them by
1916: @comment grep for "getenv" -- they are:
1917: @comment GFORTHHIST
1918: @comment POSIXELY_CORRECT
1919: @comment TMP TEMP
1920: @comment HOME
1921: @comment LINES
1922: @comment COLUMNS
1923: @comment GFORTHPATH
1924: @comment FORTHSIZES ?? in INSTALL but cannot find it in the source
1925: @comment some are in .c files.
1926:
1927:
1.26 ! crook 1928: @c ******************************************************************
1.24 anton 1929: @node Words, Error messages, Invoking Gforth, Top
1.1 anton 1930: @chapter Forth Words
1.26 ! crook 1931: @cindex words
1.1 anton 1932:
1933: @menu
1934: * Notation::
1.21 crook 1935: * Comments::
1936: * Boolean Flags::
1.1 anton 1937: * Arithmetic::
1938: * Stack Manipulation::
1.5 anton 1939: * Memory::
1.1 anton 1940: * Control Structures::
1941: * Defining Words::
1.21 crook 1942: * The Text Interpreter::
1.12 anton 1943: * Tokens for Words::
1.21 crook 1944: * Word Lists::
1945: * Environmental Queries::
1.12 anton 1946: * Files::
1947: * Blocks::
1948: * Other I/O::
1949: * Programming Tools::
1950: * Assembler and Code Words::
1951: * Threading Words::
1.26 ! crook 1952: * Locals::
! 1953: * Structures::
! 1954: * Object-oriented Forth::
1.21 crook 1955: * Passing Commands to the OS::
1956: * Miscellaneous Words::
1.1 anton 1957: @end menu
1958:
1.21 crook 1959: @node Notation, Comments, Words, Words
1.1 anton 1960: @section Notation
1961: @cindex notation of glossary entries
1962: @cindex format of glossary entries
1963: @cindex glossary notation format
1964: @cindex word glossary entry format
1965:
1966: The Forth words are described in this section in the glossary notation
1967: that has become a de-facto standard for Forth texts, i.e.,
1968:
1969: @format
1970: @var{word} @var{Stack effect} @var{wordset} @var{pronunciation}
1971: @end format
1972: @var{Description}
1973:
1974: @table @var
1975: @item word
1.26 ! crook 1976: @cindex case-sensitivity
! 1977: The name of the word. Gforth is case-insensitive, so you can type the
! 1978: words in in lower case (However, @pxref{core-idef,
! 1979: Implementation-defined options, Implementation-defined options}).
1.1 anton 1980:
1981: @item Stack effect
1982: @cindex stack effect
1983: The stack effect is written in the notation @code{@var{before} --
1984: @var{after}}, where @var{before} and @var{after} describe the top of
1985: stack entries before and after the execution of the word. The rest of
1986: the stack is not touched by the word. The top of stack is rightmost,
1987: i.e., a stack sequence is written as it is typed in. Note that Gforth
1988: uses a separate floating point stack, but a unified stack
1989: notation. Also, return stack effects are not shown in @var{stack
1990: effect}, but in @var{Description}. The name of a stack item describes
1991: the type and/or the function of the item. See below for a discussion of
1992: the types.
1993:
1994: All words have two stack effects: A compile-time stack effect and a
1995: run-time stack effect. The compile-time stack-effect of most words is
1996: @var{ -- }. If the compile-time stack-effect of a word deviates from
1997: this standard behaviour, or the word does other unusual things at
1998: compile time, both stack effects are shown; otherwise only the run-time
1999: stack effect is shown.
2000:
2001: @cindex pronounciation of words
2002: @item pronunciation
2003: How the word is pronounced.
2004:
2005: @cindex wordset
2006: @item wordset
1.21 crook 2007: The ANS Forth standard is divided into several word sets. A standard
2008: system need not support all of them. Therefore, in theory, the fewer
2009: word sets your program uses the more portable it will be. However, we
2010: suspect that most ANS Forth systems on personal machines will feature
1.26 ! crook 2011: all word sets. Words that are not defined in ANS Forth have
1.21 crook 2012: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 2013: describes words that will work in future releases of Gforth;
2014: @code{gforth-internal} words are more volatile. Environmental query
2015: strings are also displayed like words; you can recognize them by the
1.21 crook 2016: @code{environment} in the word set field.
1.1 anton 2017:
2018: @item Description
2019: A description of the behaviour of the word.
2020: @end table
2021:
2022: @cindex types of stack items
2023: @cindex stack item types
2024: The type of a stack item is specified by the character(s) the name
2025: starts with:
2026:
2027: @table @code
2028: @item f
2029: @cindex @code{f}, stack item type
2030: Boolean flags, i.e. @code{false} or @code{true}.
2031: @item c
2032: @cindex @code{c}, stack item type
2033: Char
2034: @item w
2035: @cindex @code{w}, stack item type
2036: Cell, can contain an integer or an address
2037: @item n
2038: @cindex @code{n}, stack item type
2039: signed integer
2040: @item u
2041: @cindex @code{u}, stack item type
2042: unsigned integer
2043: @item d
2044: @cindex @code{d}, stack item type
2045: double sized signed integer
2046: @item ud
2047: @cindex @code{ud}, stack item type
2048: double sized unsigned integer
2049: @item r
2050: @cindex @code{r}, stack item type
2051: Float (on the FP stack)
1.21 crook 2052: @item a-
1.1 anton 2053: @cindex @code{a_}, stack item type
2054: Cell-aligned address
1.21 crook 2055: @item c-
1.1 anton 2056: @cindex @code{c_}, stack item type
2057: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 2058: @item f-
1.1 anton 2059: @cindex @code{f_}, stack item type
2060: Float-aligned address
1.21 crook 2061: @item df-
1.1 anton 2062: @cindex @code{df_}, stack item type
2063: Address aligned for IEEE double precision float
1.21 crook 2064: @item sf-
1.1 anton 2065: @cindex @code{sf_}, stack item type
2066: Address aligned for IEEE single precision float
2067: @item xt
2068: @cindex @code{xt}, stack item type
2069: Execution token, same size as Cell
2070: @item wid
2071: @cindex @code{wid}, stack item type
1.21 crook 2072: Word list ID, same size as Cell
1.1 anton 2073: @item f83name
2074: @cindex @code{f83name}, stack item type
2075: Pointer to a name structure
2076: @item "
2077: @cindex @code{"}, stack item type
1.12 anton 2078: string in the input stream (not on the stack). The terminating character
2079: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 2080: quotes.
2081: @end table
2082:
1.21 crook 2083: @node Comments, Boolean Flags, Notation, Words
2084: @section Comments
1.26 ! crook 2085: @cindex comments
1.21 crook 2086:
1.26 ! crook 2087: Forth supports two styles of comment; the traditional @var{in-line} comment,
! 2088: @code{(} and its modern cousin, the @var{comment to end of line}; @code{\}.
1.21 crook 2089:
1.23 crook 2090: doc-(
1.21 crook 2091: doc-\
1.23 crook 2092: doc-\G
1.21 crook 2093:
2094: @node Boolean Flags, Arithmetic, Comments, Words
2095: @section Boolean Flags
1.26 ! crook 2096: @cindex Boolean flags
1.21 crook 2097:
2098: A Boolean flag is cell-sized. A cell with all bits clear represents the
2099: flag @code{false} and a flag with all bits set represents the flag
1.26 ! crook 2100: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.21 crook 2101: a cell that has @var{any} bit set as @code{true}.
2102:
2103: doc-true
2104: doc-false
2105:
2106:
2107: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 2108: @section Arithmetic
2109: @cindex arithmetic words
2110:
2111: @cindex division with potentially negative operands
2112: Forth arithmetic is not checked, i.e., you will not hear about integer
2113: overflow on addition or multiplication, you may hear about division by
2114: zero if you are lucky. The operator is written after the operands, but
2115: the operands are still in the original order. I.e., the infix @code{2-1}
2116: corresponds to @code{2 1 -}. Forth offers a variety of division
2117: operators. If you perform division with potentially negative operands,
2118: you do not want to use @code{/} or @code{/mod} with its undefined
2119: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
2120: former, @pxref{Mixed precision}).
1.26 ! crook 2121: @comment TODO discuss the different division forms and the std approach
1.1 anton 2122:
2123: @menu
2124: * Single precision::
2125: * Bitwise operations::
1.21 crook 2126: * Double precision:: Double-cell integer arithmetic
2127: * Numeric comparison::
1.1 anton 2128: * Mixed precision:: operations with single and double-cell integers
2129: * Floating Point::
2130: @end menu
2131:
2132: @node Single precision, Bitwise operations, Arithmetic, Arithmetic
2133: @subsection Single precision
2134: @cindex single precision arithmetic words
2135:
1.21 crook 2136: By default, numbers in Forth are single-precision integers that are 1
1.26 ! crook 2137: cell in size. They can be signed or unsigned, depending upon how you
1.21 crook 2138: treat them. @xref{Number Conversion} for the rules used by the text
2139: interpreter for recognising single-precision integers.
2140:
1.1 anton 2141: doc-+
1.21 crook 2142: doc-1+
1.1 anton 2143: doc--
1.21 crook 2144: doc-1-
1.1 anton 2145: doc-*
2146: doc-/
2147: doc-mod
2148: doc-/mod
2149: doc-negate
2150: doc-abs
2151: doc-min
2152: doc-max
1.21 crook 2153: doc-d>s
1.1 anton 2154:
1.21 crook 2155: @node Bitwise operations, Double precision, Single precision, Arithmetic
1.1 anton 2156: @subsection Bitwise operations
2157: @cindex bitwise operation words
2158:
2159: doc-and
2160: doc-or
2161: doc-xor
2162: doc-invert
1.21 crook 2163: doc-lshift
2164: doc-rshift
1.1 anton 2165: doc-2*
1.21 crook 2166: doc-d2*
1.1 anton 2167: doc-2/
1.21 crook 2168: doc-d2/
2169:
2170: @node Double precision, Numeric comparison, Bitwise operations, Arithmetic
2171: @subsection Double precision
2172: @cindex double precision arithmetic words
2173:
2174: @xref{Number Conversion} for the rules used by the text interpreter for
2175: recognising double-precision integers.
2176:
2177: A double precision number is represented by a cell pair, with the most
1.26 ! crook 2178: significant digit at the TOS. It is trivial to convert an unsigned
! 2179: single to an (unsigned) double; simply push a @code{0} onto the
! 2180: TOS. Since numbers are represented by Gforth using 2's complement
! 2181: arithmetic, converting a signed single to a (signed) double requires
! 2182: sign-extension across the most significant digit. This can be achieved
! 2183: using @code{s>d}. The moral of the story is that you cannot convert a
! 2184: number without knowing whether it represents an unsigned or a
! 2185: signed number.
1.21 crook 2186:
2187: doc-s>d
2188: doc-d+
2189: doc-d-
2190: doc-dnegate
2191: doc-dabs
2192: doc-dmin
2193: doc-dmax
2194:
2195: @node Numeric comparison, Mixed precision, Double precision, Arithmetic
2196: @subsection Numeric comparison
2197: @cindex numeric comparison words
2198:
2199: doc-0<
1.23 crook 2200: doc-0<=
1.21 crook 2201: doc-0<>
2202: doc-0=
1.23 crook 2203: doc-0>
2204: doc-0>=
1.21 crook 2205: doc-<
1.23 crook 2206: doc-<=
1.21 crook 2207: doc-<>
2208: doc-=
2209: doc->
1.23 crook 2210: doc->=
2211:
1.21 crook 2212: doc-d0<
1.23 crook 2213: doc-d0<=
2214: doc-d0<>
1.21 crook 2215: doc-d0=
1.23 crook 2216: doc-d0>
2217: doc-d0>=
1.21 crook 2218: doc-d<
1.23 crook 2219: doc-d<=
2220: doc-d<>
1.21 crook 2221: doc-d=
1.23 crook 2222: doc-d>
2223: doc-d>=
2224:
1.21 crook 2225: doc-u<
2226: doc-du<
2227: doc-u>
1.23 crook 2228: doc-u<=
2229: @comment why u<> and u= .. they are the same as <> and =
2230: doc-u<>
2231: doc-u=
2232: doc-u>=
1.21 crook 2233: doc-within
1.1 anton 2234:
1.21 crook 2235: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 2236: @subsection Mixed precision
2237: @cindex mixed precision arithmetic words
2238:
2239: doc-m+
2240: doc-*/
2241: doc-*/mod
2242: doc-m*
2243: doc-um*
2244: doc-m*/
2245: doc-um/mod
2246: doc-fm/mod
2247: doc-sm/rem
2248:
1.21 crook 2249: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 2250: @subsection Floating Point
2251: @cindex floating point arithmetic words
2252:
1.21 crook 2253: @xref{Number Conversion} for the rules used by the text interpreter for
2254: recognising floating-point numbers.
1.1 anton 2255:
2256: @cindex angles in trigonometric operations
2257: @cindex trigonometric operations
2258: Angles in floating point operations are given in radians (a full circle
1.26 ! crook 2259: has 2 pi radians). Gforth has a separate floating point
! 2260: stack, but the documentation uses the unified notation.
1.1 anton 2261:
2262: @cindex floating-point arithmetic, pitfalls
2263: Floating point numbers have a number of unpleasant surprises for the
2264: unwary (e.g., floating point addition is not associative) and even a few
2265: for the wary. You should not use them unless you know what you are doing
2266: or you don't care that the results you get are totally bogus. If you
2267: want to learn about the problems of floating point numbers (and how to
2268: avoid them), you might start with @cite{David Goldberg, What Every
2269: Computer Scientist Should Know About Floating-Point Arithmetic, ACM
1.17 anton 2270: Computing Surveys 23(1):5@minus{}48, March 1991}
2271: (@url{http://www.validgh.com/goldberg/paper.ps}).
1.1 anton 2272:
1.21 crook 2273: doc-d>f
2274: doc-f>d
1.1 anton 2275: doc-f+
2276: doc-f-
2277: doc-f*
2278: doc-f/
2279: doc-fnegate
2280: doc-fabs
2281: doc-fmax
2282: doc-fmin
2283: doc-floor
2284: doc-fround
2285: doc-f**
2286: doc-fsqrt
2287: doc-fexp
2288: doc-fexpm1
2289: doc-fln
2290: doc-flnp1
2291: doc-flog
2292: doc-falog
2293: doc-fsin
2294: doc-fcos
2295: doc-fsincos
2296: doc-ftan
2297: doc-fasin
2298: doc-facos
2299: doc-fatan
2300: doc-fatan2
2301: doc-fsinh
2302: doc-fcosh
2303: doc-ftanh
2304: doc-fasinh
2305: doc-facosh
2306: doc-fatanh
1.21 crook 2307: doc-pi
2308: doc-f0<
2309: doc-f0=
2310: doc-f<
2311: doc-f<=
2312: doc-f<>
2313: doc-f=
2314: doc-f>
2315: doc-f>=
2316: doc-f2*
2317: doc-f2/
2318: doc-1/f
2319: doc-f~
2320: doc-precision
2321: doc-set-precision
1.1 anton 2322:
2323: @node Stack Manipulation, Memory, Arithmetic, Words
2324: @section Stack Manipulation
2325: @cindex stack manipulation words
2326:
2327: @cindex floating-point stack in the standard
1.21 crook 2328: Gforth maintains a number of separate stacks:
2329:
2330: @itemize @bullet
2331: @item
2332: A data stack (aka parameter stack) -- for characters, cells,
2333: addresses, and double cells.
2334:
2335: @item
2336: A floating point stack -- for floating point numbers.
2337:
2338: @item
2339: A return stack -- for storing the return addresses of colon
2340: definitions and other data.
2341:
2342: @item
2343: A locals stack for storing local variables.
2344: @end itemize
2345:
2346: Whilst every sane Forth has a separate floating-point stack, it is not
2347: strictly required; an ANS Forth system could theoretically keep
2348: floating-point numbers on the data stack. As an additional difficulty,
2349: you don't know how many cells a floating-point number takes. It is
2350: reportedly possible to write words in a way that they work also for a
2351: unified stack model, but we do not recommend trying it. Instead, just
2352: say that your program has an environmental dependency on a separate
2353: floating-point stack.
2354:
2355: doc-floating-stack
1.1 anton 2356:
2357: @cindex return stack and locals
2358: @cindex locals and return stack
1.21 crook 2359: A Forth system is allowed to keep local variables on the
1.1 anton 2360: return stack. This is reasonable, as local variables usually eliminate
2361: the need to use the return stack explicitly. So, if you want to produce
1.21 crook 2362: a standard compliant program and you are using local variables in a
2363: word, forget about return stack manipulations in that word (refer to the
1.1 anton 2364: standard document for the exact rules).
2365:
2366: @menu
2367: * Data stack::
2368: * Floating point stack::
2369: * Return stack::
2370: * Locals stack::
2371: * Stack pointer manipulation::
2372: @end menu
2373:
2374: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
2375: @subsection Data stack
2376: @cindex data stack manipulation words
2377: @cindex stack manipulations words, data stack
2378:
2379: doc-drop
2380: doc-nip
2381: doc-dup
2382: doc-over
2383: doc-tuck
2384: doc-swap
1.21 crook 2385: doc-pick
1.1 anton 2386: doc-rot
2387: doc--rot
2388: doc-?dup
2389: doc-roll
2390: doc-2drop
2391: doc-2nip
2392: doc-2dup
2393: doc-2over
2394: doc-2tuck
2395: doc-2swap
2396: doc-2rot
2397:
2398: @node Floating point stack, Return stack, Data stack, Stack Manipulation
2399: @subsection Floating point stack
2400: @cindex floating-point stack manipulation words
2401: @cindex stack manipulation words, floating-point stack
2402:
2403: doc-fdrop
2404: doc-fnip
2405: doc-fdup
2406: doc-fover
2407: doc-ftuck
2408: doc-fswap
1.21 crook 2409: doc-fpick
1.1 anton 2410: doc-frot
2411:
2412: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
2413: @subsection Return stack
2414: @cindex return stack manipulation words
2415: @cindex stack manipulation words, return stack
2416:
2417: doc->r
2418: doc-r>
2419: doc-r@
2420: doc-rdrop
2421: doc-2>r
2422: doc-2r>
2423: doc-2r@
2424: doc-2rdrop
2425:
2426: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
2427: @subsection Locals stack
2428:
1.26 ! crook 2429: @comment TODO
1.21 crook 2430:
1.1 anton 2431: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
2432: @subsection Stack pointer manipulation
2433: @cindex stack pointer manipulation words
2434:
1.21 crook 2435: doc-sp0
2436: doc-s0
1.1 anton 2437: doc-sp@
2438: doc-sp!
1.21 crook 2439: doc-fp0
1.1 anton 2440: doc-fp@
2441: doc-fp!
1.21 crook 2442: doc-rp0
2443: doc-r0
1.1 anton 2444: doc-rp@
2445: doc-rp!
1.21 crook 2446: doc-lp0
2447: doc-l0
1.1 anton 2448: doc-lp@
2449: doc-lp!
2450:
2451: @node Memory, Control Structures, Stack Manipulation, Words
2452: @section Memory
1.26 ! crook 2453: @cindex memory words
1.1 anton 2454:
2455: @menu
2456: * Memory Access::
2457: * Address arithmetic::
2458: * Memory Blocks::
2459: @end menu
2460:
2461: @node Memory Access, Address arithmetic, Memory, Memory
2462: @subsection Memory Access
2463: @cindex memory access words
2464:
2465: doc-@
2466: doc-!
2467: doc-+!
2468: doc-c@
2469: doc-c!
2470: doc-2@
2471: doc-2!
2472: doc-f@
2473: doc-f!
2474: doc-sf@
2475: doc-sf!
2476: doc-df@
2477: doc-df!
2478:
2479: @node Address arithmetic, Memory Blocks, Memory Access, Memory
2480: @subsection Address arithmetic
2481: @cindex address arithmetic words
2482:
2483: ANS Forth does not specify the sizes of the data types. Instead, it
2484: offers a number of words for computing sizes and doing address
2485: arithmetic. Basically, address arithmetic is performed in terms of
2486: address units (aus); on most systems the address unit is one byte. Note
2487: that a character may have more than one au, so @code{chars} is no noop
2488: (on systems where it is a noop, it compiles to nothing).
2489:
2490: @cindex alignment of addresses for types
2491: ANS Forth also defines words for aligning addresses for specific
2492: types. Many computers require that accesses to specific data types
2493: must only occur at specific addresses; e.g., that cells may only be
2494: accessed at addresses divisible by 4. Even if a machine allows unaligned
2495: accesses, it can usually perform aligned accesses faster.
2496:
2497: For the performance-conscious: alignment operations are usually only
2498: necessary during the definition of a data structure, not during the
2499: (more frequent) accesses to it.
2500:
2501: ANS Forth defines no words for character-aligning addresses. This is not
2502: an oversight, but reflects the fact that addresses that are not
2503: char-aligned have no use in the standard and therefore will not be
2504: created.
2505:
2506: @cindex @code{CREATE} and alignment
1.26 ! crook 2507: AND Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 2508: are cell-aligned; in addition, Gforth guarantees that these addresses
2509: are aligned for all purposes.
2510:
1.26 ! crook 2511: Note that the ANS Forth word @code{char} has nothing to do with address
! 2512: arithmetic.
1.1 anton 2513:
2514: doc-chars
2515: doc-char+
2516: doc-cells
2517: doc-cell+
2518: doc-cell
2519: doc-align
2520: doc-aligned
2521: doc-floats
2522: doc-float+
2523: doc-float
2524: doc-falign
2525: doc-faligned
2526: doc-sfloats
2527: doc-sfloat+
2528: doc-sfalign
2529: doc-sfaligned
2530: doc-dfloats
2531: doc-dfloat+
2532: doc-dfalign
2533: doc-dfaligned
2534: doc-maxalign
2535: doc-maxaligned
2536: doc-cfalign
2537: doc-cfaligned
2538: doc-address-unit-bits
2539:
2540: @node Memory Blocks, , Address arithmetic, Memory
2541: @subsection Memory Blocks
2542: @cindex memory block words
2543:
1.21 crook 2544: Some of these words work on address units (increments of @code{CELL}),
2545: and expect a @code{CELL}-aligned address. Others work on character units
2546: (increments of @code{CHAR}), and expect a @code{CHAR}-aligned
2547: address. Choose the correct operation depending upon your data type. If
2548: you are moving a block of memory (for example, a region reserved by
2549: @code{allot}) it is safe to use @code{move}, and it should be faster
2550: than using @code{cmove}. If you are moving (for example) a string
2551: compiled using @code{S"}, it is not portable to use @code{move}; the
2552: alignment of the string in memory could change, and the relationship
2553: between @code{CELL} and @code{CHAR} could change.
2554:
2555: When copying characters between overlapping memory regions, choose
2556: carefully between @code{cmove} and @code{cmove>}.
2557:
2558: You can only use any of these words @var{portably} to access data space.
2559:
2560: @comment - think the naming of the arguments is wrong for move
1.1 anton 2561: doc-move
2562: doc-erase
2563:
1.21 crook 2564: @comment - think the naming of the arguments is wrong for cmove
1.1 anton 2565: doc-cmove
1.21 crook 2566: @comment - think the naming of the arguments is wrong for cmove>
1.1 anton 2567: doc-cmove>
2568: doc-fill
1.21 crook 2569: @comment - think the naming of the arguments is wrong for blank
1.1 anton 2570: doc-blank
1.21 crook 2571: doc-compare
2572: doc-search
1.1 anton 2573:
1.26 ! crook 2574: @node Control Structures, Defining Words, Memory, Words
1.1 anton 2575: @section Control Structures
2576: @cindex control structures
2577:
2578: Control structures in Forth cannot be used in interpret state, only in
2579: compile state@footnote{More precisely, they have no interpretation
2580: semantics (@pxref{Interpretation and Compilation Semantics})}, i.e., in
2581: a colon definition. We do not like this limitation, but have not seen a
2582: satisfying way around it yet, although many schemes have been proposed.
2583:
2584: @menu
2585: * Selection::
2586: * Simple Loops::
2587: * Counted Loops::
2588: * Arbitrary control structures::
2589: * Calls and returns::
2590: * Exception Handling::
2591: @end menu
2592:
2593: @node Selection, Simple Loops, Control Structures, Control Structures
2594: @subsection Selection
2595: @cindex selection control structures
2596: @cindex control structures for selection
2597:
2598: @cindex @code{IF} control structure
2599: @example
2600: @var{flag}
2601: IF
2602: @var{code}
2603: ENDIF
2604: @end example
1.21 crook 2605: @noindent
1.1 anton 2606: or
2607: @example
2608: @var{flag}
2609: IF
2610: @var{code1}
2611: ELSE
2612: @var{code2}
2613: ENDIF
2614: @end example
2615:
2616: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
2617: standard, and @code{ENDIF} is not, although it is quite popular. We
2618: recommend using @code{ENDIF}, because it is less confusing for people
2619: who also know other languages (and is not prone to reinforcing negative
2620: prejudices against Forth in these people). Adding @code{ENDIF} to a
2621: system that only supplies @code{THEN} is simple:
2622: @example
1.21 crook 2623: : ENDIF POSTPONE THEN ; immediate
1.1 anton 2624: @end example
2625:
2626: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
2627: (adv.)} has the following meanings:
2628: @quotation
2629: ... 2b: following next after in order ... 3d: as a necessary consequence
2630: (if you were there, then you saw them).
2631: @end quotation
2632: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
2633: and many other programming languages has the meaning 3d.]
2634:
1.21 crook 2635: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 2636: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 ! crook 2637: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 2638: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
2639: @file{compat/control.fs}.
2640:
2641: @cindex @code{CASE} control structure
2642: @example
2643: @var{n}
2644: CASE
2645: @var{n1} OF @var{code1} ENDOF
2646: @var{n2} OF @var{code2} ENDOF
2647: @dots{}
2648: ENDCASE
2649: @end example
2650:
2651: Executes the first @var{codei}, where the @var{ni} is equal to
2652: @var{n}. A default case can be added by simply writing the code after
2653: the last @code{ENDOF}. It may use @var{n}, which is on top of the stack,
2654: but must not consume it.
2655:
2656: @node Simple Loops, Counted Loops, Selection, Control Structures
2657: @subsection Simple Loops
2658: @cindex simple loops
2659: @cindex loops without count
2660:
2661: @cindex @code{WHILE} loop
2662: @example
2663: BEGIN
2664: @var{code1}
2665: @var{flag}
2666: WHILE
2667: @var{code2}
2668: REPEAT
2669: @end example
2670:
2671: @var{code1} is executed and @var{flag} is computed. If it is true,
2672: @var{code2} is executed and the loop is restarted; If @var{flag} is
2673: false, execution continues after the @code{REPEAT}.
2674:
2675: @cindex @code{UNTIL} loop
2676: @example
2677: BEGIN
2678: @var{code}
2679: @var{flag}
2680: UNTIL
2681: @end example
2682:
2683: @var{code} is executed. The loop is restarted if @code{flag} is false.
2684:
2685: @cindex endless loop
2686: @cindex loops, endless
2687: @example
2688: BEGIN
2689: @var{code}
2690: AGAIN
2691: @end example
2692:
2693: This is an endless loop.
2694:
2695: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
2696: @subsection Counted Loops
2697: @cindex counted loops
2698: @cindex loops, counted
2699: @cindex @code{DO} loops
2700:
2701: The basic counted loop is:
2702: @example
2703: @var{limit} @var{start}
2704: ?DO
2705: @var{body}
2706: LOOP
2707: @end example
2708:
2709: This performs one iteration for every integer, starting from @var{start}
1.21 crook 2710: and up to, but excluding @var{limit}. The counter, or @var{index}, can be
2711: accessed with @code{i}. For example, the loop:
1.1 anton 2712: @example
2713: 10 0 ?DO
2714: i .
2715: LOOP
2716: @end example
1.21 crook 2717: @noindent
2718: prints @code{0 1 2 3 4 5 6 7 8 9}
2719:
1.1 anton 2720: The index of the innermost loop can be accessed with @code{i}, the index
2721: of the next loop with @code{j}, and the index of the third loop with
2722: @code{k}.
2723:
2724: doc-i
2725: doc-j
2726: doc-k
2727:
2728: The loop control data are kept on the return stack, so there are some
1.21 crook 2729: restrictions on mixing return stack accesses and counted loop words. In
2730: particuler, if you put values on the return stack outside the loop, you
2731: cannot read them inside the loop@footnote{well, not in a way that is
2732: portable.}. If you put values on the return stack within a loop, you
2733: have to remove them before the end of the loop and before accessing the
2734: index of the loop.
1.1 anton 2735:
2736: There are several variations on the counted loop:
2737:
1.21 crook 2738: @itemize @bullet
2739: @item
2740: @code{LEAVE} leaves the innermost counted loop immediately; execution
2741: continues after the associated @code{LOOP} or @code{NEXT}. For example:
2742:
2743: @example
2744: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
2745: @end example
2746: prints @code{0 1 2 3}
2747:
1.1 anton 2748:
1.21 crook 2749: @item
2750: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
2751: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
2752: return stack so @code{EXIT} can get to its return address. For example:
2753:
2754: @example
2755: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
2756: @end example
2757: prints @code{0 1 2 3}
2758:
2759:
2760: @item
1.1 anton 2761: If @var{start} is greater than @var{limit}, a @code{?DO} loop is entered
2762: (and @code{LOOP} iterates until they become equal by wrap-around
2763: arithmetic). This behaviour is usually not what you want. Therefore,
2764: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
2765: @code{?DO}), which do not enter the loop if @var{start} is greater than
2766: @var{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
2767: unsigned loop parameters.
2768:
1.21 crook 2769: @item
2770: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
2771: the loop, independent of the loop parameters. Do not use @code{DO}, even
2772: if you know that the loop is entered in any case. Such knowledge tends
2773: to become invalid during maintenance of a program, and then the
2774: @code{DO} will make trouble.
2775:
2776: @item
1.1 anton 2777: @code{LOOP} can be replaced with @code{@var{n} +LOOP}; this updates the
2778: index by @var{n} instead of by 1. The loop is terminated when the border
2779: between @var{limit-1} and @var{limit} is crossed. E.g.:
2780:
1.21 crook 2781: @example
2782: 4 0 +DO i . 2 +LOOP
2783: @end example
2784: @noindent
2785: prints @code{0 2}
2786:
2787: @example
2788: 4 1 +DO i . 2 +LOOP
2789: @end example
2790: @noindent
2791: prints @code{1 3}
1.1 anton 2792:
2793:
2794: @cindex negative increment for counted loops
2795: @cindex counted loops with negative increment
2796: The behaviour of @code{@var{n} +LOOP} is peculiar when @var{n} is negative:
2797:
1.21 crook 2798: @example
2799: -1 0 ?DO i . -1 +LOOP
2800: @end example
2801: @noindent
2802: prints @code{0 -1}
1.1 anton 2803:
1.21 crook 2804: @example
2805: 0 0 ?DO i . -1 +LOOP
2806: @end example
2807: prints nothing.
1.1 anton 2808:
2809: Therefore we recommend avoiding @code{@var{n} +LOOP} with negative
2810: @var{n}. One alternative is @code{@var{u} -LOOP}, which reduces the
2811: index by @var{u} each iteration. The loop is terminated when the border
2812: between @var{limit+1} and @var{limit} is crossed. Gforth also provides
2813: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
2814:
1.21 crook 2815: @example
2816: -2 0 -DO i . 1 -LOOP
2817: @end example
2818: @noindent
2819: prints @code{0 -1}
1.1 anton 2820:
1.21 crook 2821: @example
2822: -1 0 -DO i . 1 -LOOP
2823: @end example
2824: @noindent
2825: prints @code{0}
2826:
2827: @example
2828: 0 0 -DO i . 1 -LOOP
2829: @end example
2830: @noindent
2831: prints nothing.
1.1 anton 2832:
1.21 crook 2833: @end itemize
1.1 anton 2834:
2835: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 ! crook 2836: @code{-LOOP} are not defined in ANS Forth. However, an implementation
! 2837: for these words that uses only standard words is provided in
! 2838: @file{compat/loops.fs}.
1.1 anton 2839:
2840:
2841: @cindex @code{FOR} loops
1.26 ! crook 2842: Another counted loop is:
1.1 anton 2843: @example
2844: @var{n}
2845: FOR
2846: @var{body}
2847: NEXT
2848: @end example
2849: This is the preferred loop of native code compiler writers who are too
1.26 ! crook 2850: lazy to optimize @code{?DO} loops properly. This loop structure is not
! 2851: defined in ANS Forth. In Gforth, this loop iterates @var{n+1} times;
! 2852: @code{i} produces values starting with @var{n} and ending with 0. Other
! 2853: Forth systems may behave differently, even if they support @code{FOR}
! 2854: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 2855:
2856: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
2857: @subsection Arbitrary control structures
2858: @cindex control structures, user-defined
2859:
2860: @cindex control-flow stack
2861: ANS Forth permits and supports using control structures in a non-nested
2862: way. Information about incomplete control structures is stored on the
2863: control-flow stack. This stack may be implemented on the Forth data
2864: stack, and this is what we have done in Gforth.
2865:
2866: @cindex @code{orig}, control-flow stack item
2867: @cindex @code{dest}, control-flow stack item
2868: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
2869: entry represents a backward branch target. A few words are the basis for
2870: building any control structure possible (except control structures that
2871: need storage, like calls, coroutines, and backtracking).
2872:
2873: doc-if
2874: doc-ahead
2875: doc-then
2876: doc-begin
2877: doc-until
2878: doc-again
2879: doc-cs-pick
2880: doc-cs-roll
2881:
1.21 crook 2882: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
2883: manipulate the control-flow stack in a portable way. Without them, you
2884: would need to know how many stack items are occupied by a control-flow
2885: entry (many systems use one cell. In Gforth they currently take three,
2886: but this may change in the future).
2887:
1.1 anton 2888: Some standard control structure words are built from these words:
2889:
2890: doc-else
2891: doc-while
2892: doc-repeat
2893:
2894: Gforth adds some more control-structure words:
2895:
2896: doc-endif
2897: doc-?dup-if
2898: doc-?dup-0=-if
2899:
2900: Counted loop words constitute a separate group of words:
2901:
2902: doc-?do
2903: doc-+do
2904: doc-u+do
2905: doc--do
2906: doc-u-do
2907: doc-do
2908: doc-for
2909: doc-loop
2910: doc-+loop
2911: doc--loop
2912: doc-next
2913: doc-leave
2914: doc-?leave
2915: doc-unloop
2916: doc-done
2917:
1.21 crook 2918: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
2919: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 2920: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
2921: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
2922: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
2923: resolved (by using one of the loop-ending words or @code{DONE}).
2924:
1.26 ! crook 2925: Another group of control structure words are:
1.1 anton 2926:
2927: doc-case
2928: doc-endcase
2929: doc-of
2930: doc-endof
2931:
1.21 crook 2932: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
2933: @code{CS-ROLL}.
1.1 anton 2934:
2935: @subsubsection Programming Style
2936:
2937: In order to ensure readability we recommend that you do not create
2938: arbitrary control structures directly, but define new control structure
2939: words for the control structure you want and use these words in your
1.26 ! crook 2940: program. For example, instead of writing:
1.1 anton 2941:
2942: @example
1.26 ! crook 2943: BEGIN
1.1 anton 2944: ...
1.26 ! crook 2945: IF [ 1 CS-ROLL ]
1.1 anton 2946: ...
1.26 ! crook 2947: AGAIN THEN
1.1 anton 2948: @end example
2949:
1.21 crook 2950: @noindent
1.1 anton 2951: we recommend defining control structure words, e.g.,
2952:
2953: @example
1.26 ! crook 2954: : WHILE ( DEST -- ORIG DEST )
! 2955: POSTPONE IF
! 2956: 1 CS-ROLL ; immediate
! 2957:
! 2958: : REPEAT ( orig dest -- )
! 2959: POSTPONE AGAIN
! 2960: POSTPONE THEN ; immediate
1.1 anton 2961: @end example
2962:
1.21 crook 2963: @noindent
1.1 anton 2964: and then using these to create the control structure:
2965:
2966: @example
1.26 ! crook 2967: BEGIN
1.1 anton 2968: ...
1.26 ! crook 2969: WHILE
1.1 anton 2970: ...
1.26 ! crook 2971: REPEAT
1.1 anton 2972: @end example
2973:
2974: That's much easier to read, isn't it? Of course, @code{REPEAT} and
2975: @code{WHILE} are predefined, so in this example it would not be
2976: necessary to define them.
2977:
2978: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
2979: @subsection Calls and returns
2980: @cindex calling a definition
2981: @cindex returning from a definition
2982:
1.3 anton 2983: @cindex recursive definitions
2984: A definition can be called simply be writing the name of the definition
1.26 ! crook 2985: to be called. Normally a definition is invisible during its own
1.3 anton 2986: definition. If you want to write a directly recursive definition, you
1.26 ! crook 2987: can use @code{recursive} to make the current definition visible, or
! 2988: @code{recurse} to call the current definition directly.
1.3 anton 2989:
2990: doc-recursive
2991: doc-recurse
2992:
1.21 crook 2993: @comment TODO add example of the two recursion methods
1.12 anton 2994: @quotation
2995: @progstyle
2996: I prefer using @code{recursive} to @code{recurse}, because calling the
2997: definition by name is more descriptive (if the name is well-chosen) than
2998: the somewhat cryptic @code{recurse}. E.g., in a quicksort
2999: implementation, it is much better to read (and think) ``now sort the
3000: partitions'' than to read ``now do a recursive call''.
3001: @end quotation
1.3 anton 3002:
1.21 crook 3003: @comment TODO maybe move deferred words to Defining Words section and x-ref
3004: @comment from here.. that is where these two are glossed.
3005:
1.3 anton 3006: For mutual recursion, use @code{defer}red words, like this:
3007:
3008: @example
3009: defer foo
3010:
3011: : bar ( ... -- ... )
3012: ... foo ... ;
3013:
3014: :noname ( ... -- ... )
3015: ... bar ... ;
3016: IS foo
3017: @end example
3018:
1.26 ! crook 3019: The current definition returns control to the calling definition when
! 3020: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 3021:
3022: doc-exit
3023: doc-;s
3024:
3025: @node Exception Handling, , Calls and returns, Control Structures
3026: @subsection Exception Handling
1.26 ! crook 3027: @cindex exceptions
1.1 anton 3028:
1.26 ! crook 3029: If your program detects a fatal error condition, the simplest action
! 3030: that it can take is to @code{quit}. This resets the return stack and
! 3031: restarts the text interpreter, but does not print any error message.
1.21 crook 3032:
1.26 ! crook 3033: The next stage in severity is to execute @code{abort}, which has the
! 3034: same effect as @code{quit}, with the addition that it resets the data
! 3035: stack.
1.1 anton 3036:
1.26 ! crook 3037: A slightly more sophisticated approach is use use @code{abort"}, which
! 3038: compiles a string to be used as an error message and does a conditional
! 3039: @code{abort} at run-time. For example:
1.1 anton 3040:
1.26 ! crook 3041: @example
! 3042: @kbd{: checker abort" That flag was true" ." A false flag" ;<return>} ok
! 3043: @kbd{0 checker<return>} A false flag ok
! 3044: @kbd{1 checker<return>}
! 3045: :1: That flag was true
! 3046: 1 checker
! 3047: ^^^^^^^
! 3048: $400D1648 throw
! 3049: $400E4660
! 3050: @end example
1.1 anton 3051:
1.26 ! crook 3052: These simple techniques allow a program to react to a fatal error
! 3053: condition, but they are not exactly user-friendly. The ANS Forth
! 3054: Exception word set provides the pair of words @code{throw} and
! 3055: @code{catch}, which can be used to provide sophisticated error-handling.
1.1 anton 3056:
1.26 ! crook 3057: @code{catch} has a similar behaviour to @code{execute}, in that it takes
! 3058: an @var{xt} as a parameter and starts execution of the xt. However,
! 3059: before passing control to the xt, @code{catch} pushes an
! 3060: @var{exception frame} onto the @var{exception stack}. This exception
! 3061: frame is used to restore the system to a known state if a detected error
! 3062: occurs during the execution of the xt. A typical way to use @code{catch}
! 3063: would be:
1.1 anton 3064:
1.26 ! crook 3065: @example
! 3066: ... ['] foo catch IF ...
! 3067: @end example
1.1 anton 3068:
1.26 ! crook 3069: Whilst @code{foo} executes, it can call other words to any level of
! 3070: nesting, as usual. If @code{foo} (and all the words that it calls)
! 3071: execute successfully, control will ultimately passes to the word following
! 3072: the @code{catch}, and there will be a @code{true} flag (0) at
! 3073: TOS. However, if any word detects an error, it can terminate the
! 3074: execution of @code{foo} by pushing an error code onto the stack and then
! 3075: performing a @code{throw}. The execution of @code{throw} will pass
! 3076: control to the word following the @code{catch}, but this time the TOS
! 3077: will hold the error code. Therefore, the @code{IF} in the example
! 3078: can be used to determine whether @code{foo} executed successfully.
1.1 anton 3079:
1.26 ! crook 3080: This simple example shows how you can use @code{throw} and @code{catch}
! 3081: to ``take over'' exception handling from the system:
1.1 anton 3082: @example
1.26 ! crook 3083: : my-div ['] / catch if ." DIVIDE ERROR" else ." OK.. " . then ;
1.1 anton 3084: @end example
3085:
1.26 ! crook 3086: The next example is more sophisticated and shows a multi-level
! 3087: @code{throw} and @code{catch}. To understand this example, start at the
! 3088: definition of @code{top-level} and work backwards:
! 3089:
1.1 anton 3090: @example
1.26 ! crook 3091: : lowest-level ( -- c )
! 3092: key dup 27 = if
! 3093: 1 throw \ ESCAPE key pressed
! 3094: else
! 3095: ." lowest-level successfull" CR
! 3096: then
! 3097: ;
! 3098:
! 3099: : lower-level ( -- c )
! 3100: lowest-level
! 3101: \ at this level consider a CTRL-U to be a fatal error
! 3102: dup 21 = if \ CTRL-U
! 3103: 2 throw
! 3104: else
! 3105: ." lower-level successfull" CR
! 3106: then
! 3107: ;
! 3108:
! 3109: : low-level ( -- c )
! 3110: ['] lower-level catch
! 3111: ?dup if
! 3112: \ error occurred - do we recognise it?
! 3113: dup 1 = if
! 3114: \ ESCAPE key pressed.. pretend it was an E
! 3115: [char] E
! 3116: else throw \ propogate the error upwards
! 3117: then
! 3118: then
! 3119: ." low-level successfull" CR
! 3120: ;
! 3121:
! 3122: : top-level ( -- )
! 3123: CR ['] low-level catch \ CATCH is used like EXECUTE
! 3124: ?dup if \ error occurred..
! 3125: ." Error " . ." occurred - contact your supplier"
! 3126: else
! 3127: ." The '" emit ." ' key was pressed" CR
! 3128: then
! 3129: ;
1.1 anton 3130: @end example
3131:
1.26 ! crook 3132: The ANS Forth document assigns @code{throw} codes thus:
1.1 anton 3133:
1.26 ! crook 3134: @itemize @bullet
! 3135: @item
! 3136: codes in the range -1 -- -255 are reserved to be assigned by the
! 3137: Standard. Assignments for codes in the range -1 -- -58 are currently
! 3138: documented in the Standard. In particular, @code{-1 throw} is equivalent
! 3139: to @code{abort} and @code{-2 throw} is equivalent to @code{abort"}.
! 3140: @item
! 3141: codes in the range -256 -- -4095 are reserved to be assigned by the system.
! 3142: @item
! 3143: all other codes may be assigned by programs.
! 3144: @end itemize
1.1 anton 3145:
1.26 ! crook 3146: Gforth provides the word @code{exception} as a mechanism for assigning
! 3147: system throw codes to applications. This allows multiple applications to
! 3148: co-exist in memory without any clash of @code{throw} codes. A definition
! 3149: of @code{exception} in ANS Forth is provided in
! 3150: @file{compat/exception.fs}.
1.1 anton 3151:
3152:
1.26 ! crook 3153: doc-quit
! 3154: doc-abort
! 3155: doc-abort"
1.1 anton 3156:
1.26 ! crook 3157: doc-catch
! 3158: doc-throw
! 3159: doc---exception-exception
1.1 anton 3160:
3161:
1.26 ! crook 3162: @c -------------------------------------------------------------
! 3163: @node Defining Words, The Text Interpreter, Control Structures, Words
! 3164: @section Defining Words
! 3165: @cindex defining words
1.1 anton 3166:
1.26 ! crook 3167: @comment TODO much more intro material here. 3 classes: colon defn, variables/constants
! 3168: @comment values, user-defined defining words.
1.1 anton 3169:
3170: @menu
1.26 ! crook 3171: * Simple Defining Words::
! 3172: * Colon Definitions::
! 3173: * User-defined Defining Words::
! 3174: * Supplying names::
! 3175: * Interpretation and Compilation Semantics::
1.1 anton 3176: @end menu
3177:
1.26 ! crook 3178: @node Simple Defining Words, Colon Definitions, Defining Words, Defining Words
! 3179: @subsection Simple Defining Words
! 3180: @cindex simple defining words
! 3181: @cindex defining words, simple
! 3182:
! 3183: doc-constant
! 3184: doc-2constant
! 3185: doc-fconstant
! 3186: doc-variable
! 3187: doc-2variable
! 3188: doc-fvariable
! 3189: doc-create
! 3190: doc-user
! 3191: doc-value
! 3192: doc-to
! 3193: doc-defer
! 3194: doc-is
! 3195:
! 3196: Definitions in ANS Forth for @code{defer}, @code{<is>} and
! 3197: @code{[is]} are provided in @file{compat/defer.fs}.
! 3198: @comment TODO - what do the two "is" words do?
1.1 anton 3199:
1.26 ! crook 3200: @node Colon Definitions, User-defined Defining Words, Simple Defining Words, Defining Words
! 3201: @subsection Colon Definitions
! 3202: @cindex colon definitions
1.1 anton 3203:
1.26 ! crook 3204: @example
! 3205: : name ( ... -- ... )
! 3206: word1 word2 word3 ;
! 3207: @end example
1.1 anton 3208:
1.26 ! crook 3209: creates a word called @code{name}, that, upon execution, executes
! 3210: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.1 anton 3211:
1.26 ! crook 3212: The explanation above is somewhat superficial. @xref{Interpretation and
! 3213: Compilation Semantics} for an in-depth discussion of some of the issues
! 3214: involved.
! 3215:
! 3216: doc-:
! 3217: doc-;
1.1 anton 3218:
1.26 ! crook 3219: @node User-defined Defining Words, Supplying names, Colon Definitions, Defining Words
! 3220: @subsection User-defined Defining Words
! 3221: @cindex user-defined defining words
! 3222: @cindex defining words, user-defined
1.1 anton 3223:
1.26 ! crook 3224: You can create new defining words simply by wrapping defining-time code
! 3225: around existing defining words and putting the sequence in a colon
! 3226: definition.
1.1 anton 3227:
1.26 ! crook 3228: @comment TODO example
1.1 anton 3229:
1.26 ! crook 3230: @cindex @code{CREATE} ... @code{DOES>}
! 3231: If you want the words defined with your defining words to behave
! 3232: differently from words defined with standard defining words, you can
! 3233: write your defining word like this:
1.1 anton 3234:
3235: @example
1.26 ! crook 3236: : def-word ( "name" -- )
! 3237: Create @var{code1}
! 3238: DOES> ( ... -- ... )
! 3239: @var{code2} ;
! 3240:
! 3241: def-word name
1.1 anton 3242: @end example
3243:
1.26 ! crook 3244: Technically, this fragment defines a defining word @code{def-word}, and
! 3245: a word @code{name}; when you execute @code{name}, the address of the
! 3246: body of @code{name} is put on the data stack and @var{code2} is executed
! 3247: (the address of the body of @code{name} is the address @code{HERE}
! 3248: returns immediately after the @code{CREATE}). The word @code{name} is
! 3249: sometimes called a @var{child} of @code{def-word}.
1.1 anton 3250:
1.26 ! crook 3251: In other words, if you make the following definitions:
1.1 anton 3252:
3253: @example
1.26 ! crook 3254: : def-word1 ( "name" -- )
! 3255: Create @var{code1} ;
! 3256:
! 3257: : action1 ( ... -- ... )
! 3258: @var{code2} ;
! 3259:
! 3260: def-word name1
1.1 anton 3261: @end example
3262:
1.26 ! crook 3263: Using @code{name1 action1} is equivalent to using @code{name}.
! 3264:
! 3265: The classic example is that you can define @code{Constant} in this way:
! 3266:
1.1 anton 3267: @example
1.26 ! crook 3268: : constant ( w "name" -- )
! 3269: create ,
! 3270: DOES> ( -- w )
! 3271: @@ ;
1.1 anton 3272: @end example
3273:
1.26 ! crook 3274: @comment that is the classic example.. maybe it should be earlier. There
! 3275: @comment is a beautiful description of how this works and what it does in
! 3276: @comment the Forthwrite 100th edition.
! 3277:
! 3278: When you create a constant with @code{5 constant five}, first a new word
! 3279: @code{five} is created, then the value 5 is laid down in the body of
! 3280: @code{five} with @code{,}. When @code{five} is invoked, the address of
! 3281: the body is put on the stack, and @code{@@} retrieves the value 5.
! 3282:
! 3283: @cindex stack effect of @code{DOES>}-parts
! 3284: @cindex @code{DOES>}-parts, stack effect
! 3285: In the example above the stack comment after the @code{DOES>} specifies
! 3286: the stack effect of the defined words, not the stack effect of the
! 3287: following code (the following code expects the address of the body on
! 3288: the top of stack, which is not reflected in the stack comment). This is
! 3289: the convention that I use and recommend (it clashes a bit with using
! 3290: locals declarations for stack effect specification, though).
1.1 anton 3291:
1.26 ! crook 3292: @subsubsection Applications of @code{CREATE..DOES>}
! 3293: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 3294:
1.26 ! crook 3295: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 3296:
1.26 ! crook 3297: @cindex factoring similar colon definitions
! 3298: When you see a sequence of code occurring several times, and you can
! 3299: identify a meaning, you will factor it out as a colon definition. When
! 3300: you see similar colon definitions, you can factor them using
! 3301: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
! 3302: that look very similar:
1.1 anton 3303: @example
1.26 ! crook 3304: : ori, ( reg-target reg-source n -- )
! 3305: 0 asm-reg-reg-imm ;
! 3306: : andi, ( reg-target reg-source n -- )
! 3307: 1 asm-reg-reg-imm ;
1.1 anton 3308: @end example
3309:
1.26 ! crook 3310: @noindent
! 3311: This could be factored with:
! 3312: @example
! 3313: : reg-reg-imm ( op-code -- )
! 3314: CREATE ,
! 3315: DOES> ( reg-target reg-source n -- )
! 3316: @@ asm-reg-reg-imm ;
! 3317:
! 3318: 0 reg-reg-imm ori,
! 3319: 1 reg-reg-imm andi,
! 3320: @end example
1.1 anton 3321:
1.26 ! crook 3322: @cindex currying
! 3323: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
! 3324: supply a part of the parameters for a word (known as @dfn{currying} in
! 3325: the functional language community). E.g., @code{+} needs two
! 3326: parameters. Creating versions of @code{+} with one parameter fixed can
! 3327: be done like this:
1.1 anton 3328: @example
1.26 ! crook 3329: : curry+ ( n1 -- )
! 3330: CREATE ,
! 3331: DOES> ( n2 -- n1+n2 )
! 3332: @@ + ;
! 3333:
! 3334: 3 curry+ 3+
! 3335: -2 curry+ 2-
1.1 anton 3336: @end example
3337:
1.26 ! crook 3338: @subsubsection The gory details of @code{CREATE..DOES>}
! 3339: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 3340:
1.26 ! crook 3341: doc-does>
1.1 anton 3342:
1.26 ! crook 3343: @cindex @code{DOES>} in a separate definition
! 3344: This means that you need not use @code{CREATE} and @code{DOES>} in the
! 3345: same definition; you can put the @code{DOES>}-part in a separate
! 3346: definition. This allows us to, e.g., select among different DOES>-parts:
! 3347: @example
! 3348: : does1
! 3349: DOES> ( ... -- ... )
! 3350: ... ;
1.1 anton 3351:
1.26 ! crook 3352: : does2
! 3353: DOES> ( ... -- ... )
! 3354: ... ;
1.1 anton 3355:
1.26 ! crook 3356: : def-word ( ... -- ... )
! 3357: create ...
! 3358: IF
! 3359: does1
! 3360: ELSE
! 3361: does2
! 3362: ENDIF ;
! 3363: @end example
1.1 anton 3364:
1.26 ! crook 3365: In this example, the selection of whether to use @code{does1} or
! 3366: @code{does2} is made at compile-time; at the time that the child word is
! 3367: @code{Create}d.
1.1 anton 3368:
1.26 ! crook 3369: @cindex @code{DOES>} in interpretation state
! 3370: In a standard program you can apply a @code{DOES>}-part only if the last
! 3371: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
! 3372: will override the behaviour of the last word defined in any case. In a
! 3373: standard program, you can use @code{DOES>} only in a colon
! 3374: definition. In Gforth, you can also use it in interpretation state, in a
! 3375: kind of one-shot mode; for example:
1.1 anton 3376: @example
1.26 ! crook 3377: CREATE name ( ... -- ... )
! 3378: @var{initialization}
! 3379: DOES>
! 3380: @var{code} ;
1.1 anton 3381: @end example
3382:
1.26 ! crook 3383: @noindent
! 3384: is equivalent to the standard:
1.1 anton 3385: @example
1.26 ! crook 3386: :noname
! 3387: DOES>
! 3388: @var{code} ;
! 3389: CREATE name EXECUTE ( ... -- ... )
! 3390: @var{initialization}
1.1 anton 3391: @end example
3392:
1.26 ! crook 3393: You can get the address of the body of a word with:
! 3394:
! 3395: doc->body
1.1 anton 3396:
1.26 ! crook 3397: @node Supplying names, Interpretation and Compilation Semantics, User-defined Defining Words, Defining Words
! 3398: @subsection Supplying names for the defined words
! 3399: @cindex names for defined words
! 3400: @cindex defining words, name parameter
1.1 anton 3401:
1.26 ! crook 3402: @cindex defining words, name given in a string
! 3403: By default, defining words take the names for the defined words from the
! 3404: input stream. Sometimes you want to supply the name from a string. You
! 3405: can do this with:
1.1 anton 3406:
1.26 ! crook 3407: doc-nextname
1.1 anton 3408:
1.26 ! crook 3409: For example:
1.1 anton 3410:
1.26 ! crook 3411: @example
! 3412: s" foo" nextname create
! 3413: @end example
! 3414: @noindent
! 3415: is equivalent to:
! 3416: @example
! 3417: create foo
! 3418: @end example
1.1 anton 3419:
1.26 ! crook 3420: @cindex defining words without name
! 3421: Sometimes you want to define an @var{anonymous word}; a word without a
! 3422: name. You can do this with:
1.1 anton 3423:
1.26 ! crook 3424: doc-:noname
1.1 anton 3425:
1.26 ! crook 3426: This leaves the execution token for the word on the stack after the
! 3427: closing @code{;}. Here's an example in which a deferred word is
! 3428: initialised with an @code{xt} from an anonymous colon definition:
! 3429: @example
! 3430: Defer deferred
! 3431: :noname ( ... -- ... )
! 3432: ... ;
! 3433: IS deferred
! 3434: @end example
1.1 anton 3435:
1.26 ! crook 3436: Gforth provides an alternative way of doing this, using two separate
! 3437: words:
1.1 anton 3438:
1.26 ! crook 3439: doc-noname
! 3440: @cindex execution token of last defined word
! 3441: doc-lastxt
1.1 anton 3442:
1.26 ! crook 3443: The previous example can be rewritten using @code{noname} and
! 3444: @code{lastxt}:
1.1 anton 3445:
1.26 ! crook 3446: @example
! 3447: Defer deferred
! 3448: noname : ( ... -- ... )
! 3449: ... ;
! 3450: lastxt IS deferred
! 3451: @end example
1.1 anton 3452:
1.26 ! crook 3453: @code{lastxt} also works when the last word was not defined as
! 3454: @code{noname}.
1.1 anton 3455:
3456:
1.26 ! crook 3457: @node Interpretation and Compilation Semantics, , Supplying names, Defining Words
! 3458: @subsection Interpretation and Compilation Semantics
! 3459: @cindex semantics, interpretation and compilation
1.1 anton 3460:
1.26 ! crook 3461: @cindex interpretation semantics
! 3462: The @dfn{interpretation semantics} of a word are what the text
! 3463: interpreter does when it encounters the word in interpret state. It also
! 3464: appears in some other contexts, e.g., the execution token returned by
! 3465: @code{' @var{word}} identifies the interpretation semantics of
! 3466: @var{word} (in other words, @code{' @var{word} execute} is equivalent to
! 3467: interpret-state text interpretation of @code{@var{word}}).
1.1 anton 3468:
1.26 ! crook 3469: @cindex compilation semantics
! 3470: The @dfn{compilation semantics} of a word are what the text interpreter
! 3471: does when it encounters the word in compile state. It also appears in
! 3472: other contexts, e.g, @code{POSTPONE @var{word}} compiles@footnote{In
! 3473: standard terminology, ``appends to the current definition''.} the
! 3474: compilation semantics of @var{word}.
1.1 anton 3475:
1.26 ! crook 3476: @cindex execution semantics
! 3477: The standard also talks about @dfn{execution semantics}. They are used
! 3478: only for defining the interpretation and compilation semantics of many
! 3479: words. By default, the interpretation semantics of a word are to
! 3480: @code{execute} its execution semantics, and the compilation semantics of
! 3481: a word are to @code{compile,} its execution semantics.@footnote{In
! 3482: standard terminology: The default interpretation semantics are its
! 3483: execution semantics; the default compilation semantics are to append its
! 3484: execution semantics to the execution semantics of the current
! 3485: definition.}
! 3486:
! 3487: @comment TODO expand, make it co-operate with new sections on text interpreter.
! 3488:
! 3489: @cindex immediate words
! 3490: @cindex compile-only words
! 3491: You can change the semantics of the most-recently defined word:
! 3492:
! 3493: doc-immediate
! 3494: doc-compile-only
! 3495: doc-restrict
! 3496:
! 3497: Note that ticking (@code{'}) a compile-only word gives an error
! 3498: (``Interpreting a compile-only word'').
1.1 anton 3499:
1.26 ! crook 3500: Gforth also allows you to define words with arbitrary combinations of
! 3501: interpretation and compilation semantics.
1.1 anton 3502:
1.26 ! crook 3503: doc-interpret/compile:
1.1 anton 3504:
1.26 ! crook 3505: This feature was introduced for implementing @code{TO} and @code{S"}. I
! 3506: recommend that you do not define such words, as cute as they may be:
! 3507: they make it hard to get at both parts of the word in some contexts.
! 3508: E.g., assume you want to get an execution token for the compilation
! 3509: part. Instead, define two words, one that embodies the interpretation
! 3510: part, and one that embodies the compilation part. Once you have done
! 3511: that, you can define a combined word with @code{interpret/compile:} for
! 3512: the convenience of your users.
1.1 anton 3513:
1.26 ! crook 3514: You might try to use this feature to provide an optimizing
! 3515: implementation of the default compilation semantics of a word. For
! 3516: example, by defining:
1.1 anton 3517: @example
1.26 ! crook 3518: :noname
! 3519: foo bar ;
! 3520: :noname
! 3521: POSTPONE foo POSTPONE bar ;
! 3522: interpret/compile: foobar
1.1 anton 3523: @end example
1.26 ! crook 3524:
1.23 crook 3525: @noindent
1.26 ! crook 3526: as an optimizing version of:
! 3527:
1.1 anton 3528: @example
1.26 ! crook 3529: : foobar
! 3530: foo bar ;
1.1 anton 3531: @end example
3532:
1.26 ! crook 3533: Unfortunately, this does not work correctly with @code{[compile]},
! 3534: because @code{[compile]} assumes that the compilation semantics of all
! 3535: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
! 3536: foobar} would compile the compilation semantics for the optimizing
! 3537: @code{foobar}, whereas it would compile the interpretation semantics for
! 3538: the non-optimizing @code{foobar}.
1.1 anton 3539:
1.26 ! crook 3540: @cindex state-smart words (are a bad idea)
! 3541: Some people try to use @var{state-smart} words to emulate the feature provided
! 3542: by @code{interpret/compile:} (words are state-smart if they check
! 3543: @code{STATE} during execution). E.g., they would try to code
! 3544: @code{foobar} like this:
1.1 anton 3545:
1.26 ! crook 3546: @example
! 3547: : foobar
! 3548: STATE @@
! 3549: IF ( compilation state )
! 3550: POSTPONE foo POSTPONE bar
! 3551: ELSE
! 3552: foo bar
! 3553: ENDIF ; immediate
! 3554: @end example
1.1 anton 3555:
1.26 ! crook 3556: Although this works if @code{foobar} is only processed by the text
! 3557: interpreter, it does not work in other contexts (like @code{'} or
! 3558: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
! 3559: for a state-smart word, not for the interpretation semantics of the
! 3560: original @code{foobar}; when you execute this execution token (directly
! 3561: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
! 3562: state, the result will not be what you expected (i.e., it will not
! 3563: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
! 3564: write them@footnote{For a more detailed discussion of this topic, see
! 3565: @cite{@code{State}-smartness -- Why it is Evil and How to Exorcise it} by Anton
! 3566: Ertl; presented at EuroForth '98 and available from
! 3567: @url{http://www.complang.tuwien.ac.at/papers/}}!
1.1 anton 3568:
1.26 ! crook 3569: @cindex defining words with arbitrary semantics combinations
! 3570: It is also possible to write defining words that define words with
! 3571: arbitrary combinations of interpretation and compilation semantics. In
! 3572: general, they look like this:
1.1 anton 3573:
1.26 ! crook 3574: @example
! 3575: : def-word
! 3576: create-interpret/compile
! 3577: @var{code1}
! 3578: interpretation>
! 3579: @var{code2}
! 3580: <interpretation
! 3581: compilation>
! 3582: @var{code3}
! 3583: <compilation ;
! 3584: @end example
1.1 anton 3585:
1.26 ! crook 3586: For a @var{word} defined with @code{def-word}, the interpretation
! 3587: semantics are to push the address of the body of @var{word} and perform
! 3588: @var{code2}, and the compilation semantics are to push the address of
! 3589: the body of @var{word} and perform @var{code3}. E.g., @code{constant}
! 3590: can also be defined like this (except that the defined constants don't
! 3591: behave correctly when @code{[compile]}d):
1.1 anton 3592:
1.26 ! crook 3593: @example
! 3594: : constant ( n "name" -- )
! 3595: create-interpret/compile
! 3596: ,
! 3597: interpretation> ( -- n )
! 3598: @@
! 3599: <interpretation
! 3600: compilation> ( compilation. -- ; run-time. -- n )
! 3601: @@ postpone literal
! 3602: <compilation ;
! 3603: @end example
1.1 anton 3604:
1.26 ! crook 3605: doc-create-interpret/compile
! 3606: doc-interpretation>
! 3607: doc-<interpretation
! 3608: doc-compilation>
! 3609: doc-<compilation
1.1 anton 3610:
1.26 ! crook 3611: Note that words defined with @code{interpret/compile:} and
! 3612: @code{create-interpret/compile} have an extended header structure that
! 3613: differs from other words; however, unless you try to access them with
! 3614: plain address arithmetic, you should not notice this. Words for
! 3615: accessing the header structure usually know how to deal with this; e.g.,
! 3616: @code{' word >body} also gives you the body of a word created with
! 3617: @code{create-interpret/compile}.
1.1 anton 3618:
1.26 ! crook 3619: @c ----------------------------------------------------------
! 3620: @node The Text Interpreter, Tokens for Words, Defining Words, Words
! 3621: @section The Text Interpreter
! 3622: @cindex interpreter - outer
! 3623: @cindex text interpreter
! 3624: @cindex outer interpreter
1.1 anton 3625:
1.26 ! crook 3626: Intro blah.
1.1 anton 3627:
1.26 ! crook 3628: @comment TODO
1.21 crook 3629:
1.26 ! crook 3630: doc->in
! 3631: doc-tib
! 3632: doc-#tib
! 3633: doc-span
! 3634: doc-restore-input
! 3635: doc-save-input
! 3636: doc-source
! 3637: doc-source-id
1.1 anton 3638:
3639:
1.26 ! crook 3640: @menu
! 3641: * Number Conversion::
! 3642: * Interpret/Compile states::
! 3643: * Literals::
! 3644: * Interpreter Directives::
! 3645: @end menu
1.1 anton 3646:
1.26 ! crook 3647: @comment TODO
1.1 anton 3648:
1.26 ! crook 3649: The text interpreter works on input one line at a time. Starting at
! 3650: the beginning of the line, it skips leading spaces (called
! 3651: @var{delimiters}) then parses a string (a sequence of non-space
! 3652: characters) until it either reaches a space character or it
! 3653: reaches the end of the line. Having parsed a string, it then makes two
! 3654: attempts to do something with it:
1.1 anton 3655:
1.26 ! crook 3656: * It looks the string up in a dictionary of definitions. If the string
! 3657: is found in the dictionary, the string names a @var{definition} (also
! 3658: known as a @var{word}) and the dictionary search will return an
! 3659: @var{Execution token} (xt) for the definition and some flags that show
! 3660: when the definition can be used legally. If the definition can be
! 3661: legally executed in @var{Interpret} mode then the text interpreter will
! 3662: use the xt to execute it, otherwise it will issue an error
! 3663: message. The dictionary is described in more detail in <blah>.
1.1 anton 3664:
1.26 ! crook 3665: * If the string is not found in the dictionary, the text interpreter
! 3666: attempts to treat it as a number in the current radix (base 10 after
! 3667: initial startup). If the string represents a legal number in the
! 3668: current radix, the number is pushed onto the appropriate parameter
! 3669: stack. Stacks are discussed in more detail in <blah>. Number
! 3670: conversion is described in more detail in <section about +, -
! 3671: numbers and different number formats>.
1.1 anton 3672:
1.26 ! crook 3673: If both of these attempts fail, the remainer of the input line is
! 3674: discarded and the text interpreter isses an error message. If one of
! 3675: these attempts succeeds, the text interpreter repeats the parsing
! 3676: process until the end of the line has been reached. At this point,
! 3677: it prints the status message `` ok'' and waits for more input.
1.21 crook 3678:
1.26 ! crook 3679: There are two important things to note about the behaviour of the text
! 3680: interpreter:
1.1 anton 3681:
1.26 ! crook 3682: * it processes each input string to completion before parsing
! 3683: additional characters from the input line.
1.1 anton 3684:
1.26 ! crook 3685: * it keeps track of its position in the input line using a variable
! 3686: (called >IN, pronounced ``to-in''). The value of >IN can be modified
! 3687: by the execution of definitions in the input line. This means that
! 3688: definitions can ``trick'' the text interpreter either into skipping
! 3689: sections of the input line or into parsing a section of the
! 3690: input line more than once.
1.1 anton 3691:
3692:
1.26 ! crook 3693: @node Number Conversion, Interpret/Compile states, The Text Interpreter, The Text Interpreter
! 3694: @subsection Number Conversion
! 3695: @cindex number conversion
! 3696: @cindex double-cell numbers, input format
! 3697: @cindex input format for double-cell numbers
! 3698: @cindex single-cell numbers, input format
! 3699: @cindex input format for single-cell numbers
! 3700: @cindex floating-point numbers, input format
! 3701: @cindex input format for floating-point numbers
1.1 anton 3702:
1.26 ! crook 3703: If the text interpreter fails to find a particular string in the name
! 3704: dictionary, it attempts to convert it to a number using a set of rules.
1.1 anton 3705:
1.26 ! crook 3706: Let <digit> represent any character that is a legal digit in the current
! 3707: number base (for example, 0-9 when the number base is decimal or 0-9, A-F
! 3708: when the number base is hexadecimal).
1.1 anton 3709:
1.26 ! crook 3710: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 3711:
1.26 ! crook 3712: @comment TODO need to extend the next defn to support fp format
! 3713: Let @{+ | -@} represent the optional presence of either a @code{+} or
! 3714: @code{-} character.
1.1 anton 3715:
1.26 ! crook 3716: Let * represent any number of instances of the previous character
! 3717: (including none).
1.1 anton 3718:
1.26 ! crook 3719: Let any other character represent itself.
1.1 anton 3720:
1.26 ! crook 3721: Now, the conversion rules are:
1.21 crook 3722:
1.26 ! crook 3723: @itemize @bullet
! 3724: @item
! 3725: A string of the form <digit><digit>* is treated as a single-precision
! 3726: (CELL-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
! 3727: @item
! 3728: A string of the form -<digit><digit>* is treated as a single-precision
! 3729: (CELL-sized) negative integer, and is represented using 2's-complement
! 3730: arithmetic. Examples are -45 -5681 -0
! 3731: @item
! 3732: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
! 3733: (double-CELL-sized) positive integer. Examples are 3465. 3.465 34.65
! 3734: (and note that these all represent the same number).
! 3735: @item
! 3736: A string of the form -<digit><digit>*.<digit>* is treated as a
! 3737: double-precision (double-CELL-sized) negative integer, and is
! 3738: represented using 2's-complement arithmetic. Examples are -3465. -3.465
! 3739: -34.65 (and note that these all represent the same number).
! 3740: @item
! 3741: A string of the form @{+ | -@}<decimal digit>@{.@}<decimal digit>*@{e | E@}@{+
! 3742: | -@}<decimal digit><decimal digit>* is treated as floating-point
! 3743: number. Examples are 1e0 1.e 1.e0 +1e+0 (which all represent the same
! 3744: number) +12.E-4
! 3745: @end itemize
1.1 anton 3746:
1.26 ! crook 3747: By default, the number base used for integer number conversion is given
! 3748: by the contents of a variable named @code{BASE}. Base 10 (decimal) is
! 3749: always used for floating-point number conversion.
1.1 anton 3750:
1.26 ! crook 3751: doc-base
! 3752: doc-hex
! 3753: doc-decimal
1.1 anton 3754:
1.26 ! crook 3755: @cindex '-prefix for character strings
! 3756: @cindex &-prefix for decimal numbers
! 3757: @cindex %-prefix for binary numbers
! 3758: @cindex $-prefix for hexadecimal numbers
! 3759: Gforth allows you to override the value of @code{BASE} by using a prefix
! 3760: before the first digit of an (integer) number. Four prefixes are
! 3761: supported:
1.1 anton 3762:
1.26 ! crook 3763: @itemize @bullet
! 3764: @item
! 3765: @code{&} -- decimal number
! 3766: @item
! 3767: @code{%} -- binary number
! 3768: @item
! 3769: @code{$} -- hexadecimal number
! 3770: @item
! 3771: @code{'} -- base 256 number
! 3772: @end itemize
1.1 anton 3773:
1.26 ! crook 3774: Here are some examples, with the equivalent decimal number shown after
! 3775: in braces:
1.1 anton 3776:
1.26 ! crook 3777: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
! 3778: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
! 3779: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
! 3780: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 3781:
1.26 ! crook 3782: @cindex number conversion - traps for the unwary
! 3783: Number conversion has a number of traps for the unwary:
1.1 anton 3784:
1.26 ! crook 3785: @itemize @bullet
! 3786: @item
! 3787: You cannot determine the current number base using the code sequence
! 3788: @code{BASE @@ .} -- the number base is always 10 in the current number
! 3789: base. Instead, use something like @code{BASE @@ DECIMAL DUP . BASE !}
! 3790: @item
! 3791: If the number base is set to a value greater than 14 (for example,
! 3792: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
! 3793: it to be intepreted as either a single-precision integer or a
! 3794: floating-point number (Gforth treats it as an integer). The ambiguity
! 3795: can be resolved by explicitly stating the sign of the mantissa and/or
! 3796: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
! 3797: ambiguity arises; either representation will be treated as a
! 3798: floating-point number.
! 3799: @item
! 3800: There is a word @code{bin} but it does @var{not} set the number base!
! 3801: It is used to specify file types.
! 3802: @item
! 3803: ANS Forth requires the @code{.} of a double-precision number to
! 3804: be the final character in the string. Allowing the @code{.} to be
! 3805: anywhere after the first digit is a Gforth extension.
! 3806: @item
! 3807: The number conversion process does not check for overflow.
! 3808: @item
! 3809: In Gforth, number conversion to floating-point numbers always use base
! 3810: 10, irrespective of the value of @code{BASE}. In ANS Forth,
! 3811: conversion to floating-point numbers whilst the value of
! 3812: @code{BASE} is not 10 is an ambiguous condition.
! 3813: @end itemize
1.1 anton 3814:
3815:
1.26 ! crook 3816: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
! 3817: @subsection Interpret/Compile states
! 3818: @cindex Interpret/Compile states
1.1 anton 3819:
1.26 ! crook 3820: @comment TODO Intro blah.
1.1 anton 3821:
1.26 ! crook 3822: doc-state
! 3823: doc-[
! 3824: doc-]
1.1 anton 3825:
3826:
1.26 ! crook 3827: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
! 3828: @subsection Literals
! 3829: @cindex Literals
1.21 crook 3830:
1.26 ! crook 3831: @comment TODO Intro blah.
1.23 crook 3832:
1.26 ! crook 3833: doc-literal
! 3834: doc-]L
! 3835: doc-2literal
! 3836: doc-fliteral
1.1 anton 3837:
1.26 ! crook 3838: @node Interpreter Directives, ,Literals, The Text Interpreter
! 3839: @subsection Interpreter Directives
! 3840: @cindex interpreter directives
1.1 anton 3841:
1.26 ! crook 3842: These words are usually used outside of definitions; for example, to
! 3843: control which parts of a source file are processed by the text
! 3844: interpreter. There are only a few ANS Forth Standard words, but Gforth
! 3845: supplements these with a rich set of immediate control structure words
! 3846: to compensate for the fact that the non-immediate versions can only be
! 3847: used in compile state (@pxref{Control Structures}).
1.1 anton 3848:
1.26 ! crook 3849: doc-[IF]
! 3850: doc-[ELSE]
! 3851: doc-[THEN]
! 3852: doc-[ENDIF]
1.1 anton 3853:
1.26 ! crook 3854: doc-[IFDEF]
! 3855: doc-[IFUNDEF]
1.1 anton 3856:
1.26 ! crook 3857: doc-[?DO]
! 3858: doc-[DO]
! 3859: doc-[FOR]
! 3860: doc-[LOOP]
! 3861: doc-[+LOOP]
! 3862: doc-[NEXT]
1.1 anton 3863:
1.26 ! crook 3864: doc-[BEGIN]
! 3865: doc-[UNTIL]
! 3866: doc-[AGAIN]
! 3867: doc-[WHILE]
! 3868: doc-[REPEAT]
1.1 anton 3869:
1.26 ! crook 3870: @c -------------------------------------------------------------
! 3871: @node Tokens for Words, Word Lists, The Text Interpreter, Words
! 3872: @section Tokens for Words
! 3873: @cindex tokens for words
1.1 anton 3874:
1.26 ! crook 3875: This chapter describes the creation and use of tokens that represent
! 3876: words on the stack (and in data space).
1.21 crook 3877:
1.26 ! crook 3878: Named words have interpretation and compilation semantics. Unnamed words
! 3879: just have execution semantics.
1.21 crook 3880:
1.26 ! crook 3881: @comment TODO ?normally interpretation semantics are the execution semantics.
! 3882: @comment this should all be covered in earlier ss
1.21 crook 3883:
1.26 ! crook 3884: @cindex execution token
! 3885: An @dfn{execution token} represents the execution semantics of an
! 3886: unnamed word. An execution token occupies one cell. As explained in
! 3887: @ref{Supplying names}, the execution token of the last word
! 3888: defined can be produced with @code{lastxt}.
1.1 anton 3889:
1.26 ! crook 3890: doc-execute
! 3891: doc-compile,
1.1 anton 3892:
1.26 ! crook 3893: @cindex code field address
! 3894: @cindex CFA
! 3895: In Gforth, the abstract data type @emph{execution token} is implemented
! 3896: as a code field address (CFA).
! 3897: @comment TODO note that the standard does not say what it represents..
! 3898: @comment and you cannot necessarily compile it in all Forths (eg native
! 3899: @comment compilers?).
1.1 anton 3900:
1.26 ! crook 3901: The interpretation semantics of a named word are also represented by an
! 3902: execution token. You can get it with:
1.1 anton 3903:
1.26 ! crook 3904: doc-[']
! 3905: doc-'
1.1 anton 3906:
1.26 ! crook 3907: For literals, you use @code{'} in interpreted code and @code{[']} in
! 3908: compiled code. Gforth's @code{'} and @code{[']} behave somewhat unusually
! 3909: by complaining about compile-only words. To get an execution token for a
! 3910: compiling word @var{X}, use @code{COMP' @var{X} drop} or @code{[COMP']
! 3911: @var{X} drop}.
1.1 anton 3912:
1.26 ! crook 3913: @cindex compilation token
! 3914: The compilation semantics are represented by a @dfn{compilation token}
! 3915: consisting of two cells: @var{w xt}. The top cell @var{xt} is an
! 3916: execution token. The compilation semantics represented by the
! 3917: compilation token can be performed with @code{execute}, which consumes
! 3918: the whole compilation token, with an additional stack effect determined
! 3919: by the represented compilation semantics.
1.1 anton 3920:
1.26 ! crook 3921: doc-[comp']
! 3922: doc-comp'
1.1 anton 3923:
1.26 ! crook 3924: You can compile the compilation semantics with @code{postpone,}. I.e.,
! 3925: @code{COMP' @var{word} POSTPONE,} is equivalent to @code{POSTPONE
! 3926: @var{word}}.
1.1 anton 3927:
1.26 ! crook 3928: doc-postpone,
1.1 anton 3929:
1.26 ! crook 3930: At present, the @var{w} part of a compilation token is an execution
! 3931: token, and the @var{xt} part represents either @code{execute} or
! 3932: @code{compile,}. However, don't rely on that knowledge, unless necessary;
! 3933: we may introduce unusual compilation tokens in the future (e.g.,
! 3934: compilation tokens representing the compilation semantics of literals).
1.21 crook 3935:
1.26 ! crook 3936: @cindex name token
! 3937: @cindex name field address
! 3938: @cindex NFA
! 3939: Named words are also represented by the @dfn{name token}, (@var{nt}). The abstract
! 3940: data type @emph{name token} is implemented as a name field address (NFA).
1.1 anton 3941:
1.26 ! crook 3942: doc-find-name
! 3943: doc-name>int
! 3944: doc-name?int
! 3945: doc-name>comp
! 3946: doc-name>string
1.1 anton 3947:
1.26 ! crook 3948: @c -------------------------------------------------------------
! 3949: @node Word Lists, Environmental Queries, Tokens for Words, Words
! 3950: @section Word Lists
! 3951: @cindex word lists
! 3952: @cindex name dictionary
1.1 anton 3953:
1.26 ! crook 3954: @cindex wid
! 3955: All definitions other than those created by @code{:noname} have an entry
! 3956: in the name dictionary. The name dictionary is fragmented into a number
! 3957: of parts, called @var{word lists}. A word list is identified by a
! 3958: cell-sized word list identifier (@var{wid}) in much the same way as a
! 3959: file is identified by a file handle. The numerical value of the wid has
! 3960: no (portable) meaning, and might change from session to session.
1.1 anton 3961:
1.26 ! crook 3962: @cindex compilation word list
! 3963: At any one time, a single word list is defined as the word list to which
! 3964: all new definitions will be added -- this is called the @var{compilation
! 3965: word list}. When Gforth is started, the compilation word list is the
! 3966: word list called @code{FORTH-WORDLIST}.
1.1 anton 3967:
1.26 ! crook 3968: @cindex search order stack
! 3969: Forth maintains a stack of word lists, representing the @var{search
! 3970: order}. When the name dictionary is searched (for example, when
! 3971: attempting to find a word's execution token during compilation), only
! 3972: those word lists that are currently in the search order are
! 3973: searched. The most recently-defined word in the word list at the top of
! 3974: the word list stack is searched first, and the search proceeds until
! 3975: either the word is located or the oldest definition in the word list at
! 3976: the bottom of the stack is reached. Definitions of the word may exist in
! 3977: more than one word lists; the search order determines which version will
! 3978: be found.
1.1 anton 3979:
1.26 ! crook 3980: The ANS Forth Standard ``Search order'' word set is intended to provide a
! 3981: set of low-level tools that allow various different schemes to be
! 3982: implemented. Gforth provides @code{vocabulary}, a traditional Forth
! 3983: word. @file{compat/vocabulary.fs} provides an implementation in ANS
! 3984: Standard Forth.
1.1 anton 3985:
1.26 ! crook 3986: TODO: locals section refers to here, saying that every word list (aka
! 3987: vocabulary) has its own methods for searching etc. Need to document that.
1.1 anton 3988:
1.26 ! crook 3989: doc-forth-wordlist
! 3990: doc-definitions
! 3991: doc-get-current
! 3992: doc-set-current
1.1 anton 3993:
1.26 ! crook 3994: @comment TODO when a defn (like set-order) is instanced twice, the second instance gets documented.
! 3995: @comment In general that might be fine, but in this example (search.fs) the second instance is an
! 3996: @comment alias, so it would not naturally have documentation
! 3997: @comment .. the fix to that is to add a specific prefix, like the object-orientation stuff does.
1.1 anton 3998:
1.26 ! crook 3999: doc-get-order
! 4000: doc-set-order
! 4001: doc-wordlist
! 4002: doc-also
! 4003: doc-forth
! 4004: doc-only
! 4005: doc-order
! 4006: doc-previous
1.15 anton 4007:
1.26 ! crook 4008: doc-find
! 4009: doc-search-wordlist
1.15 anton 4010:
1.26 ! crook 4011: doc-words
! 4012: doc-vlist
1.1 anton 4013:
1.26 ! crook 4014: doc-mappedwordlist
! 4015: doc-root
! 4016: doc-vocabulary
! 4017: doc-seal
! 4018: doc-vocs
! 4019: doc-current
! 4020: doc-context
1.1 anton 4021:
1.26 ! crook 4022: @menu
! 4023: * Why use word lists?::
! 4024: * Word list examples::
! 4025: @end menu
! 4026:
! 4027: @node Why use word lists?, Word list examples, Word Lists, Word Lists
! 4028: @subsection Why use word lists?
! 4029: @cindex word lists - why use them?
! 4030:
! 4031: There are several reasons for using multiple word lists:
! 4032:
! 4033: @itemize @bullet
! 4034: @item
! 4035: To improve compilation speed by reducing the number of name dictionary
! 4036: entries that must be searched. This is achieved by creating a new
! 4037: word list that contains all of the definitions that are used in the
! 4038: definition of a Forth system but which would not usually be used by
! 4039: programs running on that system. That word list would be on the search
! 4040: list when the Forth system was compiled but would be removed from the
! 4041: search list for normal operation. This can be a useful technique for
! 4042: low-performance systems (for example, 8-bit processors in embedded
! 4043: systems) but is unlikely to be necessary in high-performance desktop
! 4044: systems.
! 4045: @item
! 4046: To prevent a set of words from being used outside the context in which
! 4047: they are valid. Two classic examples of this are an integrated editor
! 4048: (all of the edit commands are defined in a separate word list; the
! 4049: search order is set to the editor word list when the editor is invoked;
! 4050: the old search order is restored when the editor is terminated) and an
! 4051: integrated assembler (the op-codes for the machine are defined in a
! 4052: separate word list which is used when a @code{CODE} word is defined).
! 4053: @item
! 4054: To prevent a name-space clash between multiple definitions with the same
! 4055: name. For example, when building a cross-compiler you might have a word
! 4056: @code{IF} that generates conditional code for your target system. By
! 4057: placing this definition in a different word list you can control whether
! 4058: the host system's @code{IF} or the target system's @code{IF} get used in
! 4059: any particular context by controlling the order of the word lists on the
! 4060: search order stack.
! 4061: @end itemize
1.1 anton 4062:
1.26 ! crook 4063: @node Word list examples, ,Why use word lists?, Word Lists
! 4064: @subsection Word list examples
! 4065: @cindex word lists - examples
1.1 anton 4066:
1.26 ! crook 4067: Here is an example of creating and using a new wordlist using ANS
! 4068: Forth Standard words:
1.1 anton 4069:
4070: @example
1.26 ! crook 4071: wordlist constant my-new-words-wordlist
! 4072: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
1.21 crook 4073:
1.26 ! crook 4074: \ add it to the search order
! 4075: also my-new-words
1.21 crook 4076:
1.26 ! crook 4077: \ alternatively, add it to the search order and make it
! 4078: \ the compilation word list
! 4079: also my-new-words definitions
! 4080: \ type "order" to see the problem
1.21 crook 4081: @end example
4082:
1.26 ! crook 4083: The problem with this example is that @code{order} has no way to
! 4084: associate the name @code{my-new-words} with the wid of the word list (in
! 4085: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
! 4086: that has no associated name). There is no Standard way of associating a
! 4087: name with a wid.
! 4088:
! 4089: In Gforth, this example can be re-coded using @code{vocabulary}, which
! 4090: associates a name with a wid:
1.21 crook 4091:
1.26 ! crook 4092: @example
! 4093: vocabulary my-new-words
1.21 crook 4094:
1.26 ! crook 4095: \ add it to the search order
! 4096: my-new-words
1.21 crook 4097:
1.26 ! crook 4098: \ alternatively, add it to the search order and make it
! 4099: \ the compilation word list
! 4100: my-new-words definitions
! 4101: \ type "order" to see that the problem is solved
! 4102: @end example
1.23 crook 4103:
1.26 ! crook 4104: @c -------------------------------------------------------------
! 4105: @node Environmental Queries, Files, Word Lists, Words
! 4106: @section Environmental Queries
! 4107: @cindex environmental queries
! 4108: @comment TODO more index entries
1.21 crook 4109:
1.26 ! crook 4110: ANS Forth introduced the idea of ``environmental queries'' as a way
! 4111: for a program running on a system to determine certain characteristics of the system.
! 4112: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 4113:
1.26 ! crook 4114: The Standard requires that the name space used for environmental queries
! 4115: be distinct from the name space used for definitions.
1.21 crook 4116:
1.26 ! crook 4117: Typically, environmental queries are supported by creating a set of
! 4118: definitions in a word list that is @var{only} used during environmental
! 4119: queries; that is what Gforth does. There is no Standard way of adding
! 4120: definitions to the set of recognised environmental queries, but any
! 4121: implementation that supports the loading of optional word sets must have
! 4122: some mechanism for doing this (after loading the word set, the
! 4123: associated environmental query string must return @code{true}). In
! 4124: Gforth, the word list used to honour environmental queries can be
! 4125: manipulated just like any other word list.
1.21 crook 4126:
1.26 ! crook 4127: doc-environment?
! 4128: doc-environment-wordlist
1.21 crook 4129:
1.26 ! crook 4130: doc-gforth
! 4131: doc-os-class
1.21 crook 4132:
1.26 ! crook 4133: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
! 4134: returning two items on the stack, querying it using @code{environment?}
! 4135: will return an additional item; the @code{true} flag that shows that the
! 4136: string was recognised.
1.21 crook 4137:
1.26 ! crook 4138: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 4139:
1.26 ! crook 4140: Here are some examples of using environmental queries:
1.21 crook 4141:
1.26 ! crook 4142: @example
! 4143: s" address-unit-bits" environment? 0=
! 4144: [IF]
! 4145: cr .( environmental attribute address-units-bits unknown... ) cr
! 4146: [THEN]
1.21 crook 4147:
1.26 ! crook 4148: s" block" environment? [IF] DROP include block.fs [THEN]
1.21 crook 4149:
1.26 ! crook 4150: s" gforth" environment? [IF] 2DROP include compat/vocabulary.fs [THEN]
1.21 crook 4151:
1.26 ! crook 4152: s" gforth" environment? [IF] .( Gforth version ) TYPE
! 4153: [ELSE] .( Not Gforth..) [THEN]
! 4154: @end example
1.21 crook 4155:
4156:
1.26 ! crook 4157: Here is an example of adding a definition to the environment word list:
1.21 crook 4158:
1.26 ! crook 4159: @example
! 4160: get-current environment-wordlist set-current
! 4161: true constant block
! 4162: true constant block-ext
! 4163: set-current
! 4164: @end example
1.21 crook 4165:
1.26 ! crook 4166: You can see what definitions are in the environment word list like this:
1.21 crook 4167:
1.26 ! crook 4168: @example
! 4169: get-order 1+ environment-wordlist swap set-order words previous
! 4170: @end example
1.21 crook 4171:
4172:
1.26 ! crook 4173: @c -------------------------------------------------------------
! 4174: @node Files, Blocks, Environmental Queries, Words
! 4175: @section Files
1.21 crook 4176:
1.26 ! crook 4177: Gforth provides facilities for accessing files that are stored in the
! 4178: host operating system's file-system. Files that are processed by Gforth
! 4179: can be divided into two categories:
1.21 crook 4180:
1.23 crook 4181: @itemize @bullet
4182: @item
1.26 ! crook 4183: Files that are processed by the Text Interpreter (@var{Forth source files}).
1.23 crook 4184: @item
1.26 ! crook 4185: Files that are processed by some other program (@var{general files}).
! 4186: @end itemize
! 4187:
! 4188: @menu
! 4189: * Forth source files::
! 4190: * General files::
! 4191: * Search Paths::
! 4192: * Forth Search Paths::
! 4193: * General Search Paths::
! 4194: @end menu
! 4195:
1.21 crook 4196:
1.26 ! crook 4197: @c -------------------------------------------------------------
! 4198: @node Forth source files, General files, Files, Files
! 4199: @subsection Forth source files
! 4200: @cindex including files
! 4201: @cindex Forth source files
1.21 crook 4202:
1.26 ! crook 4203: The simplest way to interpret the contents of a file is to use one of
! 4204: these two formats:
1.21 crook 4205:
1.26 ! crook 4206: @example
! 4207: include mysource.fs
! 4208: s" mysource.fs" included
! 4209: @end example
1.21 crook 4210:
1.26 ! crook 4211: Sometimes you want to include a file only if it is not included already
! 4212: (by, say, another source file). In that case, you can use one of these
! 4213: fomats:
1.21 crook 4214:
1.26 ! crook 4215: @example
! 4216: require mysource.fs
! 4217: needs mysource.fs
! 4218: s" mysource.fs" required
! 4219: @end example
1.21 crook 4220:
1.26 ! crook 4221: @cindex stack effect of included files
! 4222: @cindex including files, stack effect
! 4223: I recommend that you write your source files such that interpreting them
! 4224: does not change the stack. This allows using these files with
! 4225: @code{required} and friends without complications. For example:
1.21 crook 4226:
1.26 ! crook 4227: @example
! 4228: 1 require foo.fs drop
! 4229: @end example
1.21 crook 4230:
4231:
1.26 ! crook 4232: doc-include-file
! 4233: doc-included
! 4234: doc-include
! 4235: @comment TODO describe what happens on error. Describes how the require
! 4236: @comment stuff works and describe how to clear/reset the history (eg
! 4237: @comment for debug). Might want to include that in the MARKER example.
! 4238: doc-required
! 4239: doc-require
! 4240: doc-needs
1.21 crook 4241:
1.26 ! crook 4242: A definition in ANS Forth for @code{required} is provided in
! 4243: @file{compat/required.fs}.
1.21 crook 4244:
1.26 ! crook 4245: @c -------------------------------------------------------------
! 4246: @node General files, Search Paths, Forth source files, Files
! 4247: @subsection General files
! 4248: @cindex general files
! 4249: @cindex file-handling
1.21 crook 4250:
1.26 ! crook 4251: Files are opened/created by name and type. The following types are
! 4252: recognised:
1.1 anton 4253:
1.26 ! crook 4254: doc-r/o
! 4255: doc-r/w
! 4256: doc-w/o
! 4257: doc-bin
1.1 anton 4258:
1.26 ! crook 4259: When a file is opened/created, it returns a file identifier,
! 4260: @var{wfileid} that is used for all other file commands. All file
! 4261: commands also return a status value, @var{wior}, that is 0 for a
! 4262: successful operation and an implementation-defined non-zero value in the
! 4263: case of an error.
1.21 crook 4264:
1.26 ! crook 4265: doc-open-file
! 4266: doc-create-file
1.21 crook 4267:
1.26 ! crook 4268: doc-close-file
! 4269: doc-delete-file
! 4270: doc-rename-file
! 4271: doc-read-file
! 4272: doc-read-line
! 4273: doc-write-file
! 4274: doc-write-line
! 4275: doc-emit-file
! 4276: doc-flush-file
1.21 crook 4277:
1.26 ! crook 4278: doc-file-status
! 4279: doc-file-position
! 4280: doc-reposition-file
! 4281: doc-file-size
! 4282: doc-resize-file
1.21 crook 4283:
1.26 ! crook 4284: @c ---------------------------------------------------------
! 4285: @node Search Paths, Forth Search Paths, General files, Files
! 4286: @subsection Search Paths
! 4287: @cindex path for @code{included}
! 4288: @cindex file search path
! 4289: @cindex @code{include} search path
! 4290: @cindex search path for files
1.21 crook 4291:
1.26 ! crook 4292: @comment what uses these search paths.. just include and friends?
! 4293: If you specify an absolute filename (i.e., a filename starting with
! 4294: @file{/} or @file{~}, or with @file{:} in the second position (as in
! 4295: @samp{C:...})) for @code{included} and friends, that file is included
! 4296: just as you would expect.
1.21 crook 4297:
1.26 ! crook 4298: For relative filenames, Gforth uses a search path similar to Forth's
! 4299: search order (@pxref{Word Lists}). It tries to find the given filename
! 4300: in the directories present in the path, and includes the first one it
! 4301: finds. There are separate search paths for Forth source files and
! 4302: general files.
1.21 crook 4303:
1.26 ! crook 4304: If the search path contains the directory @file{.} (as it should), this
! 4305: refers to the directory that the present file was @code{included}
! 4306: from. This allows files to include other files relative to their own
! 4307: position (irrespective of the current working directory or the absolute
! 4308: position). This feature is essential for libraries consisting of
! 4309: several files, where a file may include other files from the library.
! 4310: It corresponds to @code{#include "..."} in C. If the current input
! 4311: source is not a file, @file{.} refers to the directory of the innermost
! 4312: file being included, or, if there is no file being included, to the
! 4313: current working directory.
1.21 crook 4314:
1.26 ! crook 4315: Use @file{~+} to refer to the current working directory (as in the
! 4316: @code{bash}).
1.1 anton 4317:
1.26 ! crook 4318: If the filename starts with @file{./}, the search path is not searched
! 4319: (just as with absolute filenames), and the @file{.} has the same meaning
! 4320: as described above.
1.1 anton 4321:
1.26 ! crook 4322: @c ---------------------------------------------------------
! 4323: @node Forth Search Paths, General Search Paths, Search Paths, Files
! 4324: @subsubsection Forth Search Paths
! 4325: @cindex search path control - forth
1.5 anton 4326:
1.26 ! crook 4327: The search path is initialized when you start Gforth (@pxref{Invoking
! 4328: Gforth}). You can display it and change it using these words:
1.5 anton 4329:
1.26 ! crook 4330: doc-.fpath
! 4331: doc-fpath+
! 4332: doc-fpath=
! 4333: doc-open-fpath-file
1.5 anton 4334:
1.26 ! crook 4335: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 4336:
1.26 ! crook 4337: @example
! 4338: fpath= /usr/lib/forth/|./
! 4339: require timer.fs
! 4340: @end example
1.5 anton 4341:
1.26 ! crook 4342: @c ---------------------------------------------------------
! 4343: @node General Search Paths, , Forth Search Paths, Files
! 4344: @subsubsection General Search Paths
! 4345: @cindex search path control - for user applications
1.5 anton 4346:
1.26 ! crook 4347: Your application may need to search files in several directories, like
! 4348: @code{included} does. To facilitate this, Gforth allows you to define
! 4349: and use your own search paths, by providing generic equivalents of the
! 4350: Forth search path words:
1.5 anton 4351:
1.26 ! crook 4352: doc-.path
! 4353: doc-path+
! 4354: doc-path=
! 4355: doc-open-path-file
1.5 anton 4356:
1.26 ! crook 4357: Here's an example of creating a search path:
1.5 anton 4358:
1.26 ! crook 4359: @example
! 4360: \ Make a buffer for the path:
! 4361: create mypath 100 chars , \ maximum length (is checked)
! 4362: 0 , \ real len
! 4363: 100 chars allot \ space for path
! 4364: @end example
1.5 anton 4365:
1.26 ! crook 4366: @c -------------------------------------------------------------
! 4367: @node Blocks, Other I/O, Files, Words
! 4368: @section Blocks
! 4369:
! 4370: This chapter describes how to use block files within Gforth.
! 4371:
! 4372: Block files are traditionally means of data and source storage in
! 4373: Forth. They have been very important in resource-starved computers
! 4374: without OS in the past. Gforth doesn't encourage to use blocks as
! 4375: source, and provides blocks only for backward compatibility. The ANS
! 4376: standard requires blocks to be available when files are.
! 4377:
! 4378: @comment TODO what about errors on open-blocks?
! 4379: doc-open-blocks
! 4380: doc-use
! 4381: doc-scr
! 4382: doc-blk
! 4383: doc-get-block-fid
! 4384: doc-block-position
! 4385: doc-update
! 4386: doc-save-buffers
! 4387: doc-save-buffer
! 4388: doc-empty-buffers
! 4389: doc-empty-buffer
! 4390: doc-flush
! 4391: doc-get-buffer
! 4392: doc---block-block
! 4393: doc-buffer
! 4394: doc-updated?
! 4395: doc-list
! 4396: doc-load
! 4397: doc-thru
! 4398: doc-+load
! 4399: doc-+thru
! 4400: doc---block--->
! 4401: doc-block-included
! 4402:
! 4403: @c -------------------------------------------------------------
! 4404: @node Other I/O, Programming Tools, Blocks, Words
! 4405: @section Other I/O
! 4406: @comment TODO more index entries
! 4407:
! 4408: @menu
! 4409: * Simple numeric output:: Predefined formats
! 4410: * Formatted numeric output:: Formatted (pictured) output
! 4411: * String Formats:: How Forth stores strings in memory
! 4412: * Displaying characters and strings:: Other stuff
! 4413: * Input:: Input
! 4414: @end menu
! 4415:
! 4416: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
! 4417: @subsection Simple numeric output
! 4418: @cindex simple numeric output
! 4419: @comment TODO more index entries
1.5 anton 4420:
1.26 ! crook 4421: The simplest output functions are those that display numbers from the
! 4422: data or floating-point stacks. Floating-point output is always displayed
! 4423: using base 10. Numbers displayed from the data stack use the value stored
! 4424: in @code{base}.
1.5 anton 4425:
1.26 ! crook 4426: doc-.
! 4427: doc-dec.
! 4428: doc-hex.
! 4429: doc-u.
! 4430: doc-.r
! 4431: doc-u.r
! 4432: doc-d.
! 4433: doc-ud.
! 4434: doc-d.r
! 4435: doc-ud.r
! 4436: doc-f.
! 4437: doc-fe.
! 4438: doc-fs.
1.5 anton 4439:
1.26 ! crook 4440: Examples of printing the number 1234.5678E23 in the different floating-point output
! 4441: formats are shown below:
1.5 anton 4442:
4443: @example
1.26 ! crook 4444: f. 123456779999999000000000000.
! 4445: fe. 123.456779999999E24
! 4446: fs. 1.23456779999999E26
1.5 anton 4447: @end example
4448:
4449:
1.26 ! crook 4450: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
! 4451: @subsection Formatted numeric output
! 4452: @cindex Formatted numeric output
! 4453: @cindex pictured numeric output
! 4454: @comment TODO more index entries
! 4455:
! 4456: Forth traditionally uses a technique called @var{pictured numeric
! 4457: output} for formatted printing of integers. In this technique, digits
! 4458: are extracted from the number (using the current output radix defined by
! 4459: @code{base}), converted to ASCII codes and appended to a string that is
! 4460: built in a scratch-pad area of memory (@pxref{core-idef,
! 4461: Implementation-defined options, Implementation-defined
! 4462: options}). Arbitrary characters can be appended to the string during the
! 4463: extraction process. The completed string is specified by an address
! 4464: and length and can be manipulated (@code{TYPE}ed, copied, modified)
! 4465: under program control.
1.5 anton 4466:
1.26 ! crook 4467: All of the words described in the previous section for simple numeric
! 4468: output are implemented in Gforth using pictured numeric output.
1.5 anton 4469:
1.26 ! crook 4470: Three important things to remember about Pictured Numeric Output:
1.5 anton 4471:
1.26 ! crook 4472: @itemize @bullet
! 4473: @item
! 4474: It always operates on double-precision numbers; to display a single-precision number,
! 4475: convert it first (@pxref{Double precision} for ways of doing this).
! 4476: @item
! 4477: It always treats the double-precision number as though it were unsigned. Refer to
! 4478: the examples below for ways of printing signed numbers.
! 4479: @item
! 4480: The string is built up from right to left; least significant digit first.
! 4481: @end itemize
1.5 anton 4482:
1.26 ! crook 4483: doc-<#
! 4484: doc-#
! 4485: doc-#s
! 4486: doc-hold
! 4487: doc-sign
! 4488: doc-#>
1.5 anton 4489:
1.26 ! crook 4490: doc-represent
1.5 anton 4491:
1.26 ! crook 4492: Here are some examples of using pictured numeric output:
1.5 anton 4493:
4494: @example
1.26 ! crook 4495: : my-u. ( u -- )
! 4496: \ Simplest use of pns.. behaves like Standard u.
! 4497: 0 \ convert to unsigned double
! 4498: <# \ start conversion
! 4499: #s \ convert all digits
! 4500: #> \ complete conversion
! 4501: TYPE SPACE ; \ display, with trailing space
1.5 anton 4502:
1.26 ! crook 4503: : cents-only ( u -- )
! 4504: 0 \ convert to unsigned double
! 4505: <# \ start conversion
! 4506: # # \ convert two least-significant digits
! 4507: #> \ complete conversion, discard other digits
! 4508: TYPE SPACE ; \ display, with trailing space
1.5 anton 4509:
1.26 ! crook 4510: : dollars-and-cents ( u -- )
! 4511: 0 \ convert to unsigned double
! 4512: <# \ start conversion
! 4513: # # \ convert two least-significant digits
! 4514: [char] . hold \ insert decimal point
! 4515: #s \ convert remaining digits
! 4516: [char] $ hold \ append currency symbol
! 4517: #> \ complete conversion
! 4518: TYPE SPACE ; \ display, with trailing space
1.5 anton 4519:
1.26 ! crook 4520: : my-. ( n -- )
! 4521: \ handling negatives.. behaves like Standard .
! 4522: s>d \ convert to signed double
! 4523: swap over dabs \ leave sign byte followed by unsigned double
! 4524: <# \ start conversion
! 4525: #s \ convert all digits
! 4526: rot sign \ get at sign byte, append "-" if needed
! 4527: #> \ complete conversion
! 4528: TYPE SPACE ; \ display, with trailing space
1.5 anton 4529:
1.26 ! crook 4530: : account. ( n -- )
! 4531: \ accountants don't like minus signs, they use braces
! 4532: \ for negative numbers
! 4533: s>d \ convert to signed double
! 4534: swap over dabs \ leave sign byte followed by unsigned double
! 4535: <# \ start conversion
! 4536: 2 pick \ get copy of sign byte
! 4537: 0< IF [char] ) hold THEN \ right-most character of output
! 4538: #s \ convert all digits
! 4539: rot \ get at sign byte
! 4540: 0< IF [char] ( hold THEN
! 4541: #> \ complete conversion
! 4542: TYPE SPACE ; \ display, with trailing space
1.5 anton 4543: @end example
4544:
1.26 ! crook 4545: Here are some examples of using these words:
1.5 anton 4546:
4547: @example
1.26 ! crook 4548: 1 my-u. 1
! 4549: hex -1 my-u. decimal FFFFFFFF
! 4550: 1 cents-only 01
! 4551: 1234 cents-only 34
! 4552: 2 dollars-and-cents $0.02
! 4553: 1234 dollars-and-cents $12.34
! 4554: 123 my-. 123
! 4555: -123 my. -123
! 4556: 123 account. 123
! 4557: -456 account. (456)
1.5 anton 4558: @end example
4559:
4560:
1.26 ! crook 4561: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
! 4562: @subsection String Formats
! 4563: @cindex string formats
! 4564:
! 4565: @comment TODO more index entries
! 4566:
! 4567: Forth commonly uses two different methods for representing a string:
! 4568:
! 4569: @itemize @bullet
! 4570: @item
! 4571: @cindex address of counted string
! 4572: As a @var{counted string}, represented by a @var{c-addr}. The char
! 4573: addressed by @var{c-addr} contains a character-count, @var{n}, of the
! 4574: string and the string occupies the subsequent @var{n} char addresses in
! 4575: memory.
! 4576: @item
! 4577: As cell pair on the stack; @var{c-addr u}, where @var{u} is the length
! 4578: of the string in characters, and @var{c-addr} is the address of the
! 4579: first byte of the string.
! 4580: @end itemize
! 4581:
! 4582: ANS Forth encourages the use of the second format when representing
! 4583: strings on the stack, whilst conceeding that the counted string format
! 4584: remains useful as a way of storing strings in memory.
! 4585:
! 4586: doc-count
! 4587:
! 4588: @xref{Memory Blocks} for words that move, copy and search
! 4589: for strings. @xref{Displaying characters and strings,} for words that
! 4590: display characters and strings.
! 4591:
! 4592:
! 4593: @node Displaying characters and strings, Input, String Formats, Other I/O
! 4594: @subsection Displaying characters and strings
! 4595: @cindex displaying characters and strings
! 4596: @cindex compiling characters and strings
! 4597: @cindex cursor control
! 4598:
! 4599: @comment TODO more index entries
! 4600:
! 4601: This section starts with a glossary of Forth words and ends with a set
! 4602: of examples.
! 4603:
! 4604: doc-bl
! 4605: doc-space
! 4606: doc-spaces
! 4607: doc-emit
! 4608: doc-toupper
! 4609: doc-."
! 4610: doc-.(
! 4611: doc-type
! 4612: doc-cr
! 4613: doc-at-xy
! 4614: doc-page
! 4615: doc-s"
! 4616: doc-c"
! 4617: doc-char
! 4618: doc-[char]
! 4619: doc-sliteral
! 4620:
! 4621: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 4622:
4623: @example
1.26 ! crook 4624: .( text-1)
! 4625: : my-word
! 4626: ." text-2" cr
! 4627: .( text-3)
! 4628: ;
! 4629:
! 4630: ." text-4"
! 4631:
! 4632: : my-char
! 4633: [char] ALPHABET emit
! 4634: char emit
! 4635: ;
1.5 anton 4636: @end example
4637:
1.26 ! crook 4638: When you load this code into Gforth, the following output is generated:
1.5 anton 4639:
1.26 ! crook 4640: @example
! 4641: @kbd{include test.fs <return>} text-1text-3text-4 ok
! 4642: @end example
1.5 anton 4643:
1.26 ! crook 4644: @itemize @bullet
! 4645: @item
! 4646: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
! 4647: is an immediate word; it behaves in the same way whether it is used inside
! 4648: or outside a colon definition.
! 4649: @item
! 4650: Message @code{text-4} is displayed because of Gforth's added interpretation
! 4651: semantics for @code{."}.
! 4652: @item
! 4653: Message @code{text-2} is @var{not} displayed, because the text interpreter
! 4654: performs the compilation semantics for @code{."} within the definition of
! 4655: @code{my-word}.
! 4656: @end itemize
1.5 anton 4657:
1.26 ! crook 4658: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 4659:
1.26 ! crook 4660: @example
! 4661: @kbd{my-word <return>} text-2
! 4662: ok
! 4663: @kbd{my-char fred <return>} Af ok
! 4664: @kbd{my-char jim <return>} Aj ok
! 4665: @end example
1.5 anton 4666:
4667: @itemize @bullet
4668: @item
1.26 ! crook 4669: Message @code{text-2} is displayed because of the run-time behaviour of
! 4670: @code{."}.
! 4671: @item
! 4672: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
! 4673: on the stack at run-time. @code{emit} always displays the character
! 4674: when @code{my-char} is executed.
! 4675: @item
! 4676: @code{char} parses a string at run-time and the second @code{emit} displays
! 4677: the first character of the string.
1.5 anton 4678: @item
1.26 ! crook 4679: If you type @code{see my-char} you can see that @code{[char]} discarded
! 4680: the text ``LPHABET'' and only compiled the display code for ``A'' into the
! 4681: definition of @code{my-char}.
1.5 anton 4682: @end itemize
4683:
4684:
4685:
1.26 ! crook 4686: @node Input, , Displaying characters and strings, Other I/O
! 4687: @subsection Input
! 4688: @cindex input
! 4689: @comment TODO more index entries
1.5 anton 4690:
1.26 ! crook 4691: Blah on traditional and recommended string formats.
1.5 anton 4692:
1.26 ! crook 4693: doc--trailing
! 4694: doc-/string
! 4695: doc-convert
! 4696: doc->number
! 4697: doc->float
! 4698: doc-accept
! 4699: doc-query
! 4700: doc-expect
! 4701: doc-evaluate
! 4702: doc-key
! 4703: doc-key?
1.5 anton 4704:
1.26 ! crook 4705: TODO reference the block move stuff elsewhere
1.5 anton 4706:
1.26 ! crook 4707: TODO convert and >number might be better in the numeric input section.
1.5 anton 4708:
1.26 ! crook 4709: TODO maybe some of these shouldn't be here but should be in a ``parsing'' section
1.5 anton 4710:
4711:
4712: @c -------------------------------------------------------------
1.26 ! crook 4713: @node Programming Tools, Assembler and Code Words, Other I/O, Words
! 4714: @section Programming Tools
! 4715: @cindex programming tools
1.12 anton 4716:
4717: @menu
1.26 ! crook 4718: * Debugging:: Simple and quick.
! 4719: * Assertions:: Making your programs self-checking.
! 4720: * Singlestep Debugger:: Executing your program word by word.
1.5 anton 4721: @end menu
4722:
1.26 ! crook 4723: @node Debugging, Assertions, Programming Tools, Programming Tools
! 4724: @subsection Debugging
! 4725: @cindex debugging
1.5 anton 4726:
1.26 ! crook 4727: Languages with a slow edit/compile/link/test development loop tend to
! 4728: require sophisticated tracing/stepping debuggers to facilate
! 4729: productive debugging.
1.5 anton 4730:
1.26 ! crook 4731: A much better (faster) way in fast-compiling languages is to add
! 4732: printing code at well-selected places, let the program run, look at
! 4733: the output, see where things went wrong, add more printing code, etc.,
! 4734: until the bug is found.
1.5 anton 4735:
1.26 ! crook 4736: The simple debugging aids provided in @file{debugs.fs}
! 4737: are meant to support this style of debugging. In addition, there are
! 4738: words for non-destructively inspecting the stack and memory:
1.5 anton 4739:
1.26 ! crook 4740: doc-.s
! 4741: doc-f.s
1.5 anton 4742:
1.26 ! crook 4743: There is a word @code{.r} but it does @var{not} display the return
! 4744: stack! It is used for formatted numeric output.
1.5 anton 4745:
1.26 ! crook 4746: doc-depth
! 4747: doc-fdepth
! 4748: doc-clearstack
! 4749: doc-?
! 4750: doc-dump
1.5 anton 4751:
1.26 ! crook 4752: The word @code{~~} prints debugging information (by default the source
! 4753: location and the stack contents). It is easy to insert. If you use Emacs
! 4754: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
! 4755: query-replace them with nothing). The deferred words
! 4756: @code{printdebugdata} and @code{printdebugline} control the output of
! 4757: @code{~~}. The default source location output format works well with
! 4758: Emacs' compilation mode, so you can step through the program at the
! 4759: source level using @kbd{C-x `} (the advantage over a stepping debugger
! 4760: is that you can step in any direction and you know where the crash has
! 4761: happened or where the strange data has occurred).
1.5 anton 4762:
1.26 ! crook 4763: The default actions of @code{~~} clobber the contents of the pictured
! 4764: numeric output string, so you should not use @code{~~}, e.g., between
! 4765: @code{<#} and @code{#>}.
1.5 anton 4766:
1.26 ! crook 4767: doc-~~
! 4768: doc-printdebugdata
! 4769: doc-printdebugline
1.5 anton 4770:
1.26 ! crook 4771: doc-see
! 4772: doc-marker
1.5 anton 4773:
1.26 ! crook 4774: Here's an example of using @code{marker} at the start of a source file
! 4775: that you are debugging; it ensures that you only ever have one copy of
! 4776: the file's definitions compiled at any time:
1.5 anton 4777:
1.26 ! crook 4778: @example
! 4779: [IFDEF] my-code
! 4780: my-code
! 4781: [ENDIF]
1.5 anton 4782:
1.26 ! crook 4783: marker my-code
1.5 anton 4784:
1.26 ! crook 4785: \ .. definitions start here
! 4786: \ .
! 4787: \ .
! 4788: \ end
! 4789: @end example
1.5 anton 4790:
4791:
4792:
1.26 ! crook 4793: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
! 4794: @subsection Assertions
! 4795: @cindex assertions
1.5 anton 4796:
1.26 ! crook 4797: It is a good idea to make your programs self-checking, especially if you
! 4798: make an assumption that may become invalid during maintenance (for
! 4799: example, that a certain field of a data structure is never zero). Gforth
! 4800: supports @var{assertions} for this purpose. They are used like this:
1.23 crook 4801:
1.26 ! crook 4802: @example
! 4803: assert( @var{flag} )
! 4804: @end example
1.23 crook 4805:
1.26 ! crook 4806: The code between @code{assert(} and @code{)} should compute a flag, that
! 4807: should be true if everything is alright and false otherwise. It should
! 4808: not change anything else on the stack. The overall stack effect of the
! 4809: assertion is @code{( -- )}. E.g.
1.23 crook 4810:
1.26 ! crook 4811: @example
! 4812: assert( 1 1 + 2 = ) \ what we learn in school
! 4813: assert( dup 0<> ) \ assert that the top of stack is not zero
! 4814: assert( false ) \ this code should not be reached
! 4815: @end example
1.23 crook 4816:
1.26 ! crook 4817: The need for assertions is different at different times. During
! 4818: debugging, we want more checking, in production we sometimes care more
! 4819: for speed. Therefore, assertions can be turned off, i.e., the assertion
! 4820: becomes a comment. Depending on the importance of an assertion and the
! 4821: time it takes to check it, you may want to turn off some assertions and
! 4822: keep others turned on. Gforth provides several levels of assertions for
! 4823: this purpose:
1.23 crook 4824:
1.26 ! crook 4825: doc-assert0(
! 4826: doc-assert1(
! 4827: doc-assert2(
! 4828: doc-assert3(
! 4829: doc-assert(
! 4830: doc-)
1.23 crook 4831:
1.26 ! crook 4832: The variable @code{assert-level} specifies the highest assertions that
! 4833: are turned on. I.e., at the default @code{assert-level} of one,
! 4834: @code{assert0(} and @code{assert1(} assertions perform checking, while
! 4835: @code{assert2(} and @code{assert3(} assertions are treated as comments.
! 4836:
! 4837: The value of @code{assert-level} is evaluated at compile-time, not at
! 4838: run-time. Therefore you cannot turn assertions on or off at run-time;
! 4839: you have to set the @code{assert-level} appropriately before compiling a
! 4840: piece of code. You can compile different pieces of code at different
! 4841: @code{assert-level}s (e.g., a trusted library at level 1 and
! 4842: newly-written code at level 3).
1.23 crook 4843:
1.26 ! crook 4844: doc-assert-level
1.23 crook 4845:
1.26 ! crook 4846: If an assertion fails, a message compatible with Emacs' compilation mode
! 4847: is produced and the execution is aborted (currently with @code{ABORT"}.
! 4848: If there is interest, we will introduce a special throw code. But if you
! 4849: intend to @code{catch} a specific condition, using @code{throw} is
! 4850: probably more appropriate than an assertion).
1.23 crook 4851:
1.26 ! crook 4852: Definitions in ANS Forth for these assertion words are provided
! 4853: in @file{compat/assert.fs}.
1.23 crook 4854:
4855:
1.26 ! crook 4856: @node Singlestep Debugger, , Assertions, Programming Tools
! 4857: @subsection Singlestep Debugger
! 4858: @cindex singlestep Debugger
! 4859: @cindex debugging Singlestep
! 4860: @cindex @code{dbg}
! 4861: @cindex @code{BREAK:}
! 4862: @cindex @code{BREAK"}
1.23 crook 4863:
1.26 ! crook 4864: When you create a new word there's often the need to check whether it
! 4865: behaves correctly or not. You can do this by typing @code{dbg
! 4866: badword}. A debug session might look like this:
1.23 crook 4867:
1.26 ! crook 4868: @example
! 4869: : badword 0 DO i . LOOP ; ok
! 4870: 2 dbg badword
! 4871: : badword
! 4872: Scanning code...
1.23 crook 4873:
1.26 ! crook 4874: Nesting debugger ready!
1.23 crook 4875:
1.26 ! crook 4876: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
! 4877: 400D4740 8049F68 DO -> [ 0 ]
! 4878: 400D4744 804A0C8 i -> [ 1 ] 00000
! 4879: 400D4748 400C5E60 . -> 0 [ 0 ]
! 4880: 400D474C 8049D0C LOOP -> [ 0 ]
! 4881: 400D4744 804A0C8 i -> [ 1 ] 00001
! 4882: 400D4748 400C5E60 . -> 1 [ 0 ]
! 4883: 400D474C 8049D0C LOOP -> [ 0 ]
! 4884: 400D4758 804B384 ; -> ok
! 4885: @end example
1.23 crook 4886:
1.26 ! crook 4887: Each line displayed is one step. You always have to hit return to
! 4888: execute the next word that is displayed. If you don't want to execute
! 4889: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
! 4890: an overview what keys are available:
1.23 crook 4891:
1.26 ! crook 4892: @table @i
1.23 crook 4893:
1.26 ! crook 4894: @item <return>
! 4895: Next; Execute the next word.
1.23 crook 4896:
1.26 ! crook 4897: @item n
! 4898: Nest; Single step through next word.
1.5 anton 4899:
1.26 ! crook 4900: @item u
! 4901: Unnest; Stop debugging and execute rest of word. If we got to this word
! 4902: with nest, continue debugging with the calling word.
1.5 anton 4903:
1.26 ! crook 4904: @item d
! 4905: Done; Stop debugging and execute rest.
1.5 anton 4906:
1.26 ! crook 4907: @item s
! 4908: Stop; Abort immediately.
1.5 anton 4909:
1.26 ! crook 4910: @end table
1.5 anton 4911:
1.26 ! crook 4912: Debugging large application with this mechanism is very difficult, because
! 4913: you have to nest very deeply into the program before the interesting part
! 4914: begins. This takes a lot of time.
1.5 anton 4915:
1.26 ! crook 4916: To do it more directly put a @code{BREAK:} command into your source code.
! 4917: When program execution reaches @code{BREAK:} the single step debugger is
! 4918: invoked and you have all the features described above.
1.23 crook 4919:
1.26 ! crook 4920: If you have more than one part to debug it is useful to know where the
! 4921: program has stopped at the moment. You can do this by the
! 4922: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
! 4923: string is typed out when the ``breakpoint'' is reached.
! 4924:
! 4925: doc-dbg
! 4926: doc-BREAK:
! 4927: doc-BREAK"
! 4928:
! 4929:
! 4930: @c -------------------------------------------------------------
! 4931: @node Assembler and Code Words, Threading Words, Programming Tools, Words
! 4932: @section Assembler and Code Words
! 4933: @cindex assembler
! 4934: @cindex code words
1.5 anton 4935:
1.26 ! crook 4936: Gforth provides some words for defining primitives (words written in
! 4937: machine code), and for defining the the machine-code equivalent of
! 4938: @code{DOES>}-based defining words. However, the machine-independent
! 4939: nature of Gforth poses a few problems: First of all, Gforth runs on
! 4940: several architectures, so it can provide no standard assembler. What's
! 4941: worse is that the register allocation not only depends on the processor,
! 4942: but also on the @code{gcc} version and options used.
1.5 anton 4943:
1.26 ! crook 4944: The words that Gforth offers encapsulate some system dependences (e.g., the
! 4945: header structure), so a system-independent assembler may be used in
! 4946: Gforth. If you do not have an assembler, you can compile machine code
! 4947: directly with @code{,} and @code{c,}.
1.5 anton 4948:
1.26 ! crook 4949: doc-assembler
! 4950: doc-code
! 4951: doc-end-code
! 4952: doc-;code
! 4953: doc-flush-icache
1.5 anton 4954:
1.26 ! crook 4955: If @code{flush-icache} does not work correctly, @code{code} words
! 4956: etc. will not work (reliably), either.
1.5 anton 4957:
1.26 ! crook 4958: @code{flush-icache} is always present. The other words are rarely used
! 4959: and reside in @code{code.fs}, which is usually not loaded. You can load
! 4960: it with @code{require code.fs}.
1.5 anton 4961:
1.26 ! crook 4962: @cindex registers of the inner interpreter
! 4963: In the assembly code you will want to refer to the inner interpreter's
! 4964: registers (e.g., the data stack pointer) and you may want to use other
! 4965: registers for temporary storage. Unfortunately, the register allocation
! 4966: is installation-dependent.
1.5 anton 4967:
1.26 ! crook 4968: The easiest solution is to use explicit register declarations
! 4969: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
! 4970: GNU C Manual}) for all of the inner interpreter's registers: You have to
! 4971: compile Gforth with @code{-DFORCE_REG} (configure option
! 4972: @code{--enable-force-reg}) and the appropriate declarations must be
! 4973: present in the @code{machine.h} file (see @code{mips.h} for an example;
! 4974: you can find a full list of all declarable register symbols with
! 4975: @code{grep register engine.c}). If you give explicit registers to all
! 4976: variables that are declared at the beginning of @code{engine()}, you
! 4977: should be able to use the other caller-saved registers for temporary
! 4978: storage. Alternatively, you can use the @code{gcc} option
! 4979: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
! 4980: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
! 4981: (however, this restriction on register allocation may slow Gforth
! 4982: significantly).
1.5 anton 4983:
1.26 ! crook 4984: If this solution is not viable (e.g., because @code{gcc} does not allow
! 4985: you to explicitly declare all the registers you need), you have to find
! 4986: out by looking at the code where the inner interpreter's registers
! 4987: reside and which registers can be used for temporary storage. You can
! 4988: get an assembly listing of the engine's code with @code{make engine.s}.
1.5 anton 4989:
1.26 ! crook 4990: In any case, it is good practice to abstract your assembly code from the
! 4991: actual register allocation. E.g., if the data stack pointer resides in
! 4992: register @code{$17}, create an alias for this register called @code{sp},
! 4993: and use that in your assembly code.
1.5 anton 4994:
1.26 ! crook 4995: @cindex code words, portable
! 4996: Another option for implementing normal and defining words efficiently
! 4997: is to add the desired functionality to the source of Gforth. For normal
! 4998: words you just have to edit @file{primitives} (@pxref{Automatic
! 4999: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
! 5000: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
! 5001: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.5 anton 5002:
5003:
1.26 ! crook 5004: @c -------------------------------------------------------------
! 5005: @node Threading Words, Locals, Assembler and Code Words, Words
! 5006: @section Threading Words
! 5007: @cindex threading words
1.5 anton 5008:
1.26 ! crook 5009: @cindex code address
! 5010: These words provide access to code addresses and other threading stuff
! 5011: in Gforth (and, possibly, other interpretive Forths). It more or less
! 5012: abstracts away the differences between direct and indirect threading
! 5013: (and, for direct threading, the machine dependences). However, at
! 5014: present this wordset is still incomplete. It is also pretty low-level;
! 5015: some day it will hopefully be made unnecessary by an internals wordset
! 5016: that abstracts implementation details away completely.
1.5 anton 5017:
1.26 ! crook 5018: doc-threading-method
! 5019: doc->code-address
! 5020: doc->does-code
! 5021: doc-code-address!
! 5022: doc-does-code!
! 5023: doc-does-handler!
! 5024: doc-/does-handler
1.5 anton 5025:
1.26 ! crook 5026: The code addresses produced by various defining words are produced by
! 5027: the following words:
1.5 anton 5028:
1.26 ! crook 5029: doc-docol:
! 5030: doc-docon:
! 5031: doc-dovar:
! 5032: doc-douser:
! 5033: doc-dodefer:
! 5034: doc-dofield:
1.5 anton 5035:
1.26 ! crook 5036: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
! 5037: with @code{>does-code}. If the word was defined in that way, the value
! 5038: returned is non-zero and identifies the @code{DOES>} used by the
! 5039: defining word.
! 5040: @comment TODO should that be ``identifies the xt of the DOES> ??''
1.5 anton 5041:
1.26 ! crook 5042: @c -------------------------------------------------------------
! 5043: @node Locals, Structures, Threading Words, Words
! 5044: @section Locals
! 5045: @cindex locals
1.5 anton 5046:
1.26 ! crook 5047: Local variables can make Forth programming more enjoyable and Forth
! 5048: programs easier to read. Unfortunately, the locals of ANS Forth are
! 5049: laden with restrictions. Therefore, we provide not only the ANS Forth
! 5050: locals wordset, but also our own, more powerful locals wordset (we
! 5051: implemented the ANS Forth locals wordset through our locals wordset).
1.5 anton 5052:
1.26 ! crook 5053: The ideas in this section have also been published in the paper
! 5054: @cite{Automatic Scoping of Local Variables} by M. Anton Ertl, presented
! 5055: at EuroForth '94; it is available at
! 5056: @*@url{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz}.
1.5 anton 5057:
1.26 ! crook 5058: @menu
! 5059: * Gforth locals::
! 5060: * ANS Forth locals::
! 5061: @end menu
1.5 anton 5062:
1.26 ! crook 5063: @node Gforth locals, ANS Forth locals, Locals, Locals
! 5064: @subsection Gforth locals
! 5065: @cindex Gforth locals
! 5066: @cindex locals, Gforth style
1.5 anton 5067:
1.26 ! crook 5068: Locals can be defined with
1.5 anton 5069:
5070: @example
1.26 ! crook 5071: @{ local1 local2 ... -- comment @}
! 5072: @end example
! 5073: or
! 5074: @example
! 5075: @{ local1 local2 ... @}
1.5 anton 5076: @end example
5077:
1.26 ! crook 5078: E.g.,
1.5 anton 5079: @example
1.26 ! crook 5080: : max @{ n1 n2 -- n3 @}
! 5081: n1 n2 > if
! 5082: n1
! 5083: else
! 5084: n2
! 5085: endif ;
1.5 anton 5086: @end example
5087:
1.26 ! crook 5088: The similarity of locals definitions with stack comments is intended. A
! 5089: locals definition often replaces the stack comment of a word. The order
! 5090: of the locals corresponds to the order in a stack comment and everything
! 5091: after the @code{--} is really a comment.
1.5 anton 5092:
1.26 ! crook 5093: This similarity has one disadvantage: It is too easy to confuse locals
! 5094: declarations with stack comments, causing bugs and making them hard to
! 5095: find. However, this problem can be avoided by appropriate coding
! 5096: conventions: Do not use both notations in the same program. If you do,
! 5097: they should be distinguished using additional means, e.g. by position.
! 5098:
! 5099: @cindex types of locals
! 5100: @cindex locals types
! 5101: The name of the local may be preceded by a type specifier, e.g.,
! 5102: @code{F:} for a floating point value:
! 5103:
! 5104: @example
! 5105: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
! 5106: \ complex multiplication
! 5107: Ar Br f* Ai Bi f* f-
! 5108: Ar Bi f* Ai Br f* f+ ;
! 5109: @end example
! 5110:
! 5111: @cindex flavours of locals
! 5112: @cindex locals flavours
! 5113: @cindex value-flavoured locals
! 5114: @cindex variable-flavoured locals
! 5115: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
! 5116: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
! 5117: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
! 5118: with @code{W:}, @code{D:} etc.) produces its value and can be changed
! 5119: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
! 5120: produces its address (which becomes invalid when the variable's scope is
! 5121: left). E.g., the standard word @code{emit} can be defined in terms of
! 5122: @code{type} like this:
1.5 anton 5123:
5124: @example
1.26 ! crook 5125: : emit @{ C^ char* -- @}
! 5126: char* 1 type ;
1.5 anton 5127: @end example
5128:
1.26 ! crook 5129: @cindex default type of locals
! 5130: @cindex locals, default type
! 5131: A local without type specifier is a @code{W:} local. Both flavours of
! 5132: locals are initialized with values from the data or FP stack.
1.5 anton 5133:
1.26 ! crook 5134: Currently there is no way to define locals with user-defined data
! 5135: structures, but we are working on it.
1.5 anton 5136:
1.26 ! crook 5137: Gforth allows defining locals everywhere in a colon definition. This
! 5138: poses the following questions:
1.5 anton 5139:
1.26 ! crook 5140: @menu
! 5141: * Where are locals visible by name?::
! 5142: * How long do locals live?::
! 5143: * Programming Style::
! 5144: * Implementation::
! 5145: @end menu
1.5 anton 5146:
1.26 ! crook 5147: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
! 5148: @subsubsection Where are locals visible by name?
! 5149: @cindex locals visibility
! 5150: @cindex visibility of locals
! 5151: @cindex scope of locals
1.5 anton 5152:
1.26 ! crook 5153: Basically, the answer is that locals are visible where you would expect
! 5154: it in block-structured languages, and sometimes a little longer. If you
! 5155: want to restrict the scope of a local, enclose its definition in
! 5156: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 5157:
1.26 ! crook 5158: doc-scope
! 5159: doc-endscope
1.5 anton 5160:
1.26 ! crook 5161: These words behave like control structure words, so you can use them
! 5162: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
! 5163: arbitrary ways.
1.5 anton 5164:
1.26 ! crook 5165: If you want a more exact answer to the visibility question, here's the
! 5166: basic principle: A local is visible in all places that can only be
! 5167: reached through the definition of the local@footnote{In compiler
! 5168: construction terminology, all places dominated by the definition of the
! 5169: local.}. In other words, it is not visible in places that can be reached
! 5170: without going through the definition of the local. E.g., locals defined
! 5171: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
! 5172: defined in @code{BEGIN}...@code{UNTIL} are visible after the
! 5173: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.5 anton 5174:
1.26 ! crook 5175: The reasoning behind this solution is: We want to have the locals
! 5176: visible as long as it is meaningful. The user can always make the
! 5177: visibility shorter by using explicit scoping. In a place that can
! 5178: only be reached through the definition of a local, the meaning of a
! 5179: local name is clear. In other places it is not: How is the local
! 5180: initialized at the control flow path that does not contain the
! 5181: definition? Which local is meant, if the same name is defined twice in
! 5182: two independent control flow paths?
1.5 anton 5183:
1.26 ! crook 5184: This should be enough detail for nearly all users, so you can skip the
! 5185: rest of this section. If you really must know all the gory details and
! 5186: options, read on.
1.5 anton 5187:
1.26 ! crook 5188: In order to implement this rule, the compiler has to know which places
! 5189: are unreachable. It knows this automatically after @code{AHEAD},
! 5190: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
! 5191: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
! 5192: compiler that the control flow never reaches that place. If
! 5193: @code{UNREACHABLE} is not used where it could, the only consequence is
! 5194: that the visibility of some locals is more limited than the rule above
! 5195: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
! 5196: lie to the compiler), buggy code will be produced.
1.5 anton 5197:
1.26 ! crook 5198: doc-unreachable
1.5 anton 5199:
1.26 ! crook 5200: Another problem with this rule is that at @code{BEGIN}, the compiler
! 5201: does not know which locals will be visible on the incoming
! 5202: back-edge. All problems discussed in the following are due to this
! 5203: ignorance of the compiler (we discuss the problems using @code{BEGIN}
! 5204: loops as examples; the discussion also applies to @code{?DO} and other
! 5205: loops). Perhaps the most insidious example is:
1.5 anton 5206: @example
1.26 ! crook 5207: AHEAD
! 5208: BEGIN
! 5209: x
! 5210: [ 1 CS-ROLL ] THEN
! 5211: @{ x @}
! 5212: ...
! 5213: UNTIL
! 5214: @end example
1.5 anton 5215:
1.26 ! crook 5216: This should be legal according to the visibility rule. The use of
! 5217: @code{x} can only be reached through the definition; but that appears
! 5218: textually below the use.
1.5 anton 5219:
1.26 ! crook 5220: From this example it is clear that the visibility rules cannot be fully
! 5221: implemented without major headaches. Our implementation treats common
! 5222: cases as advertised and the exceptions are treated in a safe way: The
! 5223: compiler makes a reasonable guess about the locals visible after a
! 5224: @code{BEGIN}; if it is too pessimistic, the
! 5225: user will get a spurious error about the local not being defined; if the
! 5226: compiler is too optimistic, it will notice this later and issue a
! 5227: warning. In the case above the compiler would complain about @code{x}
! 5228: being undefined at its use. You can see from the obscure examples in
! 5229: this section that it takes quite unusual control structures to get the
! 5230: compiler into trouble, and even then it will often do fine.
1.5 anton 5231:
1.26 ! crook 5232: If the @code{BEGIN} is reachable from above, the most optimistic guess
! 5233: is that all locals visible before the @code{BEGIN} will also be
! 5234: visible after the @code{BEGIN}. This guess is valid for all loops that
! 5235: are entered only through the @code{BEGIN}, in particular, for normal
! 5236: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
! 5237: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
! 5238: compiler. When the branch to the @code{BEGIN} is finally generated by
! 5239: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
! 5240: warns the user if it was too optimistic:
! 5241: @example
! 5242: IF
! 5243: @{ x @}
! 5244: BEGIN
! 5245: \ x ?
! 5246: [ 1 cs-roll ] THEN
! 5247: ...
! 5248: UNTIL
1.5 anton 5249: @end example
5250:
1.26 ! crook 5251: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
! 5252: optimistically assumes that it lives until the @code{THEN}. It notices
! 5253: this difference when it compiles the @code{UNTIL} and issues a
! 5254: warning. The user can avoid the warning, and make sure that @code{x}
! 5255: is not used in the wrong area by using explicit scoping:
! 5256: @example
! 5257: IF
! 5258: SCOPE
! 5259: @{ x @}
! 5260: ENDSCOPE
! 5261: BEGIN
! 5262: [ 1 cs-roll ] THEN
! 5263: ...
! 5264: UNTIL
! 5265: @end example
1.5 anton 5266:
1.26 ! crook 5267: Since the guess is optimistic, there will be no spurious error messages
! 5268: about undefined locals.
1.5 anton 5269:
1.26 ! crook 5270: If the @code{BEGIN} is not reachable from above (e.g., after
! 5271: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
! 5272: optimistic guess, as the locals visible after the @code{BEGIN} may be
! 5273: defined later. Therefore, the compiler assumes that no locals are
! 5274: visible after the @code{BEGIN}. However, the user can use
! 5275: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
! 5276: visible at the BEGIN as at the point where the top control-flow stack
! 5277: item was created.
1.5 anton 5278:
1.26 ! crook 5279: doc-assume-live
1.5 anton 5280:
1.26 ! crook 5281: E.g.,
1.5 anton 5282: @example
1.26 ! crook 5283: @{ x @}
! 5284: AHEAD
! 5285: ASSUME-LIVE
! 5286: BEGIN
! 5287: x
! 5288: [ 1 CS-ROLL ] THEN
! 5289: ...
! 5290: UNTIL
1.5 anton 5291: @end example
5292:
1.26 ! crook 5293: Other cases where the locals are defined before the @code{BEGIN} can be
! 5294: handled by inserting an appropriate @code{CS-ROLL} before the
! 5295: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
! 5296: behind the @code{ASSUME-LIVE}).
1.5 anton 5297:
1.26 ! crook 5298: Cases where locals are defined after the @code{BEGIN} (but should be
! 5299: visible immediately after the @code{BEGIN}) can only be handled by
! 5300: rearranging the loop. E.g., the ``most insidious'' example above can be
! 5301: arranged into:
1.5 anton 5302: @example
1.26 ! crook 5303: BEGIN
! 5304: @{ x @}
! 5305: ... 0=
! 5306: WHILE
! 5307: x
! 5308: REPEAT
1.5 anton 5309: @end example
5310:
1.26 ! crook 5311: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
! 5312: @subsubsection How long do locals live?
! 5313: @cindex locals lifetime
! 5314: @cindex lifetime of locals
1.5 anton 5315:
1.26 ! crook 5316: The right answer for the lifetime question would be: A local lives at
! 5317: least as long as it can be accessed. For a value-flavoured local this
! 5318: means: until the end of its visibility. However, a variable-flavoured
! 5319: local could be accessed through its address far beyond its visibility
! 5320: scope. Ultimately, this would mean that such locals would have to be
! 5321: garbage collected. Since this entails un-Forth-like implementation
! 5322: complexities, I adopted the same cowardly solution as some other
! 5323: languages (e.g., C): The local lives only as long as it is visible;
! 5324: afterwards its address is invalid (and programs that access it
! 5325: afterwards are erroneous).
1.5 anton 5326:
1.26 ! crook 5327: @node Programming Style, Implementation, How long do locals live?, Gforth locals
! 5328: @subsubsection Programming Style
! 5329: @cindex locals programming style
! 5330: @cindex programming style, locals
1.5 anton 5331:
1.26 ! crook 5332: The freedom to define locals anywhere has the potential to change
! 5333: programming styles dramatically. In particular, the need to use the
! 5334: return stack for intermediate storage vanishes. Moreover, all stack
! 5335: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
! 5336: determined arguments) can be eliminated: If the stack items are in the
! 5337: wrong order, just write a locals definition for all of them; then
! 5338: write the items in the order you want.
1.5 anton 5339:
1.26 ! crook 5340: This seems a little far-fetched and eliminating stack manipulations is
! 5341: unlikely to become a conscious programming objective. Still, the number
! 5342: of stack manipulations will be reduced dramatically if local variables
! 5343: are used liberally (e.g., compare @code{max} in @ref{Gforth locals} with
! 5344: a traditional implementation of @code{max}).
1.5 anton 5345:
1.26 ! crook 5346: This shows one potential benefit of locals: making Forth programs more
! 5347: readable. Of course, this benefit will only be realized if the
! 5348: programmers continue to honour the principle of factoring instead of
! 5349: using the added latitude to make the words longer.
1.5 anton 5350:
1.26 ! crook 5351: @cindex single-assignment style for locals
! 5352: Using @code{TO} can and should be avoided. Without @code{TO},
! 5353: every value-flavoured local has only a single assignment and many
! 5354: advantages of functional languages apply to Forth. I.e., programs are
! 5355: easier to analyse, to optimize and to read: It is clear from the
! 5356: definition what the local stands for, it does not turn into something
! 5357: different later.
1.5 anton 5358:
1.26 ! crook 5359: E.g., a definition using @code{TO} might look like this:
1.5 anton 5360: @example
1.26 ! crook 5361: : strcmp @{ addr1 u1 addr2 u2 -- n @}
! 5362: u1 u2 min 0
! 5363: ?do
! 5364: addr1 c@@ addr2 c@@ -
! 5365: ?dup-if
! 5366: unloop exit
! 5367: then
! 5368: addr1 char+ TO addr1
! 5369: addr2 char+ TO addr2
! 5370: loop
! 5371: u1 u2 - ;
1.5 anton 5372: @end example
1.26 ! crook 5373: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
! 5374: every loop iteration. @code{strcmp} is a typical example of the
! 5375: readability problems of using @code{TO}. When you start reading
! 5376: @code{strcmp}, you think that @code{addr1} refers to the start of the
! 5377: string. Only near the end of the loop you realize that it is something
! 5378: else.
1.5 anton 5379:
1.26 ! crook 5380: This can be avoided by defining two locals at the start of the loop that
! 5381: are initialized with the right value for the current iteration.
1.5 anton 5382: @example
1.26 ! crook 5383: : strcmp @{ addr1 u1 addr2 u2 -- n @}
! 5384: addr1 addr2
! 5385: u1 u2 min 0
! 5386: ?do @{ s1 s2 @}
! 5387: s1 c@@ s2 c@@ -
! 5388: ?dup-if
! 5389: unloop exit
! 5390: then
! 5391: s1 char+ s2 char+
! 5392: loop
! 5393: 2drop
! 5394: u1 u2 - ;
1.5 anton 5395: @end example
1.26 ! crook 5396: Here it is clear from the start that @code{s1} has a different value
! 5397: in every loop iteration.
1.5 anton 5398:
1.26 ! crook 5399: @node Implementation, , Programming Style, Gforth locals
! 5400: @subsubsection Implementation
! 5401: @cindex locals implementation
! 5402: @cindex implementation of locals
1.5 anton 5403:
1.26 ! crook 5404: @cindex locals stack
! 5405: Gforth uses an extra locals stack. The most compelling reason for
! 5406: this is that the return stack is not float-aligned; using an extra stack
! 5407: also eliminates the problems and restrictions of using the return stack
! 5408: as locals stack. Like the other stacks, the locals stack grows toward
! 5409: lower addresses. A few primitives allow an efficient implementation:
1.5 anton 5410:
1.26 ! crook 5411: doc-@local#
! 5412: doc-f@local#
! 5413: doc-laddr#
! 5414: doc-lp+!#
! 5415: doc-lp!
! 5416: doc->l
! 5417: doc-f>l
1.5 anton 5418:
1.26 ! crook 5419: In addition to these primitives, some specializations of these
! 5420: primitives for commonly occurring inline arguments are provided for
! 5421: efficiency reasons, e.g., @code{@@local0} as specialization of
! 5422: @code{@@local#} for the inline argument 0. The following compiling words
! 5423: compile the right specialized version, or the general version, as
! 5424: appropriate:
1.6 pazsan 5425:
1.26 ! crook 5426: doc-compile-@local
! 5427: doc-compile-f@local
! 5428: doc-compile-lp+!
1.12 anton 5429:
1.26 ! crook 5430: Combinations of conditional branches and @code{lp+!#} like
! 5431: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
! 5432: is taken) are provided for efficiency and correctness in loops.
1.6 pazsan 5433:
1.26 ! crook 5434: A special area in the dictionary space is reserved for keeping the
! 5435: local variable names. @code{@{} switches the dictionary pointer to this
! 5436: area and @code{@}} switches it back and generates the locals
! 5437: initializing code. @code{W:} etc.@ are normal defining words. This
! 5438: special area is cleared at the start of every colon definition.
1.6 pazsan 5439:
1.26 ! crook 5440: @cindex word list for defining locals
! 5441: A special feature of Gforth's dictionary is used to implement the
! 5442: definition of locals without type specifiers: every word list (aka
! 5443: vocabulary) has its own methods for searching
! 5444: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
! 5445: with a special search method: When it is searched for a word, it
! 5446: actually creates that word using @code{W:}. @code{@{} changes the search
! 5447: order to first search the word list containing @code{@}}, @code{W:} etc.,
! 5448: and then the word list for defining locals without type specifiers.
1.12 anton 5449:
1.26 ! crook 5450: The lifetime rules support a stack discipline within a colon
! 5451: definition: The lifetime of a local is either nested with other locals
! 5452: lifetimes or it does not overlap them.
1.6 pazsan 5453:
1.26 ! crook 5454: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
! 5455: pointer manipulation is generated. Between control structure words
! 5456: locals definitions can push locals onto the locals stack. @code{AGAIN}
! 5457: is the simplest of the other three control flow words. It has to
! 5458: restore the locals stack depth of the corresponding @code{BEGIN}
! 5459: before branching. The code looks like this:
! 5460: @format
! 5461: @code{lp+!#} current-locals-size @minus{} dest-locals-size
! 5462: @code{branch} <begin>
! 5463: @end format
1.6 pazsan 5464:
1.26 ! crook 5465: @code{UNTIL} is a little more complicated: If it branches back, it
! 5466: must adjust the stack just like @code{AGAIN}. But if it falls through,
! 5467: the locals stack must not be changed. The compiler generates the
! 5468: following code:
! 5469: @format
! 5470: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
! 5471: @end format
! 5472: The locals stack pointer is only adjusted if the branch is taken.
1.6 pazsan 5473:
1.26 ! crook 5474: @code{THEN} can produce somewhat inefficient code:
! 5475: @format
! 5476: @code{lp+!#} current-locals-size @minus{} orig-locals-size
! 5477: <orig target>:
! 5478: @code{lp+!#} orig-locals-size @minus{} new-locals-size
! 5479: @end format
! 5480: The second @code{lp+!#} adjusts the locals stack pointer from the
! 5481: level at the @var{orig} point to the level after the @code{THEN}. The
! 5482: first @code{lp+!#} adjusts the locals stack pointer from the current
! 5483: level to the level at the orig point, so the complete effect is an
! 5484: adjustment from the current level to the right level after the
! 5485: @code{THEN}.
1.6 pazsan 5486:
1.26 ! crook 5487: @cindex locals information on the control-flow stack
! 5488: @cindex control-flow stack items, locals information
! 5489: In a conventional Forth implementation a dest control-flow stack entry
! 5490: is just the target address and an orig entry is just the address to be
! 5491: patched. Our locals implementation adds a word list to every orig or dest
! 5492: item. It is the list of locals visible (or assumed visible) at the point
! 5493: described by the entry. Our implementation also adds a tag to identify
! 5494: the kind of entry, in particular to differentiate between live and dead
! 5495: (reachable and unreachable) orig entries.
1.6 pazsan 5496:
1.26 ! crook 5497: A few unusual operations have to be performed on locals word lists:
1.6 pazsan 5498:
1.26 ! crook 5499: doc-common-list
! 5500: doc-sub-list?
! 5501: doc-list-size
1.6 pazsan 5502:
1.26 ! crook 5503: Several features of our locals word list implementation make these
! 5504: operations easy to implement: The locals word lists are organised as
! 5505: linked lists; the tails of these lists are shared, if the lists
! 5506: contain some of the same locals; and the address of a name is greater
! 5507: than the address of the names behind it in the list.
1.6 pazsan 5508:
1.26 ! crook 5509: Another important implementation detail is the variable
! 5510: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
! 5511: determine if they can be reached directly or only through the branch
! 5512: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
! 5513: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
! 5514: definition, by @code{BEGIN} and usually by @code{THEN}.
1.6 pazsan 5515:
1.26 ! crook 5516: Counted loops are similar to other loops in most respects, but
! 5517: @code{LEAVE} requires special attention: It performs basically the same
! 5518: service as @code{AHEAD}, but it does not create a control-flow stack
! 5519: entry. Therefore the information has to be stored elsewhere;
! 5520: traditionally, the information was stored in the target fields of the
! 5521: branches created by the @code{LEAVE}s, by organizing these fields into a
! 5522: linked list. Unfortunately, this clever trick does not provide enough
! 5523: space for storing our extended control flow information. Therefore, we
! 5524: introduce another stack, the leave stack. It contains the control-flow
! 5525: stack entries for all unresolved @code{LEAVE}s.
1.6 pazsan 5526:
1.26 ! crook 5527: Local names are kept until the end of the colon definition, even if
! 5528: they are no longer visible in any control-flow path. In a few cases
! 5529: this may lead to increased space needs for the locals name area, but
! 5530: usually less than reclaiming this space would cost in code size.
1.6 pazsan 5531:
5532:
1.26 ! crook 5533: @node ANS Forth locals, , Gforth locals, Locals
! 5534: @subsection ANS Forth locals
! 5535: @cindex locals, ANS Forth style
1.6 pazsan 5536:
1.26 ! crook 5537: The ANS Forth locals wordset does not define a syntax for locals, but
! 5538: words that make it possible to define various syntaxes. One of the
! 5539: possible syntaxes is a subset of the syntax we used in the Gforth locals
! 5540: wordset, i.e.:
1.6 pazsan 5541:
5542: @example
1.26 ! crook 5543: @{ local1 local2 ... -- comment @}
1.6 pazsan 5544: @end example
1.23 crook 5545: @noindent
1.26 ! crook 5546: or
1.6 pazsan 5547: @example
1.26 ! crook 5548: @{ local1 local2 ... @}
1.6 pazsan 5549: @end example
5550:
1.26 ! crook 5551: The order of the locals corresponds to the order in a stack comment. The
! 5552: restrictions are:
1.6 pazsan 5553:
5554: @itemize @bullet
5555: @item
1.26 ! crook 5556: Locals can only be cell-sized values (no type specifiers are allowed).
1.6 pazsan 5557: @item
1.26 ! crook 5558: Locals can be defined only outside control structures.
1.6 pazsan 5559: @item
1.26 ! crook 5560: Locals can interfere with explicit usage of the return stack. For the
! 5561: exact (and long) rules, see the standard. If you don't use return stack
! 5562: accessing words in a definition using locals, you will be all right. The
! 5563: purpose of this rule is to make locals implementation on the return
! 5564: stack easier.
1.6 pazsan 5565: @item
1.26 ! crook 5566: The whole definition must be in one line.
! 5567: @end itemize
1.6 pazsan 5568:
1.26 ! crook 5569: Locals defined in this way behave like @code{VALUE}s (@xref{Simple
! 5570: Defining Words}). I.e., they are initialized from the stack. Using their
! 5571: name produces their value. Their value can be changed using @code{TO}.
1.6 pazsan 5572:
1.26 ! crook 5573: Since this syntax is supported by Gforth directly, you need not do
! 5574: anything to use it. If you want to port a program using this syntax to
! 5575: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
! 5576: syntax on the other system.
1.6 pazsan 5577:
1.26 ! crook 5578: Note that a syntax shown in the standard, section A.13 looks
! 5579: similar, but is quite different in having the order of locals
! 5580: reversed. Beware!
1.6 pazsan 5581:
1.26 ! crook 5582: The ANS Forth locals wordset itself consists of a word:
1.6 pazsan 5583:
1.26 ! crook 5584: doc-(local)
1.6 pazsan 5585:
1.26 ! crook 5586: The ANS Forth locals extension wordset defines a syntax using @code{locals|}, but it is so
! 5587: awful that we strongly recommend not to use it. We have implemented this
! 5588: syntax to make porting to Gforth easy, but do not document it here. The
! 5589: problem with this syntax is that the locals are defined in an order
! 5590: reversed with respect to the standard stack comment notation, making
! 5591: programs harder to read, and easier to misread and miswrite. The only
! 5592: merit of this syntax is that it is easy to implement using the ANS Forth
! 5593: locals wordset.
1.7 pazsan 5594:
5595:
1.26 ! crook 5596: @c ----------------------------------------------------------
! 5597: @node Structures, Object-oriented Forth, Locals, Words
! 5598: @section Structures
! 5599: @cindex structures
! 5600: @cindex records
1.7 pazsan 5601:
1.26 ! crook 5602: This section presents the structure package that comes with Gforth. A
! 5603: version of the package implemented in ANS Forth is available in
! 5604: @file{compat/struct.fs}. This package was inspired by a posting on
! 5605: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
! 5606: possibly John Hayes). A version of this section has been published in
! 5607: ???. Marcel Hendrix provided helpful comments.
1.7 pazsan 5608:
1.26 ! crook 5609: @menu
! 5610: * Why explicit structure support?::
! 5611: * Structure Usage::
! 5612: * Structure Naming Convention::
! 5613: * Structure Implementation::
! 5614: * Structure Glossary::
! 5615: @end menu
1.7 pazsan 5616:
1.26 ! crook 5617: @node Why explicit structure support?, Structure Usage, Structures, Structures
! 5618: @subsection Why explicit structure support?
1.7 pazsan 5619:
1.26 ! crook 5620: @cindex address arithmetic for structures
! 5621: @cindex structures using address arithmetic
! 5622: If we want to use a structure containing several fields, we could simply
! 5623: reserve memory for it, and access the fields using address arithmetic
! 5624: (@pxref{Address arithmetic}). As an example, consider a structure with
! 5625: the following fields
1.7 pazsan 5626:
1.26 ! crook 5627: @table @code
! 5628: @item a
! 5629: is a float
! 5630: @item b
! 5631: is a cell
! 5632: @item c
! 5633: is a float
! 5634: @end table
1.7 pazsan 5635:
1.26 ! crook 5636: Given the (float-aligned) base address of the structure we get the
! 5637: address of the field
1.13 pazsan 5638:
1.26 ! crook 5639: @table @code
! 5640: @item a
! 5641: without doing anything further.
! 5642: @item b
! 5643: with @code{float+}
! 5644: @item c
! 5645: with @code{float+ cell+ faligned}
! 5646: @end table
1.13 pazsan 5647:
1.26 ! crook 5648: It is easy to see that this can become quite tiring.
1.13 pazsan 5649:
1.26 ! crook 5650: Moreover, it is not very readable, because seeing a
! 5651: @code{cell+} tells us neither which kind of structure is
! 5652: accessed nor what field is accessed; we have to somehow infer the kind
! 5653: of structure, and then look up in the documentation, which field of
! 5654: that structure corresponds to that offset.
1.13 pazsan 5655:
1.26 ! crook 5656: Finally, this kind of address arithmetic also causes maintenance
! 5657: troubles: If you add or delete a field somewhere in the middle of the
! 5658: structure, you have to find and change all computations for the fields
! 5659: afterwards.
1.13 pazsan 5660:
1.26 ! crook 5661: So, instead of using @code{cell+} and friends directly, how
! 5662: about storing the offsets in constants:
1.13 pazsan 5663:
5664: @example
1.26 ! crook 5665: 0 constant a-offset
! 5666: 0 float+ constant b-offset
! 5667: 0 float+ cell+ faligned c-offset
1.13 pazsan 5668: @end example
5669:
1.26 ! crook 5670: Now we can get the address of field @code{x} with @code{x-offset
! 5671: +}. This is much better in all respects. Of course, you still
! 5672: have to change all later offset definitions if you add a field. You can
! 5673: fix this by declaring the offsets in the following way:
1.13 pazsan 5674:
5675: @example
1.26 ! crook 5676: 0 constant a-offset
! 5677: a-offset float+ constant b-offset
! 5678: b-offset cell+ faligned constant c-offset
1.13 pazsan 5679: @end example
5680:
1.26 ! crook 5681: Since we always use the offsets with @code{+}, we could use a defining
! 5682: word @code{cfield} that includes the @code{+} in the action of the
! 5683: defined word:
1.8 pazsan 5684:
5685: @example
1.26 ! crook 5686: : cfield ( n "name" -- )
! 5687: create ,
! 5688: does> ( name execution: addr1 -- addr2 )
! 5689: @@ + ;
1.13 pazsan 5690:
1.26 ! crook 5691: 0 cfield a
! 5692: 0 a float+ cfield b
! 5693: 0 b cell+ faligned cfield c
1.13 pazsan 5694: @end example
5695:
1.26 ! crook 5696: Instead of @code{x-offset +}, we now simply write @code{x}.
! 5697:
! 5698: The structure field words now can be used quite nicely. However,
! 5699: their definition is still a bit cumbersome: We have to repeat the
! 5700: name, the information about size and alignment is distributed before
! 5701: and after the field definitions etc. The structure package presented
! 5702: here addresses these problems.
! 5703:
! 5704: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
! 5705: @subsection Structure Usage
! 5706: @cindex structure usage
1.13 pazsan 5707:
1.26 ! crook 5708: @cindex @code{field} usage
! 5709: @cindex @code{struct} usage
! 5710: @cindex @code{end-struct} usage
! 5711: You can define a structure for a (data-less) linked list with:
1.13 pazsan 5712: @example
1.26 ! crook 5713: struct
! 5714: cell% field list-next
! 5715: end-struct list%
1.13 pazsan 5716: @end example
5717:
1.26 ! crook 5718: With the address of the list node on the stack, you can compute the
! 5719: address of the field that contains the address of the next node with
! 5720: @code{list-next}. E.g., you can determine the length of a list
! 5721: with:
1.13 pazsan 5722:
5723: @example
1.26 ! crook 5724: : list-length ( list -- n )
! 5725: \ "list" is a pointer to the first element of a linked list
! 5726: \ "n" is the length of the list
! 5727: 0 BEGIN ( list1 n1 )
! 5728: over
! 5729: WHILE ( list1 n1 )
! 5730: 1+ swap list-next @@ swap
! 5731: REPEAT
! 5732: nip ;
1.13 pazsan 5733: @end example
5734:
1.26 ! crook 5735: You can reserve memory for a list node in the dictionary with
! 5736: @code{list% %allot}, which leaves the address of the list node on the
! 5737: stack. For the equivalent allocation on the heap you can use @code{list%
! 5738: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
! 5739: use @code{list% %allocate}). You can get the the size of a list
! 5740: node with @code{list% %size} and its alignment with @code{list%
! 5741: %alignment}.
1.13 pazsan 5742:
1.26 ! crook 5743: Note that in ANS Forth the body of a @code{create}d word is
! 5744: @code{aligned} but not necessarily @code{faligned};
! 5745: therefore, if you do a:
1.13 pazsan 5746: @example
1.26 ! crook 5747: create @emph{name} foo% %allot
1.8 pazsan 5748: @end example
5749:
1.26 ! crook 5750: @noindent
! 5751: then the memory alloted for @code{foo%} is
! 5752: guaranteed to start at the body of @code{@emph{name}} only if
! 5753: @code{foo%} contains only character, cell and double fields.
1.20 pazsan 5754:
1.26 ! crook 5755: @cindex strcutures containing structures
! 5756: You can include a structure @code{foo%} as a field of
! 5757: another structure, like this:
1.20 pazsan 5758: @example
1.26 ! crook 5759: struct
! 5760: ...
! 5761: foo% field ...
! 5762: ...
! 5763: end-struct ...
1.20 pazsan 5764: @end example
5765:
1.26 ! crook 5766: @cindex structure extension
! 5767: @cindex extended records
! 5768: Instead of starting with an empty structure, you can extend an
! 5769: existing structure. E.g., a plain linked list without data, as defined
! 5770: above, is hardly useful; You can extend it to a linked list of integers,
! 5771: like this:@footnote{This feature is also known as @emph{extended
! 5772: records}. It is the main innovation in the Oberon language; in other
! 5773: words, adding this feature to Modula-2 led Wirth to create a new
! 5774: language, write a new compiler etc. Adding this feature to Forth just
! 5775: required a few lines of code.}
1.20 pazsan 5776:
5777: @example
1.26 ! crook 5778: list%
! 5779: cell% field intlist-int
! 5780: end-struct intlist%
1.20 pazsan 5781: @end example
5782:
1.26 ! crook 5783: @code{intlist%} is a structure with two fields:
! 5784: @code{list-next} and @code{intlist-int}.
1.20 pazsan 5785:
1.26 ! crook 5786: @cindex structures containing arrays
! 5787: You can specify an array type containing @emph{n} elements of
! 5788: type @code{foo%} like this:
1.20 pazsan 5789:
5790: @example
1.26 ! crook 5791: foo% @emph{n} *
1.20 pazsan 5792: @end example
5793:
1.26 ! crook 5794: You can use this array type in any place where you can use a normal
! 5795: type, e.g., when defining a @code{field}, or with
! 5796: @code{%allot}.
1.20 pazsan 5797:
1.26 ! crook 5798: @cindex first field optimization
! 5799: The first field is at the base address of a structure and the word
! 5800: for this field (e.g., @code{list-next}) actually does not change
! 5801: the address on the stack. You may be tempted to leave it away in the
! 5802: interest of run-time and space efficiency. This is not necessary,
! 5803: because the structure package optimizes this case and compiling such
! 5804: words does not generate any code. So, in the interest of readability
! 5805: and maintainability you should include the word for the field when
! 5806: accessing the field.
1.20 pazsan 5807:
1.26 ! crook 5808: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
! 5809: @subsection Structure Naming Convention
! 5810: @cindex structure naming convention
1.20 pazsan 5811:
1.26 ! crook 5812: The field names that come to (my) mind are often quite generic, and,
! 5813: if used, would cause frequent name clashes. E.g., many structures
! 5814: probably contain a @code{counter} field. The structure names
! 5815: that come to (my) mind are often also the logical choice for the names
! 5816: of words that create such a structure.
1.20 pazsan 5817:
1.26 ! crook 5818: Therefore, I have adopted the following naming conventions:
1.20 pazsan 5819:
1.26 ! crook 5820: @itemize @bullet
! 5821: @cindex field naming convention
! 5822: @item
! 5823: The names of fields are of the form
! 5824: @code{@emph{struct}-@emph{field}}, where
! 5825: @code{@emph{struct}} is the basic name of the structure, and
! 5826: @code{@emph{field}} is the basic name of the field. You can
! 5827: think of field words as converting the (address of the)
! 5828: structure into the (address of the) field.
1.20 pazsan 5829:
1.26 ! crook 5830: @cindex structure naming convention
! 5831: @item
! 5832: The names of structures are of the form
! 5833: @code{@emph{struct}%}, where
! 5834: @code{@emph{struct}} is the basic name of the structure.
! 5835: @end itemize
1.20 pazsan 5836:
1.26 ! crook 5837: This naming convention does not work that well for fields of extended
! 5838: structures; e.g., the integer list structure has a field
! 5839: @code{intlist-int}, but has @code{list-next}, not
! 5840: @code{intlist-next}.
1.20 pazsan 5841:
1.26 ! crook 5842: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
! 5843: @subsection Structure Implementation
! 5844: @cindex structure implementation
! 5845: @cindex implementation of structures
1.20 pazsan 5846:
1.26 ! crook 5847: The central idea in the implementation is to pass the data about the
! 5848: structure being built on the stack, not in some global
! 5849: variable. Everything else falls into place naturally once this design
! 5850: decision is made.
1.20 pazsan 5851:
1.26 ! crook 5852: The type description on the stack is of the form @emph{align
! 5853: size}. Keeping the size on the top-of-stack makes dealing with arrays
! 5854: very simple.
1.20 pazsan 5855:
1.26 ! crook 5856: @code{field} is a defining word that uses @code{Create}
! 5857: and @code{DOES>}. The body of the field contains the offset
! 5858: of the field, and the normal @code{DOES>} action is simply:
1.20 pazsan 5859:
5860: @example
1.26 ! crook 5861: @ +
1.20 pazsan 5862: @end example
5863:
1.23 crook 5864: @noindent
1.26 ! crook 5865: i.e., add the offset to the address, giving the stack effect
! 5866: @var{addr1 -- addr2} for a field.
1.20 pazsan 5867:
1.26 ! crook 5868: @cindex first field optimization, implementation
! 5869: This simple structure is slightly complicated by the optimization
! 5870: for fields with offset 0, which requires a different
! 5871: @code{DOES>}-part (because we cannot rely on there being
! 5872: something on the stack if such a field is invoked during
! 5873: compilation). Therefore, we put the different @code{DOES>}-parts
! 5874: in separate words, and decide which one to invoke based on the
! 5875: offset. For a zero offset, the field is basically a noop; it is
! 5876: immediate, and therefore no code is generated when it is compiled.
1.20 pazsan 5877:
1.26 ! crook 5878: @node Structure Glossary, , Structure Implementation, Structures
! 5879: @subsection Structure Glossary
! 5880: @cindex structure glossary
1.20 pazsan 5881:
1.26 ! crook 5882: doc-%align
! 5883: doc-%alignment
! 5884: doc-%alloc
! 5885: doc-%allocate
! 5886: doc-%allot
! 5887: doc-cell%
! 5888: doc-char%
! 5889: doc-dfloat%
! 5890: doc-double%
! 5891: doc-end-struct
! 5892: doc-field
! 5893: doc-float%
! 5894: doc-naligned
! 5895: doc-sfloat%
! 5896: doc-%size
! 5897: doc-struct
1.23 crook 5898:
1.26 ! crook 5899: @c -------------------------------------------------------------
! 5900: @node Object-oriented Forth, Passing Commands to the OS, Structures, Words
! 5901: @section Object-oriented Forth
1.20 pazsan 5902:
1.26 ! crook 5903: Gforth comes with three packages for object-oriented programming:
! 5904: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
! 5905: is preloaded, so you have to @code{include} them before use. The most
! 5906: important differences between these packages (and others) are discussed
! 5907: in @ref{Comparison with other object models}. All packages are written
! 5908: in ANS Forth and can be used with any other ANS Forth.
1.20 pazsan 5909:
1.26 ! crook 5910: @menu
! 5911: * Why object-oriented programming?::
! 5912: * Object-Oriented Terminology::
! 5913: * Objects::
! 5914: * OOF::
! 5915: * Mini-OOF::
! 5916: * Comparison with other object models::
! 5917: @end menu
1.20 pazsan 5918:
1.23 crook 5919:
1.26 ! crook 5920: @node Why object-oriented programming?, Object-Oriented Terminology, , Object-oriented Forth
! 5921: @subsubsection Why object-oriented programming?
! 5922: @cindex object-oriented programming motivation
! 5923: @cindex motivation for object-oriented programming
1.23 crook 5924:
1.26 ! crook 5925: Often we have to deal with several data structures (@emph{objects}),
! 5926: that have to be treated similarly in some respects, but differently in
! 5927: others. Graphical objects are the textbook example: circles, triangles,
! 5928: dinosaurs, icons, and others, and we may want to add more during program
! 5929: development. We want to apply some operations to any graphical object,
! 5930: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
! 5931: has to do something different for every kind of object.
! 5932: @comment TODO add some other operations eg perimeter, area
! 5933: @comment and tie in to concrete examples later..
1.23 crook 5934:
1.26 ! crook 5935: We could implement @code{draw} as a big @code{CASE}
! 5936: control structure that executes the appropriate code depending on the
! 5937: kind of object to be drawn. This would be not be very elegant, and,
! 5938: moreover, we would have to change @code{draw} every time we add
! 5939: a new kind of graphical object (say, a spaceship).
1.23 crook 5940:
1.26 ! crook 5941: What we would rather do is: When defining spaceships, we would tell
! 5942: the system: ``Here's how you @code{draw} a spaceship; you figure
! 5943: out the rest''.
1.23 crook 5944:
1.26 ! crook 5945: This is the problem that all systems solve that (rightfully) call
! 5946: themselves object-oriented; the object-oriented packages presented here
! 5947: solve this problem (and not much else).
! 5948: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.23 crook 5949:
1.26 ! crook 5950: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
! 5951: @subsubsection Object-Oriented Terminology
! 5952: @cindex object-oriented terminology
! 5953: @cindex terminology for object-oriented programming
1.23 crook 5954:
1.26 ! crook 5955: This section is mainly for reference, so you don't have to understand
! 5956: all of it right away. The terminology is mainly Smalltalk-inspired. In
! 5957: short:
1.23 crook 5958:
1.26 ! crook 5959: @table @emph
! 5960: @cindex class
! 5961: @item class
! 5962: a data structure definition with some extras.
1.23 crook 5963:
1.26 ! crook 5964: @cindex object
! 5965: @item object
! 5966: an instance of the data structure described by the class definition.
1.23 crook 5967:
1.26 ! crook 5968: @cindex instance variables
! 5969: @item instance variables
! 5970: fields of the data structure.
1.23 crook 5971:
1.26 ! crook 5972: @cindex selector
! 5973: @cindex method selector
! 5974: @cindex virtual function
! 5975: @item selector
! 5976: (or @emph{method selector}) a word (e.g.,
! 5977: @code{draw}) that performs an operation on a variety of data
! 5978: structures (classes). A selector describes @emph{what} operation to
! 5979: perform. In C++ terminology: a (pure) virtual function.
1.23 crook 5980:
1.26 ! crook 5981: @cindex method
! 5982: @item method
! 5983: the concrete definition that performs the operation
! 5984: described by the selector for a specific class. A method specifies
! 5985: @emph{how} the operation is performed for a specific class.
1.23 crook 5986:
1.26 ! crook 5987: @cindex selector invocation
! 5988: @cindex message send
! 5989: @cindex invoking a selector
! 5990: @item selector invocation
! 5991: a call of a selector. One argument of the call (the TOS (top-of-stack))
! 5992: is used for determining which method is used. In Smalltalk terminology:
! 5993: a message (consisting of the selector and the other arguments) is sent
! 5994: to the object.
1.1 anton 5995:
1.26 ! crook 5996: @cindex receiving object
! 5997: @item receiving object
! 5998: the object used for determining the method executed by a selector
! 5999: invocation. In the @file{objects.fs} model, it is the object that is on
! 6000: the TOS when the selector is invoked. (@emph{Receiving} comes from
! 6001: the Smalltalk @emph{message} terminology.)
1.1 anton 6002:
1.26 ! crook 6003: @cindex child class
! 6004: @cindex parent class
! 6005: @cindex inheritance
! 6006: @item child class
! 6007: a class that has (@emph{inherits}) all properties (instance variables,
! 6008: selectors, methods) from a @emph{parent class}. In Smalltalk
! 6009: terminology: The subclass inherits from the superclass. In C++
! 6010: terminology: The derived class inherits from the base class.
1.1 anton 6011:
1.26 ! crook 6012: @end table
1.21 crook 6013:
1.26 ! crook 6014: @c If you wonder about the message sending terminology, it comes from
! 6015: @c a time when each object had it's own task and objects communicated via
! 6016: @c message passing; eventually the Smalltalk developers realized that
! 6017: @c they can do most things through simple (indirect) calls. They kept the
! 6018: @c terminology.
1.1 anton 6019:
6020:
1.26 ! crook 6021: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
! 6022: @subsection The @file{objects.fs} model
! 6023: @cindex objects
! 6024: @cindex object-oriented programming
1.1 anton 6025:
1.26 ! crook 6026: @cindex @file{objects.fs}
! 6027: @cindex @file{oof.fs}
1.1 anton 6028:
1.26 ! crook 6029: 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}).
! 6030: @c McKewan's and Zsoter's packages
1.1 anton 6031:
1.26 ! crook 6032: This section assumes that you have read @ref{Structures}.
1.1 anton 6033:
1.26 ! crook 6034: The techniques on which this model is based have been used to implement
! 6035: the parser generator, Gray, and have also been used in Gforth for
! 6036: implementing the various flavours of word lists (hashed or not,
! 6037: case-sensitive or not, special-purpose word lists for locals etc.).
1.1 anton 6038:
6039:
1.26 ! crook 6040: @menu
! 6041: * Properties of the Objects model::
! 6042: * Basic Objects Usage::
! 6043: * The Objects base class::
! 6044: * Creating objects::
! 6045: * Object-Oriented Programming Style::
! 6046: * Class Binding::
! 6047: * Method conveniences::
! 6048: * Classes and Scoping::
! 6049: * Object Interfaces::
! 6050: * Objects Implementation::
! 6051: * Objects Glossary::
! 6052: @end menu
1.1 anton 6053:
1.26 ! crook 6054: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
! 6055: and Bernd Paysan helped me with the related works section.
1.1 anton 6056:
1.26 ! crook 6057: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
! 6058: @subsubsection Properties of the @file{objects.fs} model
! 6059: @cindex @file{objects.fs} properties
1.1 anton 6060:
1.26 ! crook 6061: @itemize @bullet
! 6062: @item
! 6063: It is straightforward to pass objects on the stack. Passing
! 6064: selectors on the stack is a little less convenient, but possible.
1.1 anton 6065:
1.26 ! crook 6066: @item
! 6067: Objects are just data structures in memory, and are referenced by their
! 6068: address. You can create words for objects with normal defining words
! 6069: like @code{constant}. Likewise, there is no difference between instance
! 6070: variables that contain objects and those that contain other data.
1.1 anton 6071:
1.26 ! crook 6072: @item
! 6073: Late binding is efficient and easy to use.
1.21 crook 6074:
1.26 ! crook 6075: @item
! 6076: It avoids parsing, and thus avoids problems with state-smartness
! 6077: and reduced extensibility; for convenience there are a few parsing
! 6078: words, but they have non-parsing counterparts. There are also a few
! 6079: defining words that parse. This is hard to avoid, because all standard
! 6080: defining words parse (except @code{:noname}); however, such
! 6081: words are not as bad as many other parsing words, because they are not
! 6082: state-smart.
1.21 crook 6083:
1.26 ! crook 6084: @item
! 6085: It does not try to incorporate everything. It does a few things and does
! 6086: them well (IMO). In particular, this model was not designed to support
! 6087: information hiding (although it has features that may help); you can use
! 6088: a separate package for achieving this.
1.21 crook 6089:
1.26 ! crook 6090: @item
! 6091: It is layered; you don't have to learn and use all features to use this
! 6092: model. Only a few features are necessary (@xref{Basic Objects Usage},
! 6093: @xref{The Objects base class}, @xref{Creating objects}.), the others
! 6094: are optional and independent of each other.
1.21 crook 6095:
1.26 ! crook 6096: @item
! 6097: An implementation in ANS Forth is available.
1.21 crook 6098:
1.26 ! crook 6099: @end itemize
1.21 crook 6100:
6101:
1.26 ! crook 6102: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
! 6103: @subsubsection Basic @file{objects.fs} Usage
! 6104: @cindex basic objects usage
! 6105: @cindex objects, basic usage
1.21 crook 6106:
1.26 ! crook 6107: You can define a class for graphical objects like this:
1.21 crook 6108:
1.26 ! crook 6109: @cindex @code{class} usage
! 6110: @cindex @code{end-class} usage
! 6111: @cindex @code{selector} usage
! 6112: @example
! 6113: object class \ "object" is the parent class
! 6114: selector draw ( x y graphical -- )
! 6115: end-class graphical
! 6116: @end example
1.21 crook 6117:
1.26 ! crook 6118: This code defines a class @code{graphical} with an
! 6119: operation @code{draw}. We can perform the operation
! 6120: @code{draw} on any @code{graphical} object, e.g.:
1.21 crook 6121:
1.26 ! crook 6122: @example
! 6123: 100 100 t-rex draw
! 6124: @end example
1.21 crook 6125:
1.26 ! crook 6126: @noindent
! 6127: where @code{t-rex} is a word (say, a constant) that produces a
! 6128: graphical object.
1.21 crook 6129:
1.26 ! crook 6130: @comment nac TODO add a 2nd operation eg perimeter.. and use for
! 6131: @comment a concrete example
1.21 crook 6132:
1.26 ! crook 6133: @cindex abstract class
! 6134: How do we create a graphical object? With the present definitions,
! 6135: we cannot create a useful graphical object. The class
! 6136: @code{graphical} describes graphical objects in general, but not
! 6137: any concrete graphical object type (C++ users would call it an
! 6138: @emph{abstract class}); e.g., there is no method for the selector
! 6139: @code{draw} in the class @code{graphical}.
1.21 crook 6140:
1.26 ! crook 6141: For concrete graphical objects, we define child classes of the
! 6142: class @code{graphical}, e.g.:
1.21 crook 6143:
1.26 ! crook 6144: @cindex @code{overrides} usage
! 6145: @cindex @code{field} usage in class definition
! 6146: @example
! 6147: graphical class \ "graphical" is the parent class
! 6148: cell% field circle-radius
1.21 crook 6149:
1.26 ! crook 6150: :noname ( x y circle -- )
! 6151: circle-radius @@ draw-circle ;
! 6152: overrides draw
1.21 crook 6153:
1.26 ! crook 6154: :noname ( n-radius circle -- )
! 6155: circle-radius ! ;
! 6156: overrides construct
1.21 crook 6157:
1.26 ! crook 6158: end-class circle
1.21 crook 6159: @end example
6160:
1.26 ! crook 6161: Here we define a class @code{circle} as a child of @code{graphical},
! 6162: with field @code{circle-radius} (which behaves just like a field
! 6163: (@pxref{Structures}); it defines (using @code{overrides}) new methods
! 6164: for the selectors @code{draw} and @code{construct} (@code{construct} is
! 6165: defined in @code{object}, the parent class of @code{graphical}).
1.21 crook 6166:
1.26 ! crook 6167: Now we can create a circle on the heap (i.e.,
! 6168: @code{allocate}d memory) with:
1.21 crook 6169:
1.26 ! crook 6170: @cindex @code{heap-new} usage
1.21 crook 6171: @example
1.26 ! crook 6172: 50 circle heap-new constant my-circle
! 6173: @end example
1.21 crook 6174:
1.26 ! crook 6175: @noindent
! 6176: @code{heap-new} invokes @code{construct}, thus
! 6177: initializing the field @code{circle-radius} with 50. We can draw
! 6178: this new circle at (100,100) with:
1.21 crook 6179:
1.26 ! crook 6180: @example
! 6181: 100 100 my-circle draw
1.21 crook 6182: @end example
6183:
1.26 ! crook 6184: @cindex selector invocation, restrictions
! 6185: @cindex class definition, restrictions
! 6186: Note: You can only invoke a selector if the object on the TOS
! 6187: (the receiving object) belongs to the class where the selector was
! 6188: defined or one of its descendents; e.g., you can invoke
! 6189: @code{draw} only for objects belonging to @code{graphical}
! 6190: or its descendents (e.g., @code{circle}). Immediately before
! 6191: @code{end-class}, the search order has to be the same as
! 6192: immediately after @code{class}.
1.21 crook 6193:
1.26 ! crook 6194: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
! 6195: @subsubsection The @file{object.fs} base class
! 6196: @cindex @code{object} class
1.21 crook 6197:
1.26 ! crook 6198: When you define a class, you have to specify a parent class. So how do
! 6199: you start defining classes? There is one class available from the start:
! 6200: @code{object}. It is ancestor for all classes and so is the
! 6201: only class that has no parent. It has two selectors: @code{construct}
! 6202: and @code{print}.
1.21 crook 6203:
1.26 ! crook 6204: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
! 6205: @subsubsection Creating objects
! 6206: @cindex creating objects
! 6207: @cindex object creation
! 6208: @cindex object allocation options
1.21 crook 6209:
1.26 ! crook 6210: @cindex @code{heap-new} discussion
! 6211: @cindex @code{dict-new} discussion
! 6212: @cindex @code{construct} discussion
! 6213: You can create and initialize an object of a class on the heap with
! 6214: @code{heap-new} ( ... class -- object ) and in the dictionary
! 6215: (allocation with @code{allot}) with @code{dict-new} (
! 6216: ... class -- object ). Both words invoke @code{construct}, which
! 6217: consumes the stack items indicated by "..." above.
1.21 crook 6218:
1.26 ! crook 6219: @cindex @code{init-object} discussion
! 6220: @cindex @code{class-inst-size} discussion
! 6221: If you want to allocate memory for an object yourself, you can get its
! 6222: alignment and size with @code{class-inst-size 2@@} ( class --
! 6223: align size ). Once you have memory for an object, you can initialize
! 6224: it with @code{init-object} ( ... class object -- );
! 6225: @code{construct} does only a part of the necessary work.
1.21 crook 6226:
1.26 ! crook 6227: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
! 6228: @subsubsection Object-Oriented Programming Style
! 6229: @cindex object-oriented programming style
1.21 crook 6230:
1.26 ! crook 6231: This section is not exhaustive.
1.1 anton 6232:
1.26 ! crook 6233: @cindex stack effects of selectors
! 6234: @cindex selectors and stack effects
! 6235: In general, it is a good idea to ensure that all methods for the
! 6236: same selector have the same stack effect: when you invoke a selector,
! 6237: you often have no idea which method will be invoked, so, unless all
! 6238: methods have the same stack effect, you will not know the stack effect
! 6239: of the selector invocation.
1.21 crook 6240:
1.26 ! crook 6241: One exception to this rule is methods for the selector
! 6242: @code{construct}. We know which method is invoked, because we
! 6243: specify the class to be constructed at the same place. Actually, I
! 6244: defined @code{construct} as a selector only to give the users a
! 6245: convenient way to specify initialization. The way it is used, a
! 6246: mechanism different from selector invocation would be more natural
! 6247: (but probably would take more code and more space to explain).
1.21 crook 6248:
1.26 ! crook 6249: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
! 6250: @subsubsection Class Binding
! 6251: @cindex class binding
! 6252: @cindex early binding
1.21 crook 6253:
1.26 ! crook 6254: @cindex late binding
! 6255: Normal selector invocations determine the method at run-time depending
! 6256: on the class of the receiving object. This run-time selection is called
! 6257: @var{late binding}.
1.21 crook 6258:
1.26 ! crook 6259: Sometimes it's preferable to invoke a different method. For example,
! 6260: you might want to use the simple method for @code{print}ing
! 6261: @code{object}s instead of the possibly long-winded @code{print} method
! 6262: of the receiver class. You can achieve this by replacing the invocation
! 6263: of @code{print} with:
1.21 crook 6264:
1.26 ! crook 6265: @cindex @code{[bind]} usage
! 6266: @example
! 6267: [bind] object print
1.21 crook 6268: @end example
6269:
1.26 ! crook 6270: @noindent
! 6271: in compiled code or:
1.21 crook 6272:
1.26 ! crook 6273: @cindex @code{bind} usage
1.21 crook 6274: @example
1.26 ! crook 6275: bind object print
1.21 crook 6276: @end example
6277:
1.26 ! crook 6278: @cindex class binding, alternative to
! 6279: @noindent
! 6280: in interpreted code. Alternatively, you can define the method with a
! 6281: name (e.g., @code{print-object}), and then invoke it through the
! 6282: name. Class binding is just a (often more convenient) way to achieve
! 6283: the same effect; it avoids name clutter and allows you to invoke
! 6284: methods directly without naming them first.
! 6285:
! 6286: @cindex superclass binding
! 6287: @cindex parent class binding
! 6288: A frequent use of class binding is this: When we define a method
! 6289: for a selector, we often want the method to do what the selector does
! 6290: in the parent class, and a little more. There is a special word for
! 6291: this purpose: @code{[parent]}; @code{[parent]
! 6292: @emph{selector}} is equivalent to @code{[bind] @emph{parent
! 6293: selector}}, where @code{@emph{parent}} is the parent
! 6294: class of the current class. E.g., a method definition might look like:
1.21 crook 6295:
1.26 ! crook 6296: @cindex @code{[parent]} usage
1.21 crook 6297: @example
1.26 ! crook 6298: :noname
! 6299: dup [parent] foo \ do parent's foo on the receiving object
! 6300: ... \ do some more
! 6301: ; overrides foo
1.21 crook 6302: @end example
6303:
1.26 ! crook 6304: @cindex class binding as optimization
! 6305: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
! 6306: March 1997), Andrew McKewan presents class binding as an optimization
! 6307: technique. I recommend not using it for this purpose unless you are in
! 6308: an emergency. Late binding is pretty fast with this model anyway, so the
! 6309: benefit of using class binding is small; the cost of using class binding
! 6310: where it is not appropriate is reduced maintainability.
1.21 crook 6311:
1.26 ! crook 6312: While we are at programming style questions: You should bind
! 6313: selectors only to ancestor classes of the receiving object. E.g., say,
! 6314: you know that the receiving object is of class @code{foo} or its
! 6315: descendents; then you should bind only to @code{foo} and its
! 6316: ancestors.
1.21 crook 6317:
1.26 ! crook 6318: @node Method conveniences, Classes and Scoping, Class Binding, Objects
! 6319: @subsubsection Method conveniences
! 6320: @cindex method conveniences
1.1 anton 6321:
1.26 ! crook 6322: In a method you usually access the receiving object pretty often. If
! 6323: you define the method as a plain colon definition (e.g., with
! 6324: @code{:noname}), you may have to do a lot of stack
! 6325: gymnastics. To avoid this, you can define the method with @code{m:
! 6326: ... ;m}. E.g., you could define the method for
! 6327: @code{draw}ing a @code{circle} with
1.20 pazsan 6328:
1.26 ! crook 6329: @cindex @code{this} usage
! 6330: @cindex @code{m:} usage
! 6331: @cindex @code{;m} usage
! 6332: @example
! 6333: m: ( x y circle -- )
! 6334: ( x y ) this circle-radius @@ draw-circle ;m
! 6335: @end example
1.20 pazsan 6336:
1.26 ! crook 6337: @cindex @code{exit} in @code{m: ... ;m}
! 6338: @cindex @code{exitm} discussion
! 6339: @cindex @code{catch} in @code{m: ... ;m}
! 6340: When this method is executed, the receiver object is removed from the
! 6341: stack; you can access it with @code{this} (admittedly, in this
! 6342: example the use of @code{m: ... ;m} offers no advantage). Note
! 6343: that I specify the stack effect for the whole method (i.e. including
! 6344: the receiver object), not just for the code between @code{m:}
! 6345: and @code{;m}. You cannot use @code{exit} in
! 6346: @code{m:...;m}; instead, use
! 6347: @code{exitm}.@footnote{Moreover, for any word that calls
! 6348: @code{catch} and was defined before loading
! 6349: @code{objects.fs}, you have to redefine it like I redefined
! 6350: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.20 pazsan 6351:
1.26 ! crook 6352: @cindex @code{inst-var} usage
! 6353: You will frequently use sequences of the form @code{this
! 6354: @emph{field}} (in the example above: @code{this
! 6355: circle-radius}). If you use the field only in this way, you can
! 6356: define it with @code{inst-var} and eliminate the
! 6357: @code{this} before the field name. E.g., the @code{circle}
! 6358: class above could also be defined with:
1.20 pazsan 6359:
1.26 ! crook 6360: @example
! 6361: graphical class
! 6362: cell% inst-var radius
1.20 pazsan 6363:
1.26 ! crook 6364: m: ( x y circle -- )
! 6365: radius @@ draw-circle ;m
! 6366: overrides draw
1.20 pazsan 6367:
1.26 ! crook 6368: m: ( n-radius circle -- )
! 6369: radius ! ;m
! 6370: overrides construct
1.12 anton 6371:
1.26 ! crook 6372: end-class circle
! 6373: @end example
1.12 anton 6374:
1.26 ! crook 6375: @code{radius} can only be used in @code{circle} and its
! 6376: descendent classes and inside @code{m:...;m}.
1.12 anton 6377:
1.26 ! crook 6378: @cindex @code{inst-value} usage
! 6379: You can also define fields with @code{inst-value}, which is
! 6380: to @code{inst-var} what @code{value} is to
! 6381: @code{variable}. You can change the value of such a field with
! 6382: @code{[to-inst]}. E.g., we could also define the class
! 6383: @code{circle} like this:
1.12 anton 6384:
1.26 ! crook 6385: @example
! 6386: graphical class
! 6387: inst-value radius
1.12 anton 6388:
1.26 ! crook 6389: m: ( x y circle -- )
! 6390: radius draw-circle ;m
! 6391: overrides draw
1.12 anton 6392:
1.26 ! crook 6393: m: ( n-radius circle -- )
! 6394: [to-inst] radius ;m
! 6395: overrides construct
1.21 crook 6396:
1.26 ! crook 6397: end-class circle
1.12 anton 6398: @end example
6399:
6400:
1.26 ! crook 6401: @node Classes and Scoping, Object Interfaces, Method conveniences, Objects
! 6402: @subsubsection Classes and Scoping
! 6403: @cindex classes and scoping
! 6404: @cindex scoping and classes
1.12 anton 6405:
1.26 ! crook 6406: Inheritance is frequent, unlike structure extension. This exacerbates
! 6407: the problem with the field name convention (@pxref{Structure Naming
! 6408: Convention}): One always has to remember in which class the field was
! 6409: originally defined; changing a part of the class structure would require
! 6410: changes for renaming in otherwise unaffected code.
1.12 anton 6411:
1.26 ! crook 6412: @cindex @code{inst-var} visibility
! 6413: @cindex @code{inst-value} visibility
! 6414: To solve this problem, I added a scoping mechanism (which was not in my
! 6415: original charter): A field defined with @code{inst-var} (or
! 6416: @code{inst-value}) is visible only in the class where it is defined and in
! 6417: the descendent classes of this class. Using such fields only makes
! 6418: sense in @code{m:}-defined methods in these classes anyway.
1.12 anton 6419:
1.26 ! crook 6420: This scoping mechanism allows us to use the unadorned field name,
! 6421: because name clashes with unrelated words become much less likely.
1.12 anton 6422:
1.26 ! crook 6423: @cindex @code{protected} discussion
! 6424: @cindex @code{private} discussion
! 6425: Once we have this mechanism, we can also use it for controlling the
! 6426: visibility of other words: All words defined after
! 6427: @code{protected} are visible only in the current class and its
! 6428: descendents. @code{public} restores the compilation
! 6429: (i.e. @code{current}) word list that was in effect before. If you
! 6430: have several @code{protected}s without an intervening
! 6431: @code{public} or @code{set-current}, @code{public}
! 6432: will restore the compilation word list in effect before the first of
! 6433: these @code{protected}s.
1.12 anton 6434:
1.26 ! crook 6435: @node Object Interfaces, Objects Implementation, Classes and Scoping, Objects
! 6436: @subsubsection Object Interfaces
! 6437: @cindex object interfaces
! 6438: @cindex interfaces for objects
1.12 anton 6439:
1.26 ! crook 6440: In this model you can only call selectors defined in the class of the
! 6441: receiving objects or in one of its ancestors. If you call a selector
! 6442: with a receiving object that is not in one of these classes, the
! 6443: result is undefined; if you are lucky, the program crashes
! 6444: immediately.
1.12 anton 6445:
1.26 ! crook 6446: @cindex selectors common to hardly-related classes
! 6447: Now consider the case when you want to have a selector (or several)
! 6448: available in two classes: You would have to add the selector to a
! 6449: common ancestor class, in the worst case to @code{object}. You
! 6450: may not want to do this, e.g., because someone else is responsible for
! 6451: this ancestor class.
1.12 anton 6452:
1.26 ! crook 6453: The solution for this problem is interfaces. An interface is a
! 6454: collection of selectors. If a class implements an interface, the
! 6455: selectors become available to the class and its descendents. A class
! 6456: can implement an unlimited number of interfaces. For the problem
! 6457: discussed above, we would define an interface for the selector(s), and
! 6458: both classes would implement the interface.
1.12 anton 6459:
1.26 ! crook 6460: As an example, consider an interface @code{storage} for
! 6461: writing objects to disk and getting them back, and a class
! 6462: @code{foo} that implements it. The code would look like this:
1.12 anton 6463:
1.26 ! crook 6464: @cindex @code{interface} usage
! 6465: @cindex @code{end-interface} usage
! 6466: @cindex @code{implementation} usage
! 6467: @example
! 6468: interface
! 6469: selector write ( file object -- )
! 6470: selector read1 ( file object -- )
! 6471: end-interface storage
1.12 anton 6472:
1.26 ! crook 6473: bar class
! 6474: storage implementation
1.12 anton 6475:
1.26 ! crook 6476: ... overrides write
! 6477: ... overrides read
! 6478: ...
! 6479: end-class foo
1.12 anton 6480: @end example
6481:
1.26 ! crook 6482: @noindent
! 6483: (I would add a word @code{read} @var{( file -- object )} that uses
! 6484: @code{read1} internally, but that's beyond the point illustrated
! 6485: here.)
1.12 anton 6486:
1.26 ! crook 6487: Note that you cannot use @code{protected} in an interface; and
! 6488: of course you cannot define fields.
1.12 anton 6489:
1.26 ! crook 6490: In the Neon model, all selectors are available for all classes;
! 6491: therefore it does not need interfaces. The price you pay in this model
! 6492: is slower late binding, and therefore, added complexity to avoid late
! 6493: binding.
1.12 anton 6494:
1.26 ! crook 6495: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
! 6496: @subsubsection @file{objects.fs} Implementation
! 6497: @cindex @file{objects.fs} implementation
1.12 anton 6498:
1.26 ! crook 6499: @cindex @code{object-map} discussion
! 6500: An object is a piece of memory, like one of the data structures
! 6501: described with @code{struct...end-struct}. It has a field
! 6502: @code{object-map} that points to the method map for the object's
! 6503: class.
1.12 anton 6504:
1.26 ! crook 6505: @cindex method map
! 6506: @cindex virtual function table
! 6507: The @emph{method map}@footnote{This is Self terminology; in C++
! 6508: terminology: virtual function table.} is an array that contains the
! 6509: execution tokens (@var{xt}s) of the methods for the object's class. Each
! 6510: selector contains an offset into a method map.
1.12 anton 6511:
1.26 ! crook 6512: @cindex @code{selector} implementation, class
! 6513: @code{selector} is a defining word that uses
! 6514: @code{CREATE} and @code{DOES>}. The body of the
! 6515: selector contains the offset; the @code{does>} action for a
! 6516: class selector is, basically:
1.21 crook 6517:
1.26 ! crook 6518: @example
! 6519: ( object addr ) @@ over object-map @@ + @@ execute
! 6520: @end example
1.12 anton 6521:
1.26 ! crook 6522: Since @code{object-map} is the first field of the object, it
! 6523: does not generate any code. As you can see, calling a selector has a
! 6524: small, constant cost.
1.12 anton 6525:
1.26 ! crook 6526: @cindex @code{current-interface} discussion
! 6527: @cindex class implementation and representation
! 6528: A class is basically a @code{struct} combined with a method
! 6529: map. During the class definition the alignment and size of the class
! 6530: are passed on the stack, just as with @code{struct}s, so
! 6531: @code{field} can also be used for defining class
! 6532: fields. However, passing more items on the stack would be
! 6533: inconvenient, so @code{class} builds a data structure in memory,
! 6534: which is accessed through the variable
! 6535: @code{current-interface}. After its definition is complete, the
! 6536: class is represented on the stack by a pointer (e.g., as parameter for
! 6537: a child class definition).
1.1 anton 6538:
1.26 ! crook 6539: A new class starts off with the alignment and size of its parent,
! 6540: and a copy of the parent's method map. Defining new fields extends the
! 6541: size and alignment; likewise, defining new selectors extends the
! 6542: method map. @code{overrides} just stores a new @var{xt} in the method
! 6543: map at the offset given by the selector.
1.20 pazsan 6544:
1.26 ! crook 6545: @cindex class binding, implementation
! 6546: Class binding just gets the @var{xt} at the offset given by the selector
! 6547: from the class's method map and @code{compile,}s (in the case of
! 6548: @code{[bind]}) it.
1.21 crook 6549:
1.26 ! crook 6550: @cindex @code{this} implementation
! 6551: @cindex @code{catch} and @code{this}
! 6552: @cindex @code{this} and @code{catch}
! 6553: I implemented @code{this} as a @code{value}. At the
! 6554: start of an @code{m:...;m} method the old @code{this} is
! 6555: stored to the return stack and restored at the end; and the object on
! 6556: the TOS is stored @code{TO this}. This technique has one
! 6557: disadvantage: If the user does not leave the method via
! 6558: @code{;m}, but via @code{throw} or @code{exit},
! 6559: @code{this} is not restored (and @code{exit} may
! 6560: crash). To deal with the @code{throw} problem, I have redefined
! 6561: @code{catch} to save and restore @code{this}; the same
! 6562: should be done with any word that can catch an exception. As for
! 6563: @code{exit}, I simply forbid it (as a replacement, there is
! 6564: @code{exitm}).
1.21 crook 6565:
1.26 ! crook 6566: @cindex @code{inst-var} implementation
! 6567: @code{inst-var} is just the same as @code{field}, with
! 6568: a different @code{DOES>} action:
! 6569: @example
! 6570: @@ this +
! 6571: @end example
! 6572: Similar for @code{inst-value}.
1.21 crook 6573:
1.26 ! crook 6574: @cindex class scoping implementation
! 6575: Each class also has a word list that contains the words defined with
! 6576: @code{inst-var} and @code{inst-value}, and its protected
! 6577: words. It also has a pointer to its parent. @code{class} pushes
! 6578: the word lists of the class and all its ancestors onto the search order stack,
! 6579: and @code{end-class} drops them.
1.21 crook 6580:
1.26 ! crook 6581: @cindex interface implementation
! 6582: An interface is like a class without fields, parent and protected
! 6583: words; i.e., it just has a method map. If a class implements an
! 6584: interface, its method map contains a pointer to the method map of the
! 6585: interface. The positive offsets in the map are reserved for class
! 6586: methods, therefore interface map pointers have negative
! 6587: offsets. Interfaces have offsets that are unique throughout the
! 6588: system, unlike class selectors, whose offsets are only unique for the
! 6589: classes where the selector is available (invokable).
1.21 crook 6590:
1.26 ! crook 6591: This structure means that interface selectors have to perform one
! 6592: indirection more than class selectors to find their method. Their body
! 6593: contains the interface map pointer offset in the class method map, and
! 6594: the method offset in the interface method map. The
! 6595: @code{does>} action for an interface selector is, basically:
1.21 crook 6596:
6597: @example
1.26 ! crook 6598: ( object selector-body )
! 6599: 2dup selector-interface @@ ( object selector-body object interface-offset )
! 6600: swap object-map @@ + @@ ( object selector-body map )
! 6601: swap selector-offset @@ + @@ execute
1.21 crook 6602: @end example
6603:
1.26 ! crook 6604: where @code{object-map} and @code{selector-offset} are
! 6605: first fields and generate no code.
! 6606:
! 6607: As a concrete example, consider the following code:
1.21 crook 6608:
1.26 ! crook 6609: @example
! 6610: interface
! 6611: selector if1sel1
! 6612: selector if1sel2
! 6613: end-interface if1
1.21 crook 6614:
1.26 ! crook 6615: object class
! 6616: if1 implementation
! 6617: selector cl1sel1
! 6618: cell% inst-var cl1iv1
1.21 crook 6619:
1.26 ! crook 6620: ' m1 overrides construct
! 6621: ' m2 overrides if1sel1
! 6622: ' m3 overrides if1sel2
! 6623: ' m4 overrides cl1sel2
! 6624: end-class cl1
1.21 crook 6625:
1.26 ! crook 6626: create obj1 object dict-new drop
! 6627: create obj2 cl1 dict-new drop
! 6628: @end example
1.21 crook 6629:
1.26 ! crook 6630: The data structure created by this code (including the data structure
! 6631: for @code{object}) is shown in the <a
! 6632: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
! 6633: @comment nac TODO add this diagram..
1.21 crook 6634:
1.26 ! crook 6635: @node Objects Glossary, , Objects Implementation, Objects
! 6636: @subsubsection @file{objects.fs} Glossary
! 6637: @cindex @file{objects.fs} Glossary
1.21 crook 6638:
1.26 ! crook 6639: doc---objects-bind
! 6640: doc---objects-<bind>
! 6641: doc---objects-bind'
! 6642: doc---objects-[bind]
! 6643: doc---objects-class
! 6644: doc---objects-class->map
! 6645: doc---objects-class-inst-size
! 6646: doc---objects-class-override!
! 6647: doc---objects-construct
! 6648: doc---objects-current'
! 6649: doc---objects-[current]
! 6650: doc---objects-current-interface
! 6651: doc---objects-dict-new
! 6652: doc---objects-drop-order
! 6653: doc---objects-end-class
! 6654: doc---objects-end-class-noname
! 6655: doc---objects-end-interface
! 6656: doc---objects-end-interface-noname
! 6657: doc---objects-exitm
! 6658: doc---objects-heap-new
! 6659: doc---objects-implementation
! 6660: doc---objects-init-object
! 6661: doc---objects-inst-value
! 6662: doc---objects-inst-var
! 6663: doc---objects-interface
! 6664: doc---objects-;m
! 6665: doc---objects-m:
! 6666: doc---objects-method
! 6667: doc---objects-object
! 6668: doc---objects-overrides
! 6669: doc---objects-[parent]
! 6670: doc---objects-print
! 6671: doc---objects-protected
! 6672: doc---objects-public
! 6673: doc---objects-push-order
! 6674: doc---objects-selector
! 6675: doc---objects-this
! 6676: doc---objects-<to-inst>
! 6677: doc---objects-[to-inst]
! 6678: doc---objects-to-this
! 6679: doc---objects-xt-new
1.21 crook 6680:
1.26 ! crook 6681: @c -------------------------------------------------------------
! 6682: @node OOF, Mini-OOF, Objects, Object-oriented Forth
! 6683: @subsection The @file{oof.fs} model
! 6684: @cindex oof
! 6685: @cindex object-oriented programming
1.21 crook 6686:
1.26 ! crook 6687: @cindex @file{objects.fs}
! 6688: @cindex @file{oof.fs}
1.21 crook 6689:
1.26 ! crook 6690: This section describes the @file{oof.fs} package.
1.21 crook 6691:
1.26 ! crook 6692: The package described in this section has been used in bigFORTH since 1991, and
! 6693: used for two large applications: a chromatographic system used to
! 6694: create new medicaments, and a graphic user interface library (MINOS).
1.21 crook 6695:
1.26 ! crook 6696: You can find a description (in German) of @file{oof.fs} in @cite{Object
! 6697: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
! 6698: 10(2), 1994.
1.21 crook 6699:
1.26 ! crook 6700: @menu
! 6701: * Properties of the OOF model::
! 6702: * Basic OOF Usage::
! 6703: * The OOF base class::
! 6704: * Class Declaration::
! 6705: * Class Implementation::
! 6706: @end menu
1.21 crook 6707:
1.26 ! crook 6708: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
! 6709: @subsubsection Properties of the @file{oof.fs} model
! 6710: @cindex @file{oof.fs} properties
1.21 crook 6711:
1.26 ! crook 6712: @itemize @bullet
! 6713: @item
! 6714: This model combines object oriented programming with information
! 6715: hiding. It helps you writing large application, where scoping is
! 6716: necessary, because it provides class-oriented scoping.
1.21 crook 6717:
1.26 ! crook 6718: @item
! 6719: Named objects, object pointers, and object arrays can be created,
! 6720: selector invocation uses the ``object selector'' syntax. Selector invocation
! 6721: to objects and/or selectors on the stack is a bit less convenient, but
! 6722: possible.
1.21 crook 6723:
1.26 ! crook 6724: @item
! 6725: Selector invocation and instance variable usage of the active object is
! 6726: straightforward, since both make use of the active object.
1.21 crook 6727:
1.26 ! crook 6728: @item
! 6729: Late binding is efficient and easy to use.
1.21 crook 6730:
1.26 ! crook 6731: @item
! 6732: State-smart objects parse selectors. However, extensibility is provided
! 6733: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.21 crook 6734:
6735: @item
1.26 ! crook 6736: An implementation in ANS Forth is available.
! 6737:
1.21 crook 6738: @end itemize
6739:
6740:
1.26 ! crook 6741: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
! 6742: @subsubsection Basic @file{oof.fs} Usage
! 6743: @cindex @file{oof.fs} usage
! 6744:
! 6745: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.21 crook 6746:
1.26 ! crook 6747: You can define a class for graphical objects like this:
1.21 crook 6748:
1.26 ! crook 6749: @cindex @code{class} usage
! 6750: @cindex @code{class;} usage
! 6751: @cindex @code{method} usage
! 6752: @example
! 6753: object class graphical \ "object" is the parent class
! 6754: method draw ( x y graphical -- )
! 6755: class;
! 6756: @end example
1.21 crook 6757:
1.26 ! crook 6758: This code defines a class @code{graphical} with an
! 6759: operation @code{draw}. We can perform the operation
! 6760: @code{draw} on any @code{graphical} object, e.g.:
1.21 crook 6761:
1.26 ! crook 6762: @example
! 6763: 100 100 t-rex draw
! 6764: @end example
1.21 crook 6765:
1.26 ! crook 6766: @noindent
! 6767: where @code{t-rex} is an object or object pointer, created with e.g.
! 6768: @code{graphical : t-rex}.
1.21 crook 6769:
1.26 ! crook 6770: @cindex abstract class
! 6771: How do we create a graphical object? With the present definitions,
! 6772: we cannot create a useful graphical object. The class
! 6773: @code{graphical} describes graphical objects in general, but not
! 6774: any concrete graphical object type (C++ users would call it an
! 6775: @emph{abstract class}); e.g., there is no method for the selector
! 6776: @code{draw} in the class @code{graphical}.
1.21 crook 6777:
1.26 ! crook 6778: For concrete graphical objects, we define child classes of the
! 6779: class @code{graphical}, e.g.:
1.21 crook 6780:
6781: @example
1.26 ! crook 6782: graphical class circle \ "graphical" is the parent class
! 6783: cell var circle-radius
! 6784: how:
! 6785: : draw ( x y -- )
! 6786: circle-radius @@ draw-circle ;
! 6787:
! 6788: : init ( n-radius -- (
! 6789: circle-radius ! ;
! 6790: class;
! 6791: @end example
! 6792:
! 6793: Here we define a class @code{circle} as a child of @code{graphical},
! 6794: with a field @code{circle-radius}; it defines new methods for the
! 6795: selectors @code{draw} and @code{init} (@code{init} is defined in
! 6796: @code{object}, the parent class of @code{graphical}).
1.21 crook 6797:
1.26 ! crook 6798: Now we can create a circle in the dictionary with:
1.21 crook 6799:
1.26 ! crook 6800: @example
! 6801: 50 circle : my-circle
1.21 crook 6802: @end example
6803:
1.26 ! crook 6804: @noindent
! 6805: @code{:} invokes @code{init}, thus initializing the field
! 6806: @code{circle-radius} with 50. We can draw this new circle at (100,100)
! 6807: with:
1.21 crook 6808:
6809: @example
1.26 ! crook 6810: 100 100 my-circle draw
1.21 crook 6811: @end example
6812:
1.26 ! crook 6813: @cindex selector invocation, restrictions
! 6814: @cindex class definition, restrictions
! 6815: Note: You can only invoke a selector if the receiving object belongs to
! 6816: the class where the selector was defined or one of its descendents;
! 6817: e.g., you can invoke @code{draw} only for objects belonging to
! 6818: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
! 6819: mechanism will check if you try to invoke a selector that is not
! 6820: defined in this class hierarchy, so you'll get an error at compilation
! 6821: time.
! 6822:
! 6823:
! 6824: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
! 6825: @subsubsection The @file{oof.fs} base class
! 6826: @cindex @file{oof.fs} base class
! 6827:
! 6828: When you define a class, you have to specify a parent class. So how do
! 6829: you start defining classes? There is one class available from the start:
! 6830: @code{object}. You have to use it as ancestor for all classes. It is the
! 6831: only class that has no parent. Classes are also objects, except that
! 6832: they don't have instance variables; class manipulation such as
! 6833: inheritance or changing definitions of a class is handled through
! 6834: selectors of the class @code{object}.
! 6835:
! 6836: @code{object} provides a number of selectors:
! 6837:
1.21 crook 6838: @itemize @bullet
6839: @item
1.26 ! crook 6840: @code{class} for subclassing, @code{definitions} to add definitions
! 6841: later on, and @code{class?} to get type informations (is the class a
! 6842: subclass of the class passed on the stack?).
! 6843: doc---object-class
! 6844: doc---object-definitions
! 6845: doc---object-class?
! 6846:
1.21 crook 6847: @item
1.26 ! crook 6848: @code{init} and @code{dispose} as constructor and destructor of the
! 6849: object. @code{init} is invocated after the object's memory is allocated,
! 6850: while @code{dispose} also handles deallocation. Thus if you redefine
! 6851: @code{dispose}, you have to call the parent's dispose with @code{super
! 6852: dispose}, too.
! 6853: doc---object-init
! 6854: doc---object-dispose
! 6855:
1.21 crook 6856: @item
1.26 ! crook 6857: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
! 6858: @code{[]} to create named and unnamed objects and object arrays or
! 6859: object pointers.
! 6860: doc---object-new
! 6861: doc---object-new[]
! 6862: doc---object-:
! 6863: doc---object-ptr
! 6864: doc---object-asptr
! 6865: doc---object-[]
1.21 crook 6866:
1.26 ! crook 6867: @item
! 6868: @code{::} and @code{super} for explicit scoping. You should use explicit
! 6869: scoping only for super classes or classes with the same set of instance
! 6870: variables. Explicitly-scoped selectors use early binding.
! 6871: doc---object-::
! 6872: doc---object-super
1.21 crook 6873:
1.26 ! crook 6874: @item
! 6875: @code{self} to get the address of the object
! 6876: doc---object-self
1.21 crook 6877:
6878: @item
1.26 ! crook 6879: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
! 6880: pointers and instance defers.
! 6881: doc---object-bind
! 6882: doc---object-bound
! 6883: doc---object-link
! 6884: doc---object-is
! 6885:
1.21 crook 6886: @item
1.26 ! crook 6887: @code{'} to obtain selector tokens, @code{send} to invocate selectors
! 6888: form the stack, and @code{postpone} to generate selector invocation code.
! 6889: doc---object-'
! 6890: doc---object-postpone
! 6891:
1.21 crook 6892: @item
1.26 ! crook 6893: @code{with} and @code{endwith} to select the active object from the
! 6894: stack, and enable its scope. Using @code{with} and @code{endwith}
! 6895: also allows you to create code using selector @code{postpone} without being
! 6896: trapped by the state-smart objects.
! 6897: doc---object-with
! 6898: doc---object-endwith
! 6899:
1.21 crook 6900: @end itemize
6901:
1.26 ! crook 6902: @node Class Declaration, Class Implementation, The OOF base class, OOF
! 6903: @subsubsection Class Declaration
! 6904: @cindex class declaration
! 6905:
! 6906: @itemize @bullet
! 6907: @item
! 6908: Instance variables
! 6909: doc---oof-var
1.21 crook 6910:
1.26 ! crook 6911: @item
! 6912: Object pointers
! 6913: doc---oof-ptr
! 6914: doc---oof-asptr
1.21 crook 6915:
1.26 ! crook 6916: @item
! 6917: Instance defers
! 6918: doc---oof-defer
1.21 crook 6919:
1.26 ! crook 6920: @item
! 6921: Method selectors
! 6922: doc---oof-early
! 6923: doc---oof-method
1.21 crook 6924:
1.26 ! crook 6925: @item
! 6926: Class-wide variables
! 6927: doc---oof-static
1.21 crook 6928:
1.26 ! crook 6929: @item
! 6930: End declaration
! 6931: doc---oof-how:
! 6932: doc---oof-class;
1.21 crook 6933:
1.26 ! crook 6934: @end itemize
1.21 crook 6935:
1.26 ! crook 6936: @c -------------------------------------------------------------
! 6937: @node Class Implementation, , Class Declaration, OOF
! 6938: @subsubsection Class Implementation
! 6939: @cindex class implementation
1.21 crook 6940:
1.26 ! crook 6941: @c -------------------------------------------------------------
! 6942: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
! 6943: @subsection The @file{mini-oof.fs} model
! 6944: @cindex mini-oof
1.1 anton 6945:
1.26 ! crook 6946: Gforth's third object oriented Forth package is a 12-liner. It uses a
! 6947: mixture of the @file{object.fs} and the @file{oof.fs} syntax,
! 6948: and reduces to the bare minimum of features. This is based on a posting
! 6949: of Bernd Paysan in comp.arch.
1.1 anton 6950:
6951: @menu
1.26 ! crook 6952: * Basic Mini-OOF Usage::
! 6953: * Mini-OOF Example::
! 6954: * Mini-OOF Implementation::
1.1 anton 6955: @end menu
6956:
1.26 ! crook 6957: @c -------------------------------------------------------------
! 6958: @node Basic Mini-OOF Usage, Mini-OOF Example, , Mini-OOF
! 6959: @subsubsection Basic @file{mini-oof.fs} Usage
! 6960: @cindex mini-oof usage
1.1 anton 6961:
1.26 ! crook 6962: There is a base class (@code{class}, which allocates one cell
! 6963: for the object pointer) plus seven other words: to define a method, a
! 6964: variable, a class; to end a class, to resolve binding, to allocate an
! 6965: object and to compile a class method.
! 6966: @comment TODO better description of the last one
1.1 anton 6967:
1.26 ! crook 6968: doc-object
! 6969: doc-method
! 6970: doc-var
! 6971: doc-class
! 6972: doc-end-class
! 6973: doc-defines
! 6974: doc-new
! 6975: doc-::
1.1 anton 6976:
1.21 crook 6977:
1.26 ! crook 6978: @c -------------------------------------------------------------
! 6979: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
! 6980: @subsubsection Mini-OOF Example
! 6981: @cindex mini-oof example
1.21 crook 6982:
1.26 ! crook 6983: A short example shows how to use this package. This example, in slightly
! 6984: extended form, is supplied as @file{moof-exm.fs}
! 6985: @comment nac TODO could flesh this out with some comments from the Forthwrite article
1.21 crook 6986:
1.26 ! crook 6987: @example
! 6988: object class
! 6989: method init
! 6990: method draw
! 6991: end-class graphical
! 6992: @end example
1.21 crook 6993:
1.26 ! crook 6994: This code defines a class @code{graphical} with an
! 6995: operation @code{draw}. We can perform the operation
! 6996: @code{draw} on any @code{graphical} object, e.g.:
1.1 anton 6997:
1.26 ! crook 6998: @example
! 6999: 100 100 t-rex draw
! 7000: @end example
1.1 anton 7001:
1.26 ! crook 7002: where @code{t-rex} is an object or object pointer, created with e.g.
! 7003: @code{graphical new Constant t-rex}.
1.1 anton 7004:
1.26 ! crook 7005: For concrete graphical objects, we define child classes of the
! 7006: class @code{graphical}, e.g.:
1.21 crook 7007:
7008: @example
1.26 ! crook 7009: graphical class
! 7010: cell var circle-radius
! 7011: end-class circle \ "graphical" is the parent class
1.21 crook 7012:
1.26 ! crook 7013: :noname ( x y -- )
! 7014: circle-radius @@ draw-circle ; circle defines draw
! 7015: :noname ( r -- )
! 7016: circle-radius ! ; circle defines init
1.21 crook 7017: @end example
7018:
1.26 ! crook 7019: There is no implicit init method, so we have to define one. The creation
! 7020: code of the object now has to call init explicitely.
1.21 crook 7021:
1.26 ! crook 7022: @example
! 7023: circle new Constant my-circle
! 7024: 50 my-circle init
! 7025: @end example
1.21 crook 7026:
1.26 ! crook 7027: It is also possible to add a function to create named objects with
! 7028: automatic call of @code{init}, given that all objects have @code{init}
! 7029: on the same place:
1.1 anton 7030:
7031: @example
1.26 ! crook 7032: : new: ( .. o "name" -- )
! 7033: new dup Constant init ;
! 7034: 80 circle new: large-circle
1.1 anton 7035: @end example
7036:
1.26 ! crook 7037: We can draw this new circle at (100,100) with:
1.1 anton 7038:
7039: @example
1.26 ! crook 7040: 100 100 my-circle draw
1.1 anton 7041: @end example
7042:
1.26 ! crook 7043: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
! 7044: @subsubsection @file{mini-oof.fs} Implementation
1.1 anton 7045:
1.26 ! crook 7046: Object-oriented systems with late binding typically use a
! 7047: ``vtable''-approach: the first variable in each object is a pointer to a
! 7048: table, which contains the methods as function pointers. The vtable
! 7049: may also contain other information.
1.1 anton 7050:
1.26 ! crook 7051: So first, let's declare methods:
1.1 anton 7052:
1.26 ! crook 7053: @example
! 7054: : method ( m v -- m' v ) Create over , swap cell+ swap
! 7055: DOES> ( ... o -- ... ) @ over @ + @ execute ;
! 7056: @end example
1.1 anton 7057:
1.26 ! crook 7058: During method declaration, the number of methods and instance
! 7059: variables is on the stack (in address units). @code{method} creates
! 7060: one method and increments the method number. To execute a method, it
! 7061: takes the object, fetches the vtable pointer, adds the offset, and
! 7062: executes the @var{xt} stored there. Each method takes the object it is
! 7063: invoked from as top of stack parameter. The method itself should
! 7064: consume that object.
1.1 anton 7065:
1.26 ! crook 7066: Now, we also have to declare instance variables
1.21 crook 7067:
1.26 ! crook 7068: @example
! 7069: : var ( m v size -- m v' ) Create over , +
! 7070: DOES> ( o -- addr ) @ + ;
! 7071: @end example
1.21 crook 7072:
1.26 ! crook 7073: As before, a word is created with the current offset. Instance
! 7074: variables can have different sizes (cells, floats, doubles, chars), so
! 7075: all we do is take the size and add it to the offset. If your machine
! 7076: has alignment restrictions, put the proper @code{aligned} or
! 7077: @code{faligned} before the variable, to adjust the variable
! 7078: offset. That's why it is on the top of stack.
1.2 jwilke 7079:
1.26 ! crook 7080: We need a starting point (the base object) and some syntactic sugar:
1.21 crook 7081:
1.26 ! crook 7082: @example
! 7083: Create object 1 cells , 2 cells ,
! 7084: : class ( class -- class methods vars ) dup 2@ ;
! 7085: @end example
1.21 crook 7086:
1.26 ! crook 7087: For inheritance, the vtable of the parent object has to be
! 7088: copied when a new, derived class is declared. This gives all the
! 7089: methods of the parent class, which can be overridden, though.
1.21 crook 7090:
1.2 jwilke 7091: @example
1.26 ! crook 7092: : end-class ( class methods vars -- )
! 7093: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
! 7094: cell+ dup cell+ r> rot @ 2 cells /string move ;
! 7095: @end example
! 7096:
! 7097: The first line creates the vtable, initialized with
! 7098: @code{noop}s. The second line is the inheritance mechanism, it
! 7099: copies the xts from the parent vtable.
1.2 jwilke 7100:
1.26 ! crook 7101: We still have no way to define new methods, let's do that now:
1.2 jwilke 7102:
1.26 ! crook 7103: @example
! 7104: : defines ( xt class -- ) ' >body @ + ! ;
1.2 jwilke 7105: @end example
7106:
1.26 ! crook 7107: To allocate a new object, we need a word, too:
1.2 jwilke 7108:
1.26 ! crook 7109: @example
! 7110: : new ( class -- o ) here over @ allot swap over ! ;
! 7111: @end example
1.2 jwilke 7112:
1.26 ! crook 7113: Sometimes derived classes want to access the method of the
! 7114: parent object. There are two ways to achieve this with Mini-OOF:
! 7115: first, you could use named words, and second, you could look up the
! 7116: vtable of the parent object.
1.2 jwilke 7117:
1.26 ! crook 7118: @example
! 7119: : :: ( class "name" -- ) ' >body @ + @ compile, ;
! 7120: @end example
1.2 jwilke 7121:
7122:
1.26 ! crook 7123: Nothing can be more confusing than a good example, so here is
! 7124: one. First let's declare a text object (called
! 7125: @code{button}), that stores text and position:
1.2 jwilke 7126:
1.26 ! crook 7127: @example
! 7128: object class
! 7129: cell var text
! 7130: cell var len
! 7131: cell var x
! 7132: cell var y
! 7133: method init
! 7134: method draw
! 7135: end-class button
! 7136: @end example
1.2 jwilke 7137:
1.26 ! crook 7138: @noindent
! 7139: Now, implement the two methods, @code{draw} and @code{init}:
1.2 jwilke 7140:
1.26 ! crook 7141: @example
! 7142: :noname ( o -- )
! 7143: >r r@ x @ r@ y @ at-xy r@ text @ r> len @ type ;
! 7144: button defines draw
! 7145: :noname ( addr u o -- )
! 7146: >r 0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
! 7147: button defines init
! 7148: @end example
1.2 jwilke 7149:
1.26 ! crook 7150: @noindent
! 7151: To demonstrate inheritance, we define a class @code{bold-button}, with no
! 7152: new data and no new methods:
1.2 jwilke 7153:
1.26 ! crook 7154: @example
! 7155: button class
! 7156: end-class bold-button
1.1 anton 7157:
1.26 ! crook 7158: : bold 27 emit ." [1m" ;
! 7159: : normal 27 emit ." [0m" ;
! 7160: @end example
1.1 anton 7161:
1.26 ! crook 7162: @noindent
! 7163: The class @code{bold-button} has a different draw method to
! 7164: @code{button}, but the new method is defined in terms of the draw method
! 7165: for @code{button}:
1.1 anton 7166:
1.26 ! crook 7167: @example
! 7168: :noname bold [ button :: draw ] normal ; bold-button defines draw
! 7169: @end example
1.1 anton 7170:
1.26 ! crook 7171: @noindent
! 7172: Finally, create two objects and apply methods:
1.1 anton 7173:
1.26 ! crook 7174: @example
! 7175: button new Constant foo
! 7176: s" thin foo" foo init
! 7177: page
! 7178: foo draw
! 7179: bold-button new Constant bar
! 7180: s" fat bar" bar init
! 7181: 1 bar y !
! 7182: bar draw
! 7183: @end example
1.1 anton 7184:
7185:
1.26 ! crook 7186: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
! 7187: @subsubsection Comparison with other object models
! 7188: @cindex comparison of object models
! 7189: @cindex object models, comparison
1.1 anton 7190:
1.26 ! crook 7191: Many object-oriented Forth extensions have been proposed (@cite{A survey
! 7192: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
! 7193: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
! 7194: relation of the object models described here to two well-known and two
! 7195: closely-related (by the use of method maps) models.
1.1 anton 7196:
1.26 ! crook 7197: @cindex Neon model
! 7198: The most popular model currently seems to be the Neon model (see
! 7199: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
! 7200: 1997) by Andrew McKewan) but this model has a number of limitations
! 7201: @footnote{A longer version of this critique can be
! 7202: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
! 7203: Dimensions, May 1997) by Anton Ertl.}:
1.1 anton 7204:
1.26 ! crook 7205: @itemize @bullet
! 7206: @item
! 7207: It uses a @code{@emph{selector
! 7208: object}} syntax, which makes it unnatural to pass objects on the
! 7209: stack.
1.1 anton 7210:
1.26 ! crook 7211: @item
! 7212: It requires that the selector parses the input stream (at
! 7213: compile time); this leads to reduced extensibility and to bugs that are+
! 7214: hard to find.
1.1 anton 7215:
1.26 ! crook 7216: @item
! 7217: It allows using every selector to every object;
! 7218: this eliminates the need for classes, but makes it harder to create
! 7219: efficient implementations.
! 7220: @end itemize
1.1 anton 7221:
1.26 ! crook 7222: @cindex Pountain's object-oriented model
! 7223: Another well-known publication is @cite{Object-Oriented Forth} (Academic
! 7224: Press, London, 1987) by Dick Pountain. However, it is not really about
! 7225: object-oriented programming, because it hardly deals with late
! 7226: binding. Instead, it focuses on features like information hiding and
! 7227: overloading that are characteristic of modular languages like Ada (83).
1.1 anton 7228:
1.26 ! crook 7229: @cindex Zsoter's object-oriented model
! 7230: In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1) 1996, pages 31-35)
! 7231: Andras Zsoter describes a model that makes heavy use of an active object
! 7232: (like @code{this} in @file{objects.fs}): The active object is not only
! 7233: used for accessing all fields, but also specifies the receiving object
! 7234: of every selector invocation; you have to change the active object
! 7235: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
! 7236: changes more or less implicitly at @code{m: ... ;m}. Such a change at
! 7237: the method entry point is unnecessary with the Zsoter's model, because
! 7238: the receiving object is the active object already. On the other hand, the explicit
! 7239: change is absolutely necessary in that model, because otherwise no one
! 7240: could ever change the active object. An ANS Forth implementation of this
! 7241: model is available at @url{http://www.forth.org/fig/oopf.html}.
1.1 anton 7242:
1.26 ! crook 7243: @cindex @file{oof.fs}, differences to other models
! 7244: The @file{oof.fs} model combines information hiding and overloading
! 7245: resolution (by keeping names in various word lists) with object-oriented
! 7246: programming. It sets the active object implicitly on method entry, but
! 7247: also allows explicit changing (with @code{>o...o>} or with
! 7248: @code{with...endwith}). It uses parsing and state-smart objects and
! 7249: classes for resolving overloading and for early binding: the object or
! 7250: class parses the selector and determines the method from this. If the
! 7251: selector is not parsed by an object or class, it performs a call to the
! 7252: selector for the active object (late binding), like Zsoter's model.
! 7253: Fields are always accessed through the active object. The big
! 7254: disadvantage of this model is the parsing and the state-smartness, which
! 7255: reduces extensibility and increases the opportunities for subtle bugs;
! 7256: essentially, you are only safe if you never tick or @code{postpone} an
! 7257: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.1 anton 7258:
1.26 ! crook 7259: @cindex @file{mini-oof.fs}, differences to other models
! 7260: The @file{mini-oof.fs} model is quite similar to a very stripped-down version of
! 7261: the @file{objects.fs} model, but syntactically it is a mixture of the @file{objects.fs} and
! 7262: @file{oof.fs} models.
1.1 anton 7263:
1.26 ! crook 7264: @c -------------------------------------------------------------
! 7265: @node Passing Commands to the OS, Miscellaneous Words, Object-oriented Forth, Words
1.21 crook 7266: @section Passing Commands to the Operating System
7267: @cindex operating system - passing commands
7268: @cindex shell commands
7269:
7270: Gforth allows you to pass an arbitrary string to the host operating
7271: system shell (if such a thing exists) for execution.
7272:
7273: doc-sh
7274: doc-system
7275: doc-$?
1.23 crook 7276: doc-getenv
1.21 crook 7277:
1.26 ! crook 7278: @c -------------------------------------------------------------
1.21 crook 7279: @node Miscellaneous Words, , Passing Commands to the OS, Words
7280: @section Miscellaneous Words
7281: @cindex miscellaneous words
7282:
1.26 ! crook 7283: These section lists the ANS Forth words that are not documented
1.21 crook 7284: elsewhere in this manual. Ultimately, they all need proper homes.
7285:
7286: doc-,
7287: doc-allocate
7288: doc-allot
7289: doc-c,
7290: doc-here
7291: doc-ms
7292: doc-pad
7293: doc-parse
7294: doc-postpone
7295: doc-resize
7296: doc-time&date
7297: doc-unused
7298: doc-word
7299: doc-[compile]
1.23 crook 7300: doc-refill
1.21 crook 7301:
1.26 ! crook 7302: These ANS Forth words are not currently implemented in Gforth
1.21 crook 7303: (see TODO section on dependencies)
7304:
1.26 ! crook 7305: The following ANS Forth words are not currently supported by Gforth
1.21 crook 7306: (@pxref{ANS conformance})
7307:
7308: @code{EDITOR}
7309: @code{EKEY}
7310: @code{EKEY>CHAR}
7311: @code{EKEY?}
7312: @code{EMIT?}
7313: @code{FORGET}
7314:
1.24 anton 7315: @c ******************************************************************
7316: @node Error messages, Tools, Words, Top
7317: @chapter Error messages
7318: @cindex error messages
7319: @cindex backtrace
7320:
7321: A typical Gforth error message looks like this:
7322:
7323: @example
7324: in file included from :-1
7325: in file included from ./yyy.fs:1
7326: ./xxx.fs:4: Invalid memory address
7327: bar
7328: ^^^
1.25 anton 7329: $400E664C @@
7330: $400E6664 foo
1.24 anton 7331: @end example
7332:
7333: The message identifying the error is @code{Invalid memory address}. The
7334: error happened when text-interpreting line 4 of the file
7335: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
7336: word on the line where the error happened, is pointed out (with
7337: @code{^^^}).
7338:
7339: The file containing the error was included in line 1 of @file{./yyy.fs},
7340: and @file{yyy.fs} was included from a non-file (in this case, by giving
7341: @file{yyy.fs} as command-line parameter to Gforth).
7342:
7343: At the end of the error message you find a return stack dump that can be
7344: interpreted as a backtrace (possibly empty). On top you find the top of
7345: the return stack when the @code{throw} happened, and at the bottom you
7346: find the return stack entry just above the return stack of the topmost
7347: text interpreter.
7348:
7349: To the right of most return stack entries you see a guess for the word
7350: that pushed that return stack entry as its return address. This gives a
7351: backtrace. In our case we see that @code{bar} called @code{foo}, and
7352: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
7353: address} exception).
7354:
7355: Note that the backtrace is not perfect: We don't know which return stack
7356: entries are return addresses (so we may get false positives); and in
7357: some cases (e.g., for @code{abort"}) we cannot determine from the return
7358: address the word that pushed the return address, so for some return
7359: addresses you see no names in the return stack dump.
1.25 anton 7360:
7361: @cindex @code{catch} and backtraces
7362: The return stack dump represents the return stack at the time when a
7363: specific @code{throw} was executed. In programs that make use of
7364: @code{catch}, it is not necessarily clear which @code{throw} should be
7365: used for the return stack dump (e.g., consider one @code{throw} that
7366: indicates an error, which is caught, and during recovery another error
7367: happens; which @code{throw} should be used for the stack dump). Gforth
7368: presents the return stack dump for the first @code{throw} after the last
7369: executed (not returned-to) @code{catch}; this works well in the usual
7370: case.
7371:
7372: @cindex @code{gforth-fast} and backtraces
7373: @cindex @code{gforth-fast}, difference from @code{gforth}
7374: @cindex backtraces with @code{gforth-fast}
7375: @cindex return stack dump with @code{gforth-fast}
7376: @code{gforth} is able to do a return stack dump for throws generated
7377: from primitives (e.g., invalid memory address, stack empty etc.);
7378: @code{gforth-fast} is only able to do a return stack dump from a
7379: directly called @code{throw} (including @code{abort} etc.). This is the
7380: only difference (apart from a speed difference of about 30%) between
7381: @code{gforth} and @code{gforth-fast}. Given an exception caused by a
7382: primitive in @code{gforth-fast}, you will typically see no return stack
7383: dump at all; however, if the exception is caught by @code{catch} (e.g.,
7384: for restoring some state), and then @code{throw}n again, the return
7385: stack dump will be for the first such @code{throw}.
1.2 jwilke 7386:
1.5 anton 7387: @c ******************************************************************
1.24 anton 7388: @node Tools, ANS conformance, Error messages, Top
1.1 anton 7389: @chapter Tools
7390:
7391: @menu
7392: * ANS Report:: Report the words used, sorted by wordset.
7393: @end menu
7394:
7395: See also @ref{Emacs and Gforth}.
7396:
7397: @node ANS Report, , Tools, Tools
7398: @section @file{ans-report.fs}: Report the words used, sorted by wordset
7399: @cindex @file{ans-report.fs}
7400: @cindex report the words used in your program
7401: @cindex words used in your program
7402:
7403: If you want to label a Forth program as ANS Forth Program, you must
7404: document which wordsets the program uses; for extension wordsets, it is
7405: helpful to list the words the program requires from these wordsets
7406: (because Forth systems are allowed to provide only some words of them).
7407:
7408: The @file{ans-report.fs} tool makes it easy for you to determine which
7409: words from which wordset and which non-ANS words your application
7410: uses. You simply have to include @file{ans-report.fs} before loading the
7411: program you want to check. After loading your program, you can get the
7412: report with @code{print-ans-report}. A typical use is to run this as
7413: batch job like this:
7414: @example
7415: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
7416: @end example
7417:
7418: The output looks like this (for @file{compat/control.fs}):
7419: @example
7420: The program uses the following words
7421: from CORE :
7422: : POSTPONE THEN ; immediate ?dup IF 0=
7423: from BLOCK-EXT :
7424: \
7425: from FILE :
7426: (
7427: @end example
7428:
7429: @subsection Caveats
7430:
7431: Note that @file{ans-report.fs} just checks which words are used, not whether
7432: they are used in an ANS Forth conforming way!
7433:
7434: Some words are defined in several wordsets in the
7435: standard. @file{ans-report.fs} reports them for only one of the
7436: wordsets, and not necessarily the one you expect. It depends on usage
7437: which wordset is the right one to specify. E.g., if you only use the
7438: compilation semantics of @code{S"}, it is a Core word; if you also use
7439: its interpretation semantics, it is a File word.
7440:
7441: @c ******************************************************************
7442: @node ANS conformance, Model, Tools, Top
7443: @chapter ANS conformance
7444: @cindex ANS conformance of Gforth
7445:
7446: To the best of our knowledge, Gforth is an
7447:
7448: ANS Forth System
7449: @itemize @bullet
7450: @item providing the Core Extensions word set
7451: @item providing the Block word set
7452: @item providing the Block Extensions word set
7453: @item providing the Double-Number word set
7454: @item providing the Double-Number Extensions word set
7455: @item providing the Exception word set
7456: @item providing the Exception Extensions word set
7457: @item providing the Facility word set
7458: @item providing @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
7459: @item providing the File Access word set
7460: @item providing the File Access Extensions word set
7461: @item providing the Floating-Point word set
7462: @item providing the Floating-Point Extensions word set
7463: @item providing the Locals word set
7464: @item providing the Locals Extensions word set
7465: @item providing the Memory-Allocation word set
7466: @item providing the Memory-Allocation Extensions word set (that one's easy)
7467: @item providing the Programming-Tools word set
7468: @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
7469: @item providing the Search-Order word set
7470: @item providing the Search-Order Extensions word set
7471: @item providing the String word set
7472: @item providing the String Extensions word set (another easy one)
7473: @end itemize
7474:
7475: @cindex system documentation
7476: In addition, ANS Forth systems are required to document certain
7477: implementation choices. This chapter tries to meet these
7478: requirements. In many cases it gives a way to ask the system for the
7479: information instead of providing the information directly, in
7480: particular, if the information depends on the processor, the operating
7481: system or the installation options chosen, or if they are likely to
7482: change during the maintenance of Gforth.
7483:
7484: @comment The framework for the rest has been taken from pfe.
7485:
7486: @menu
7487: * The Core Words::
7488: * The optional Block word set::
7489: * The optional Double Number word set::
7490: * The optional Exception word set::
7491: * The optional Facility word set::
7492: * The optional File-Access word set::
7493: * The optional Floating-Point word set::
7494: * The optional Locals word set::
7495: * The optional Memory-Allocation word set::
7496: * The optional Programming-Tools word set::
7497: * The optional Search-Order word set::
7498: @end menu
7499:
7500:
7501: @c =====================================================================
7502: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
7503: @comment node-name, next, previous, up
7504: @section The Core Words
7505: @c =====================================================================
7506: @cindex core words, system documentation
7507: @cindex system documentation, core words
7508:
7509: @menu
7510: * core-idef:: Implementation Defined Options
7511: * core-ambcond:: Ambiguous Conditions
7512: * core-other:: Other System Documentation
7513: @end menu
7514:
7515: @c ---------------------------------------------------------------------
7516: @node core-idef, core-ambcond, The Core Words, The Core Words
7517: @subsection Implementation Defined Options
7518: @c ---------------------------------------------------------------------
7519: @cindex core words, implementation-defined options
7520: @cindex implementation-defined options, core words
7521:
7522:
7523: @table @i
7524: @item (Cell) aligned addresses:
7525: @cindex cell-aligned addresses
7526: @cindex aligned addresses
7527: processor-dependent. Gforth's alignment words perform natural alignment
7528: (e.g., an address aligned for a datum of size 8 is divisible by
7529: 8). Unaligned accesses usually result in a @code{-23 THROW}.
7530:
7531: @item @code{EMIT} and non-graphic characters:
7532: @cindex @code{EMIT} and non-graphic characters
7533: @cindex non-graphic characters and @code{EMIT}
7534: The character is output using the C library function (actually, macro)
7535: @code{putc}.
7536:
7537: @item character editing of @code{ACCEPT} and @code{EXPECT}:
7538: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
7539: @cindex editing in @code{ACCEPT} and @code{EXPECT}
7540: @cindex @code{ACCEPT}, editing
7541: @cindex @code{EXPECT}, editing
7542: This is modeled on the GNU readline library (@pxref{Readline
7543: Interaction, , Command Line Editing, readline, The GNU Readline
7544: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
7545: producing a full word completion every time you type it (instead of
7546: producing the common prefix of all completions).
7547:
7548: @item character set:
7549: @cindex character set
7550: The character set of your computer and display device. Gforth is
7551: 8-bit-clean (but some other component in your system may make trouble).
7552:
7553: @item Character-aligned address requirements:
7554: @cindex character-aligned address requirements
7555: installation-dependent. Currently a character is represented by a C
7556: @code{unsigned char}; in the future we might switch to @code{wchar_t}
7557: (Comments on that requested).
7558:
7559: @item character-set extensions and matching of names:
7560: @cindex character-set extensions and matching of names
1.26 ! crook 7561: @cindex case-sensitivity for name lookup
! 7562: @cindex name lookup, case-sensitivity
! 7563: @cindex locale and case-sensitivity
1.21 crook 7564: Any character except the ASCII NUL character can be used in a
1.1 anton 7565: name. Matching is case-insensitive (except in @code{TABLE}s). The
7566: matching is performed using the C function @code{strncasecmp}, whose
7567: function is probably influenced by the locale. E.g., the @code{C} locale
7568: does not know about accents and umlauts, so they are matched
7569: case-sensitively in that locale. For portability reasons it is best to
7570: write programs such that they work in the @code{C} locale. Then one can
7571: use libraries written by a Polish programmer (who might use words
7572: containing ISO Latin-2 encoded characters) and by a French programmer
7573: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
7574: funny results for some of the words (which ones, depends on the font you
7575: are using)). Also, the locale you prefer may not be available in other
7576: operating systems. Hopefully, Unicode will solve these problems one day.
7577:
7578: @item conditions under which control characters match a space delimiter:
7579: @cindex space delimiters
7580: @cindex control characters as delimiters
7581: If @code{WORD} is called with the space character as a delimiter, all
7582: white-space characters (as identified by the C macro @code{isspace()})
7583: are delimiters. @code{PARSE}, on the other hand, treats space like other
7584: delimiters. @code{PARSE-WORD} treats space like @code{WORD}, but behaves
7585: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
7586: interpreter (aka text interpreter) by default, treats all white-space
7587: characters as delimiters.
7588:
1.26 ! crook 7589: @item format of the control-flow stack:
! 7590: @cindex control-flow stack, format
! 7591: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 7592: stack item in cells is given by the constant @code{cs-item-size}. At the
7593: time of this writing, an item consists of a (pointer to a) locals list
7594: (third), an address in the code (second), and a tag for identifying the
7595: item (TOS). The following tags are used: @code{defstart},
7596: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
7597: @code{scopestart}.
7598:
7599: @item conversion of digits > 35
7600: @cindex digits > 35
7601: The characters @code{[\]^_'} are the digits with the decimal value
7602: 36@minus{}41. There is no way to input many of the larger digits.
7603:
7604: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
7605: @cindex @code{EXPECT}, display after end of input
7606: @cindex @code{ACCEPT}, display after end of input
7607: The cursor is moved to the end of the entered string. If the input is
7608: terminated using the @kbd{Return} key, a space is typed.
7609:
7610: @item exception abort sequence of @code{ABORT"}:
7611: @cindex exception abort sequence of @code{ABORT"}
7612: @cindex @code{ABORT"}, exception abort sequence
7613: The error string is stored into the variable @code{"error} and a
7614: @code{-2 throw} is performed.
7615:
7616: @item input line terminator:
7617: @cindex input line terminator
7618: @cindex line terminator on input
1.26 ! crook 7619: @cindex newline character on input
1.1 anton 7620: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
7621: lines. One of these characters is typically produced when you type the
7622: @kbd{Enter} or @kbd{Return} key.
7623:
7624: @item maximum size of a counted string:
7625: @cindex maximum size of a counted string
7626: @cindex counted string, maximum size
7627: @code{s" /counted-string" environment? drop .}. Currently 255 characters
7628: on all ports, but this may change.
7629:
7630: @item maximum size of a parsed string:
7631: @cindex maximum size of a parsed string
7632: @cindex parsed string, maximum size
7633: Given by the constant @code{/line}. Currently 255 characters.
7634:
7635: @item maximum size of a definition name, in characters:
7636: @cindex maximum size of a definition name, in characters
7637: @cindex name, maximum length
7638: 31
7639:
7640: @item maximum string length for @code{ENVIRONMENT?}, in characters:
7641: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
7642: @cindex @code{ENVIRONMENT?} string length, maximum
7643: 31
7644:
7645: @item method of selecting the user input device:
7646: @cindex user input device, method of selecting
7647: The user input device is the standard input. There is currently no way to
7648: change it from within Gforth. However, the input can typically be
7649: redirected in the command line that starts Gforth.
7650:
7651: @item method of selecting the user output device:
7652: @cindex user output device, method of selecting
7653: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 7654: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
7655: output when the user output device is a terminal, otherwise the output
7656: is buffered.
1.1 anton 7657:
7658: @item methods of dictionary compilation:
7659: What are we expected to document here?
7660:
7661: @item number of bits in one address unit:
7662: @cindex number of bits in one address unit
7663: @cindex address unit, size in bits
7664: @code{s" address-units-bits" environment? drop .}. 8 in all current
7665: ports.
7666:
7667: @item number representation and arithmetic:
7668: @cindex number representation and arithmetic
7669: Processor-dependent. Binary two's complement on all current ports.
7670:
7671: @item ranges for integer types:
7672: @cindex ranges for integer types
7673: @cindex integer types, ranges
7674: Installation-dependent. Make environmental queries for @code{MAX-N},
7675: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
7676: unsigned (and positive) types is 0. The lower bound for signed types on
7677: two's complement and one's complement machines machines can be computed
7678: by adding 1 to the upper bound.
7679:
7680: @item read-only data space regions:
7681: @cindex read-only data space regions
7682: @cindex data-space, read-only regions
7683: The whole Forth data space is writable.
7684:
7685: @item size of buffer at @code{WORD}:
7686: @cindex size of buffer at @code{WORD}
7687: @cindex @code{WORD} buffer size
7688: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
7689: shared with the pictured numeric output string. If overwriting
7690: @code{PAD} is acceptable, it is as large as the remaining dictionary
7691: space, although only as much can be sensibly used as fits in a counted
7692: string.
7693:
7694: @item size of one cell in address units:
7695: @cindex cell size
7696: @code{1 cells .}.
7697:
7698: @item size of one character in address units:
7699: @cindex char size
7700: @code{1 chars .}. 1 on all current ports.
7701:
7702: @item size of the keyboard terminal buffer:
7703: @cindex size of the keyboard terminal buffer
7704: @cindex terminal buffer, size
7705: Varies. You can determine the size at a specific time using @code{lp@@
7706: tib - .}. It is shared with the locals stack and TIBs of files that
7707: include the current file. You can change the amount of space for TIBs
7708: and locals stack at Gforth startup with the command line option
7709: @code{-l}.
7710:
7711: @item size of the pictured numeric output buffer:
7712: @cindex size of the pictured numeric output buffer
7713: @cindex pictured numeric output buffer, size
7714: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
7715: shared with @code{WORD}.
7716:
7717: @item size of the scratch area returned by @code{PAD}:
7718: @cindex size of the scratch area returned by @code{PAD}
7719: @cindex @code{PAD} size
7720: The remainder of dictionary space. @code{unused pad here - - .}.
7721:
7722: @item system case-sensitivity characteristics:
7723: @cindex case-sensitivity characteristics
1.26 ! crook 7724: Dictionary searches are case-insensitive (except in
1.1 anton 7725: @code{TABLE}s). However, as explained above under @i{character-set
7726: extensions}, the matching for non-ASCII characters is determined by the
7727: locale you are using. In the default @code{C} locale all non-ASCII
7728: characters are matched case-sensitively.
7729:
7730: @item system prompt:
7731: @cindex system prompt
7732: @cindex prompt
7733: @code{ ok} in interpret state, @code{ compiled} in compile state.
7734:
7735: @item division rounding:
7736: @cindex division rounding
7737: installation dependent. @code{s" floored" environment? drop .}. We leave
7738: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
7739: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
7740:
7741: @item values of @code{STATE} when true:
7742: @cindex @code{STATE} values
7743: -1.
7744:
7745: @item values returned after arithmetic overflow:
7746: On two's complement machines, arithmetic is performed modulo
7747: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
7748: arithmetic (with appropriate mapping for signed types). Division by zero
7749: typically results in a @code{-55 throw} (Floating-point unidentified
7750: fault), although a @code{-10 throw} (divide by zero) would be more
7751: appropriate.
7752:
7753: @item whether the current definition can be found after @t{DOES>}:
7754: @cindex @t{DOES>}, visibility of current definition
7755: No.
7756:
7757: @end table
7758:
7759: @c ---------------------------------------------------------------------
7760: @node core-ambcond, core-other, core-idef, The Core Words
7761: @subsection Ambiguous conditions
7762: @c ---------------------------------------------------------------------
7763: @cindex core words, ambiguous conditions
7764: @cindex ambiguous conditions, core words
7765:
7766: @table @i
7767:
7768: @item a name is neither a word nor a number:
7769: @cindex name not found
1.26 ! crook 7770: @cindex undefined word
1.1 anton 7771: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
7772: preserves the data and FP stack, so you don't lose more work than
7773: necessary.
7774:
7775: @item a definition name exceeds the maximum length allowed:
1.26 ! crook 7776: @cindex word name too long
1.1 anton 7777: @code{-19 throw} (Word name too long)
7778:
7779: @item addressing a region not inside the various data spaces of the forth system:
7780: @cindex Invalid memory address
7781: The stacks, code space and name space are accessible. Machine code space is
7782: typically readable. Accessing other addresses gives results dependent on
7783: the operating system. On decent systems: @code{-9 throw} (Invalid memory
7784: address).
7785:
7786: @item argument type incompatible with parameter:
1.26 ! crook 7787: @cindex argument type mismatch
1.1 anton 7788: This is usually not caught. Some words perform checks, e.g., the control
7789: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
7790: mismatch).
7791:
7792: @item attempting to obtain the execution token of a word with undefined execution semantics:
7793: @cindex Interpreting a compile-only word, for @code{'} etc.
7794: @cindex execution token of words with undefined execution semantics
7795: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
7796: get an execution token for @code{compile-only-error} (which performs a
7797: @code{-14 throw} when executed).
7798:
7799: @item dividing by zero:
7800: @cindex dividing by zero
7801: @cindex floating point unidentified fault, integer division
1.24 anton 7802: On better platforms, this produces a @code{-10 throw} (Division by
7803: zero); on other systems, this typically results in a @code{-55 throw}
7804: (Floating-point unidentified fault).
1.1 anton 7805:
7806: @item insufficient data stack or return stack space:
7807: @cindex insufficient data stack or return stack space
7808: @cindex stack overflow
1.26 ! crook 7809: @cindex address alignment exception, stack overflow
1.1 anton 7810: @cindex Invalid memory address, stack overflow
7811: Depending on the operating system, the installation, and the invocation
7812: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 7813: it is not checked. If it is checked, you typically get a @code{-3 throw}
7814: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
7815: throw} (Invalid memory address) (depending on the platform and how you
7816: achieved the overflow) as soon as the overflow happens. If it is not
7817: checked, overflows typically result in mysterious illegal memory
7818: accesses, producing @code{-9 throw} (Invalid memory address) or
7819: @code{-23 throw} (Address alignment exception); they might also destroy
7820: the internal data structure of @code{ALLOCATE} and friends, resulting in
7821: various errors in these words.
1.1 anton 7822:
7823: @item insufficient space for loop control parameters:
7824: @cindex insufficient space for loop control parameters
7825: like other return stack overflows.
7826:
7827: @item insufficient space in the dictionary:
7828: @cindex insufficient space in the dictionary
7829: @cindex dictionary overflow
1.12 anton 7830: If you try to allot (either directly with @code{allot}, or indirectly
7831: with @code{,}, @code{create} etc.) more memory than available in the
7832: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
7833: to access memory beyond the end of the dictionary, the results are
7834: similar to stack overflows.
1.1 anton 7835:
7836: @item interpreting a word with undefined interpretation semantics:
7837: @cindex interpreting a word with undefined interpretation semantics
7838: @cindex Interpreting a compile-only word
7839: For some words, we have defined interpretation semantics. For the
7840: others: @code{-14 throw} (Interpreting a compile-only word).
7841:
7842: @item modifying the contents of the input buffer or a string literal:
7843: @cindex modifying the contents of the input buffer or a string literal
7844: These are located in writable memory and can be modified.
7845:
7846: @item overflow of the pictured numeric output string:
7847: @cindex overflow of the pictured numeric output string
7848: @cindex pictured numeric output string, overflow
1.24 anton 7849: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 7850:
7851: @item parsed string overflow:
7852: @cindex parsed string overflow
7853: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
7854:
7855: @item producing a result out of range:
7856: @cindex result out of range
7857: On two's complement machines, arithmetic is performed modulo
7858: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
7859: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 7860: typically results in a @code{-10 throw} (divide by zero) or @code{-55
7861: throw} (floating point unidentified fault). @code{convert} and
7862: @code{>number} currently overflow silently.
1.1 anton 7863:
7864: @item reading from an empty data or return stack:
7865: @cindex stack empty
7866: @cindex stack underflow
1.24 anton 7867: @cindex return stack underflow
1.1 anton 7868: The data stack is checked by the outer (aka text) interpreter after
7869: every word executed. If it has underflowed, a @code{-4 throw} (Stack
7870: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 7871: depending on operating system, installation, and invocation. If they are
7872: caught by a check, they typically result in @code{-4 throw} (Stack
7873: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
7874: (Invalid memory address), depending on the platform and which stack
7875: underflows and by how much. Note that even if the system uses checking
7876: (through the MMU), your program may have to underflow by a significant
7877: number of stack items to trigger the reaction (the reason for this is
7878: that the MMU, and therefore the checking, works with a page-size
7879: granularity). If there is no checking, the symptoms resulting from an
7880: underflow are similar to those from an overflow. Unbalanced return
7881: stack errors result in a variaty of symptoms, including @code{-9 throw}
7882: (Invalid memory address) and Illegal Instruction (typically @code{-260
7883: throw}).
1.1 anton 7884:
7885: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
7886: @cindex unexpected end of the input buffer
7887: @cindex zero-length string as a name
7888: @cindex Attempt to use zero-length string as a name
7889: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
7890: use zero-length string as a name). Words like @code{'} probably will not
7891: find what they search. Note that it is possible to create zero-length
7892: names with @code{nextname} (should it not?).
7893:
7894: @item @code{>IN} greater than input buffer:
7895: @cindex @code{>IN} greater than input buffer
7896: The next invocation of a parsing word returns a string with length 0.
7897:
7898: @item @code{RECURSE} appears after @code{DOES>}:
7899: @cindex @code{RECURSE} appears after @code{DOES>}
7900: Compiles a recursive call to the defining word, not to the defined word.
7901:
7902: @item argument input source different than current input source for @code{RESTORE-INPUT}:
7903: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 ! crook 7904: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 7905: @cindex @code{RESTORE-INPUT}, Argument type mismatch
7906: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
7907: the end of the file was reached), its source-id may be
7908: reused. Therefore, restoring an input source specification referencing a
7909: closed file may lead to unpredictable results instead of a @code{-12
7910: THROW}.
7911:
7912: In the future, Gforth may be able to restore input source specifications
7913: from other than the current input source.
7914:
7915: @item data space containing definitions gets de-allocated:
7916: @cindex data space containing definitions gets de-allocated
7917: Deallocation with @code{allot} is not checked. This typically results in
7918: memory access faults or execution of illegal instructions.
7919:
7920: @item data space read/write with incorrect alignment:
7921: @cindex data space read/write with incorrect alignment
7922: @cindex alignment faults
1.26 ! crook 7923: @cindex address alignment exception
1.1 anton 7924: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 7925: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 7926: alignment turned on, incorrect alignment results in a @code{-9 throw}
7927: (Invalid memory address). There are reportedly some processors with
1.12 anton 7928: alignment restrictions that do not report violations.
1.1 anton 7929:
7930: @item data space pointer not properly aligned, @code{,}, @code{C,}:
7931: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
7932: Like other alignment errors.
7933:
7934: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
7935: Like other stack underflows.
7936:
7937: @item loop control parameters not available:
7938: @cindex loop control parameters not available
7939: Not checked. The counted loop words simply assume that the top of return
7940: stack items are loop control parameters and behave accordingly.
7941:
7942: @item most recent definition does not have a name (@code{IMMEDIATE}):
7943: @cindex most recent definition does not have a name (@code{IMMEDIATE})
7944: @cindex last word was headerless
7945: @code{abort" last word was headerless"}.
7946:
7947: @item name not defined by @code{VALUE} used by @code{TO}:
7948: @cindex name not defined by @code{VALUE} used by @code{TO}
7949: @cindex @code{TO} on non-@code{VALUE}s
7950: @cindex Invalid name argument, @code{TO}
7951: @code{-32 throw} (Invalid name argument) (unless name is a local or was
7952: defined by @code{CONSTANT}; in the latter case it just changes the constant).
7953:
7954: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
7955: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 ! crook 7956: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 7957: @code{-13 throw} (Undefined word)
7958:
7959: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
7960: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
7961: Gforth behaves as if they were of the same type. I.e., you can predict
7962: the behaviour by interpreting all parameters as, e.g., signed.
7963:
7964: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
7965: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
7966: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
7967: compilation semantics of @code{TO}.
7968:
7969: @item String longer than a counted string returned by @code{WORD}:
1.26 ! crook 7970: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 7971: @cindex @code{WORD}, string overflow
7972: Not checked. The string will be ok, but the count will, of course,
7973: contain only the least significant bits of the length.
7974:
7975: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
7976: @cindex @code{LSHIFT}, large shift counts
7977: @cindex @code{RSHIFT}, large shift counts
7978: Processor-dependent. Typical behaviours are returning 0 and using only
7979: the low bits of the shift count.
7980:
7981: @item word not defined via @code{CREATE}:
7982: @cindex @code{>BODY} of non-@code{CREATE}d words
7983: @code{>BODY} produces the PFA of the word no matter how it was defined.
7984:
7985: @cindex @code{DOES>} of non-@code{CREATE}d words
7986: @code{DOES>} changes the execution semantics of the last defined word no
7987: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
7988: @code{CREATE , DOES>}.
7989:
7990: @item words improperly used outside @code{<#} and @code{#>}:
7991: Not checked. As usual, you can expect memory faults.
7992:
7993: @end table
7994:
7995:
7996: @c ---------------------------------------------------------------------
7997: @node core-other, , core-ambcond, The Core Words
7998: @subsection Other system documentation
7999: @c ---------------------------------------------------------------------
8000: @cindex other system documentation, core words
8001: @cindex core words, other system documentation
8002:
8003: @table @i
8004: @item nonstandard words using @code{PAD}:
8005: @cindex @code{PAD} use by nonstandard words
8006: None.
8007:
8008: @item operator's terminal facilities available:
8009: @cindex operator's terminal facilities available
8010: After processing the command line, Gforth goes into interactive mode,
8011: and you can give commands to Gforth interactively. The actual facilities
8012: available depend on how you invoke Gforth.
8013:
8014: @item program data space available:
8015: @cindex program data space available
8016: @cindex data space available
8017: @code{UNUSED .} gives the remaining dictionary space. The total
8018: dictionary space can be specified with the @code{-m} switch
8019: (@pxref{Invoking Gforth}) when Gforth starts up.
8020:
8021: @item return stack space available:
8022: @cindex return stack space available
8023: You can compute the total return stack space in cells with
8024: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
8025: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
8026:
8027: @item stack space available:
8028: @cindex stack space available
8029: You can compute the total data stack space in cells with
8030: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
8031: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
8032:
8033: @item system dictionary space required, in address units:
8034: @cindex system dictionary space required, in address units
8035: Type @code{here forthstart - .} after startup. At the time of this
8036: writing, this gives 80080 (bytes) on a 32-bit system.
8037: @end table
8038:
8039:
8040: @c =====================================================================
8041: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
8042: @section The optional Block word set
8043: @c =====================================================================
8044: @cindex system documentation, block words
8045: @cindex block words, system documentation
8046:
8047: @menu
8048: * block-idef:: Implementation Defined Options
8049: * block-ambcond:: Ambiguous Conditions
8050: * block-other:: Other System Documentation
8051: @end menu
8052:
8053:
8054: @c ---------------------------------------------------------------------
8055: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
8056: @subsection Implementation Defined Options
8057: @c ---------------------------------------------------------------------
8058: @cindex implementation-defined options, block words
8059: @cindex block words, implementation-defined options
8060:
8061: @table @i
8062: @item the format for display by @code{LIST}:
8063: @cindex @code{LIST} display format
8064: First the screen number is displayed, then 16 lines of 64 characters,
8065: each line preceded by the line number.
8066:
8067: @item the length of a line affected by @code{\}:
8068: @cindex length of a line affected by @code{\}
8069: @cindex @code{\}, line length in blocks
8070: 64 characters.
8071: @end table
8072:
8073:
8074: @c ---------------------------------------------------------------------
8075: @node block-ambcond, block-other, block-idef, The optional Block word set
8076: @subsection Ambiguous conditions
8077: @c ---------------------------------------------------------------------
8078: @cindex block words, ambiguous conditions
8079: @cindex ambiguous conditions, block words
8080:
8081: @table @i
8082: @item correct block read was not possible:
8083: @cindex block read not possible
8084: Typically results in a @code{throw} of some OS-derived value (between
8085: -512 and -2048). If the blocks file was just not long enough, blanks are
8086: supplied for the missing portion.
8087:
8088: @item I/O exception in block transfer:
8089: @cindex I/O exception in block transfer
8090: @cindex block transfer, I/O exception
8091: Typically results in a @code{throw} of some OS-derived value (between
8092: -512 and -2048).
8093:
8094: @item invalid block number:
8095: @cindex invalid block number
8096: @cindex block number invalid
8097: @code{-35 throw} (Invalid block number)
8098:
8099: @item a program directly alters the contents of @code{BLK}:
8100: @cindex @code{BLK}, altering @code{BLK}
8101: The input stream is switched to that other block, at the same
8102: position. If the storing to @code{BLK} happens when interpreting
8103: non-block input, the system will get quite confused when the block ends.
8104:
8105: @item no current block buffer for @code{UPDATE}:
8106: @cindex @code{UPDATE}, no current block buffer
8107: @code{UPDATE} has no effect.
8108:
8109: @end table
8110:
8111: @c ---------------------------------------------------------------------
8112: @node block-other, , block-ambcond, The optional Block word set
8113: @subsection Other system documentation
8114: @c ---------------------------------------------------------------------
8115: @cindex other system documentation, block words
8116: @cindex block words, other system documentation
8117:
8118: @table @i
8119: @item any restrictions a multiprogramming system places on the use of buffer addresses:
8120: No restrictions (yet).
8121:
8122: @item the number of blocks available for source and data:
8123: depends on your disk space.
8124:
8125: @end table
8126:
8127:
8128: @c =====================================================================
8129: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
8130: @section The optional Double Number word set
8131: @c =====================================================================
8132: @cindex system documentation, double words
8133: @cindex double words, system documentation
8134:
8135: @menu
8136: * double-ambcond:: Ambiguous Conditions
8137: @end menu
8138:
8139:
8140: @c ---------------------------------------------------------------------
8141: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
8142: @subsection Ambiguous conditions
8143: @c ---------------------------------------------------------------------
8144: @cindex double words, ambiguous conditions
8145: @cindex ambiguous conditions, double words
8146:
8147: @table @i
8148: @item @var{d} outside of range of @var{n} in @code{D>S}:
8149: @cindex @code{D>S}, @var{d} out of range of @var{n}
8150: The least significant cell of @var{d} is produced.
8151:
8152: @end table
8153:
8154:
8155: @c =====================================================================
8156: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
8157: @section The optional Exception word set
8158: @c =====================================================================
8159: @cindex system documentation, exception words
8160: @cindex exception words, system documentation
8161:
8162: @menu
8163: * exception-idef:: Implementation Defined Options
8164: @end menu
8165:
8166:
8167: @c ---------------------------------------------------------------------
8168: @node exception-idef, , The optional Exception word set, The optional Exception word set
8169: @subsection Implementation Defined Options
8170: @c ---------------------------------------------------------------------
8171: @cindex implementation-defined options, exception words
8172: @cindex exception words, implementation-defined options
8173:
8174: @table @i
8175: @item @code{THROW}-codes used in the system:
8176: @cindex @code{THROW}-codes used in the system
8177: The codes -256@minus{}-511 are used for reporting signals. The mapping
8178: from OS signal numbers to throw codes is -256@minus{}@var{signal}. The
8179: codes -512@minus{}-2047 are used for OS errors (for file and memory
8180: allocation operations). The mapping from OS error numbers to throw codes
8181: is -512@minus{}@code{errno}. One side effect of this mapping is that
8182: undefined OS errors produce a message with a strange number; e.g.,
8183: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
8184: @end table
8185:
8186: @c =====================================================================
8187: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
8188: @section The optional Facility word set
8189: @c =====================================================================
8190: @cindex system documentation, facility words
8191: @cindex facility words, system documentation
8192:
8193: @menu
8194: * facility-idef:: Implementation Defined Options
8195: * facility-ambcond:: Ambiguous Conditions
8196: @end menu
8197:
8198:
8199: @c ---------------------------------------------------------------------
8200: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
8201: @subsection Implementation Defined Options
8202: @c ---------------------------------------------------------------------
8203: @cindex implementation-defined options, facility words
8204: @cindex facility words, implementation-defined options
8205:
8206: @table @i
8207: @item encoding of keyboard events (@code{EKEY}):
8208: @cindex keyboard events, encoding in @code{EKEY}
8209: @cindex @code{EKEY}, encoding of keyboard events
8210: Not yet implemented.
8211:
8212: @item duration of a system clock tick:
8213: @cindex duration of a system clock tick
8214: @cindex clock tick duration
8215: System dependent. With respect to @code{MS}, the time is specified in
8216: microseconds. How well the OS and the hardware implement this, is
8217: another question.
8218:
8219: @item repeatability to be expected from the execution of @code{MS}:
8220: @cindex repeatability to be expected from the execution of @code{MS}
8221: @cindex @code{MS}, repeatability to be expected
8222: System dependent. On Unix, a lot depends on load. If the system is
8223: lightly loaded, and the delay is short enough that Gforth does not get
8224: swapped out, the performance should be acceptable. Under MS-DOS and
8225: other single-tasking systems, it should be good.
8226:
8227: @end table
8228:
8229:
8230: @c ---------------------------------------------------------------------
8231: @node facility-ambcond, , facility-idef, The optional Facility word set
8232: @subsection Ambiguous conditions
8233: @c ---------------------------------------------------------------------
8234: @cindex facility words, ambiguous conditions
8235: @cindex ambiguous conditions, facility words
8236:
8237: @table @i
8238: @item @code{AT-XY} can't be performed on user output device:
8239: @cindex @code{AT-XY} can't be performed on user output device
8240: Largely terminal dependent. No range checks are done on the arguments.
8241: No errors are reported. You may see some garbage appearing, you may see
8242: simply nothing happen.
8243:
8244: @end table
8245:
8246:
8247: @c =====================================================================
8248: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
8249: @section The optional File-Access word set
8250: @c =====================================================================
8251: @cindex system documentation, file words
8252: @cindex file words, system documentation
8253:
8254: @menu
8255: * file-idef:: Implementation Defined Options
8256: * file-ambcond:: Ambiguous Conditions
8257: @end menu
8258:
8259: @c ---------------------------------------------------------------------
8260: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
8261: @subsection Implementation Defined Options
8262: @c ---------------------------------------------------------------------
8263: @cindex implementation-defined options, file words
8264: @cindex file words, implementation-defined options
8265:
8266: @table @i
8267: @item file access methods used:
8268: @cindex file access methods used
8269: @code{R/O}, @code{R/W} and @code{BIN} work as you would
8270: expect. @code{W/O} translates into the C file opening mode @code{w} (or
8271: @code{wb}): The file is cleared, if it exists, and created, if it does
8272: not (with both @code{open-file} and @code{create-file}). Under Unix
8273: @code{create-file} creates a file with 666 permissions modified by your
8274: umask.
8275:
8276: @item file exceptions:
8277: @cindex file exceptions
8278: The file words do not raise exceptions (except, perhaps, memory access
8279: faults when you pass illegal addresses or file-ids).
8280:
8281: @item file line terminator:
8282: @cindex file line terminator
8283: System-dependent. Gforth uses C's newline character as line
8284: terminator. What the actual character code(s) of this are is
8285: system-dependent.
8286:
8287: @item file name format:
8288: @cindex file name format
8289: System dependent. Gforth just uses the file name format of your OS.
8290:
8291: @item information returned by @code{FILE-STATUS}:
8292: @cindex @code{FILE-STATUS}, returned information
8293: @code{FILE-STATUS} returns the most powerful file access mode allowed
8294: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
8295: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
8296: along with the returned mode.
8297:
8298: @item input file state after an exception when including source:
8299: @cindex exception when including source
8300: All files that are left via the exception are closed.
8301:
8302: @item @var{ior} values and meaning:
8303: @cindex @var{ior} values and meaning
8304: The @var{ior}s returned by the file and memory allocation words are
8305: intended as throw codes. They typically are in the range
8306: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
8307: @var{ior}s is -512@minus{}@var{errno}.
8308:
8309: @item maximum depth of file input nesting:
8310: @cindex maximum depth of file input nesting
8311: @cindex file input nesting, maximum depth
8312: limited by the amount of return stack, locals/TIB stack, and the number
8313: of open files available. This should not give you troubles.
8314:
8315: @item maximum size of input line:
8316: @cindex maximum size of input line
8317: @cindex input line size, maximum
8318: @code{/line}. Currently 255.
8319:
8320: @item methods of mapping block ranges to files:
8321: @cindex mapping block ranges to files
8322: @cindex files containing blocks
8323: @cindex blocks in files
8324: By default, blocks are accessed in the file @file{blocks.fb} in the
8325: current working directory. The file can be switched with @code{USE}.
8326:
8327: @item number of string buffers provided by @code{S"}:
8328: @cindex @code{S"}, number of string buffers
8329: 1
8330:
8331: @item size of string buffer used by @code{S"}:
8332: @cindex @code{S"}, size of string buffer
8333: @code{/line}. currently 255.
8334:
8335: @end table
8336:
8337: @c ---------------------------------------------------------------------
8338: @node file-ambcond, , file-idef, The optional File-Access word set
8339: @subsection Ambiguous conditions
8340: @c ---------------------------------------------------------------------
8341: @cindex file words, ambiguous conditions
8342: @cindex ambiguous conditions, file words
8343:
8344: @table @i
8345: @item attempting to position a file outside its boundaries:
8346: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
8347: @code{REPOSITION-FILE} is performed as usual: Afterwards,
8348: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
8349:
8350: @item attempting to read from file positions not yet written:
8351: @cindex reading from file positions not yet written
8352: End-of-file, i.e., zero characters are read and no error is reported.
8353:
8354: @item @var{file-id} is invalid (@code{INCLUDE-FILE}):
8355: @cindex @code{INCLUDE-FILE}, @var{file-id} is invalid
8356: An appropriate exception may be thrown, but a memory fault or other
8357: problem is more probable.
8358:
8359: @item I/O exception reading or closing @var{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
8360: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @var{file-id}
8361: @cindex @code{INCLUDED}, I/O exception reading or closing @var{file-id}
8362: The @var{ior} produced by the operation, that discovered the problem, is
8363: thrown.
8364:
8365: @item named file cannot be opened (@code{INCLUDED}):
8366: @cindex @code{INCLUDED}, named file cannot be opened
8367: The @var{ior} produced by @code{open-file} is thrown.
8368:
8369: @item requesting an unmapped block number:
8370: @cindex unmapped block numbers
8371: There are no unmapped legal block numbers. On some operating systems,
8372: writing a block with a large number may overflow the file system and
8373: have an error message as consequence.
8374:
8375: @item using @code{source-id} when @code{blk} is non-zero:
8376: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
8377: @code{source-id} performs its function. Typically it will give the id of
8378: the source which loaded the block. (Better ideas?)
8379:
8380: @end table
8381:
8382:
8383: @c =====================================================================
8384: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
8385: @section The optional Floating-Point word set
8386: @c =====================================================================
8387: @cindex system documentation, floating-point words
8388: @cindex floating-point words, system documentation
8389:
8390: @menu
8391: * floating-idef:: Implementation Defined Options
8392: * floating-ambcond:: Ambiguous Conditions
8393: @end menu
8394:
8395:
8396: @c ---------------------------------------------------------------------
8397: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
8398: @subsection Implementation Defined Options
8399: @c ---------------------------------------------------------------------
8400: @cindex implementation-defined options, floating-point words
8401: @cindex floating-point words, implementation-defined options
8402:
8403: @table @i
8404: @item format and range of floating point numbers:
8405: @cindex format and range of floating point numbers
8406: @cindex floating point numbers, format and range
8407: System-dependent; the @code{double} type of C.
8408:
8409: @item results of @code{REPRESENT} when @var{float} is out of range:
8410: @cindex @code{REPRESENT}, results when @var{float} is out of range
8411: System dependent; @code{REPRESENT} is implemented using the C library
8412: function @code{ecvt()} and inherits its behaviour in this respect.
8413:
8414: @item rounding or truncation of floating-point numbers:
8415: @cindex rounding of floating-point numbers
8416: @cindex truncation of floating-point numbers
8417: @cindex floating-point numbers, rounding or truncation
8418: System dependent; the rounding behaviour is inherited from the hosting C
8419: compiler. IEEE-FP-based (i.e., most) systems by default round to
8420: nearest, and break ties by rounding to even (i.e., such that the last
8421: bit of the mantissa is 0).
8422:
8423: @item size of floating-point stack:
8424: @cindex floating-point stack size
8425: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
8426: the floating-point stack (in floats). You can specify this on startup
8427: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
8428:
8429: @item width of floating-point stack:
8430: @cindex floating-point stack width
8431: @code{1 floats}.
8432:
8433: @end table
8434:
8435:
8436: @c ---------------------------------------------------------------------
8437: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
8438: @subsection Ambiguous conditions
8439: @c ---------------------------------------------------------------------
8440: @cindex floating-point words, ambiguous conditions
8441: @cindex ambiguous conditions, floating-point words
8442:
8443: @table @i
8444: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
8445: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
8446: System-dependent. Typically results in a @code{-23 THROW} like other
8447: alignment violations.
8448:
8449: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
8450: @cindex @code{f@@} used with an address that is not float aligned
8451: @cindex @code{f!} used with an address that is not float aligned
8452: System-dependent. Typically results in a @code{-23 THROW} like other
8453: alignment violations.
8454:
8455: @item floating-point result out of range:
8456: @cindex floating-point result out of range
8457: System-dependent. Can result in a @code{-55 THROW} (Floating-point
8458: unidentified fault), or can produce a special value representing, e.g.,
8459: Infinity.
8460:
8461: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
8462: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
8463: System-dependent. Typically results in an alignment fault like other
8464: alignment violations.
8465:
8466: @item @code{BASE} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
8467: @cindex @code{BASE} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
8468: The floating-point number is converted into decimal nonetheless.
8469:
8470: @item Both arguments are equal to zero (@code{FATAN2}):
8471: @cindex @code{FATAN2}, both arguments are equal to zero
8472: System-dependent. @code{FATAN2} is implemented using the C library
8473: function @code{atan2()}.
8474:
8475: @item Using @code{FTAN} on an argument @var{r1} where cos(@var{r1}) is zero:
8476: @cindex @code{FTAN} on an argument @var{r1} where cos(@var{r1}) is zero
8477: System-dependent. Anyway, typically the cos of @var{r1} will not be zero
8478: because of small errors and the tan will be a very large (or very small)
8479: but finite number.
8480:
8481: @item @var{d} cannot be presented precisely as a float in @code{D>F}:
8482: @cindex @code{D>F}, @var{d} cannot be presented precisely as a float
8483: The result is rounded to the nearest float.
8484:
8485: @item dividing by zero:
8486: @cindex dividing by zero, floating-point
8487: @cindex floating-point dividing by zero
8488: @cindex floating-point unidentified fault, FP divide-by-zero
8489: @code{-55 throw} (Floating-point unidentified fault)
8490:
8491: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
8492: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
8493: System dependent. On IEEE-FP based systems the number is converted into
8494: an infinity.
8495:
8496: @item @var{float}<1 (@code{FACOSH}):
8497: @cindex @code{FACOSH}, @var{float}<1
8498: @cindex floating-point unidentified fault, @code{FACOSH}
8499: @code{-55 throw} (Floating-point unidentified fault)
8500:
8501: @item @var{float}=<-1 (@code{FLNP1}):
8502: @cindex @code{FLNP1}, @var{float}=<-1
8503: @cindex floating-point unidentified fault, @code{FLNP1}
8504: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
8505: negative infinity is typically produced for @var{float}=-1.
8506:
8507: @item @var{float}=<0 (@code{FLN}, @code{FLOG}):
8508: @cindex @code{FLN}, @var{float}=<0
8509: @cindex @code{FLOG}, @var{float}=<0
8510: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
8511: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
8512: negative infinity is typically produced for @var{float}=0.
8513:
8514: @item @var{float}<0 (@code{FASINH}, @code{FSQRT}):
8515: @cindex @code{FASINH}, @var{float}<0
8516: @cindex @code{FSQRT}, @var{float}<0
8517: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
8518: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
8519: produces values for these inputs on my Linux box (Bug in the C library?)
8520:
8521: @item |@var{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
8522: @cindex @code{FACOS}, |@var{float}|>1
8523: @cindex @code{FASIN}, |@var{float}|>1
8524: @cindex @code{FATANH}, |@var{float}|>1
8525: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
8526: @code{-55 throw} (Floating-point unidentified fault).
8527:
8528: @item integer part of float cannot be represented by @var{d} in @code{F>D}:
8529: @cindex @code{F>D}, integer part of float cannot be represented by @var{d}
8530: @cindex floating-point unidentified fault, @code{F>D}
8531: @code{-55 throw} (Floating-point unidentified fault).
8532:
8533: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
8534: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
8535: This does not happen.
8536: @end table
8537:
8538: @c =====================================================================
8539: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
8540: @section The optional Locals word set
8541: @c =====================================================================
8542: @cindex system documentation, locals words
8543: @cindex locals words, system documentation
8544:
8545: @menu
8546: * locals-idef:: Implementation Defined Options
8547: * locals-ambcond:: Ambiguous Conditions
8548: @end menu
8549:
8550:
8551: @c ---------------------------------------------------------------------
8552: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
8553: @subsection Implementation Defined Options
8554: @c ---------------------------------------------------------------------
8555: @cindex implementation-defined options, locals words
8556: @cindex locals words, implementation-defined options
8557:
8558: @table @i
8559: @item maximum number of locals in a definition:
8560: @cindex maximum number of locals in a definition
8561: @cindex locals, maximum number in a definition
8562: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
8563: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
8564: characters. The number of locals in a definition is bounded by the size
8565: of locals-buffer, which contains the names of the locals.
8566:
8567: @end table
8568:
8569:
8570: @c ---------------------------------------------------------------------
8571: @node locals-ambcond, , locals-idef, The optional Locals word set
8572: @subsection Ambiguous conditions
8573: @c ---------------------------------------------------------------------
8574: @cindex locals words, ambiguous conditions
8575: @cindex ambiguous conditions, locals words
8576:
8577: @table @i
8578: @item executing a named local in interpretation state:
8579: @cindex local in interpretation state
8580: @cindex Interpreting a compile-only word, for a local
8581: Locals have no interpretation semantics. If you try to perform the
8582: interpretation semantics, you will get a @code{-14 throw} somewhere
8583: (Interpreting a compile-only word). If you perform the compilation
8584: semantics, the locals access will be compiled (irrespective of state).
8585:
8586: @item @var{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
8587: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
8588: @cindex @code{TO} on non-@code{VALUE}s and non-locals
8589: @cindex Invalid name argument, @code{TO}
8590: @code{-32 throw} (Invalid name argument)
8591:
8592: @end table
8593:
8594:
8595: @c =====================================================================
8596: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
8597: @section The optional Memory-Allocation word set
8598: @c =====================================================================
8599: @cindex system documentation, memory-allocation words
8600: @cindex memory-allocation words, system documentation
8601:
8602: @menu
8603: * memory-idef:: Implementation Defined Options
8604: @end menu
8605:
8606:
8607: @c ---------------------------------------------------------------------
8608: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
8609: @subsection Implementation Defined Options
8610: @c ---------------------------------------------------------------------
8611: @cindex implementation-defined options, memory-allocation words
8612: @cindex memory-allocation words, implementation-defined options
8613:
8614: @table @i
8615: @item values and meaning of @var{ior}:
8616: @cindex @var{ior} values and meaning
8617: The @var{ior}s returned by the file and memory allocation words are
8618: intended as throw codes. They typically are in the range
8619: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
8620: @var{ior}s is -512@minus{}@var{errno}.
8621:
8622: @end table
8623:
8624: @c =====================================================================
8625: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
8626: @section The optional Programming-Tools word set
8627: @c =====================================================================
8628: @cindex system documentation, programming-tools words
8629: @cindex programming-tools words, system documentation
8630:
8631: @menu
8632: * programming-idef:: Implementation Defined Options
8633: * programming-ambcond:: Ambiguous Conditions
8634: @end menu
8635:
8636:
8637: @c ---------------------------------------------------------------------
8638: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
8639: @subsection Implementation Defined Options
8640: @c ---------------------------------------------------------------------
8641: @cindex implementation-defined options, programming-tools words
8642: @cindex programming-tools words, implementation-defined options
8643:
8644: @table @i
8645: @item ending sequence for input following @code{;CODE} and @code{CODE}:
8646: @cindex @code{;CODE} ending sequence
8647: @cindex @code{CODE} ending sequence
8648: @code{END-CODE}
8649:
8650: @item manner of processing input following @code{;CODE} and @code{CODE}:
8651: @cindex @code{;CODE}, processing input
8652: @cindex @code{CODE}, processing input
8653: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
8654: the input is processed by the text interpreter, (starting) in interpret
8655: state.
8656:
8657: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
8658: @cindex @code{ASSEMBLER}, search order capability
8659: The ANS Forth search order word set.
8660:
8661: @item source and format of display by @code{SEE}:
8662: @cindex @code{SEE}, source and format of output
8663: The source for @code{see} is the intermediate code used by the inner
8664: interpreter. The current @code{see} tries to output Forth source code
8665: as well as possible.
8666:
8667: @end table
8668:
8669: @c ---------------------------------------------------------------------
8670: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
8671: @subsection Ambiguous conditions
8672: @c ---------------------------------------------------------------------
8673: @cindex programming-tools words, ambiguous conditions
8674: @cindex ambiguous conditions, programming-tools words
8675:
8676: @table @i
8677:
1.21 crook 8678: @item deleting the compilation word list (@code{FORGET}):
8679: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 8680: Not implemented (yet).
8681:
1.26 ! crook 8682: @item fewer than @var{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
! 8683: @cindex @code{CS-PICK}, fewer than @var{u}+1 items on the control flow-stack
! 8684: @cindex @code{CS-ROLL}, fewer than @var{u}+1 items on the control flow-stack
1.1 anton 8685: @cindex control-flow stack underflow
8686: This typically results in an @code{abort"} with a descriptive error
8687: message (may change into a @code{-22 throw} (Control structure mismatch)
8688: in the future). You may also get a memory access error. If you are
8689: unlucky, this ambiguous condition is not caught.
8690:
8691: @item @var{name} can't be found (@code{FORGET}):
8692: @cindex @code{FORGET}, @var{name} can't be found
8693: Not implemented (yet).
8694:
8695: @item @var{name} not defined via @code{CREATE}:
8696: @cindex @code{;CODE}, @var{name} not defined via @code{CREATE}
8697: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
8698: the execution semantics of the last defined word no matter how it was
8699: defined.
8700:
8701: @item @code{POSTPONE} applied to @code{[IF]}:
8702: @cindex @code{POSTPONE} applied to @code{[IF]}
8703: @cindex @code{[IF]} and @code{POSTPONE}
8704: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
8705: equivalent to @code{[IF]}.
8706:
8707: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
8708: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
8709: Continue in the same state of conditional compilation in the next outer
8710: input source. Currently there is no warning to the user about this.
8711:
8712: @item removing a needed definition (@code{FORGET}):
8713: @cindex @code{FORGET}, removing a needed definition
8714: Not implemented (yet).
8715:
8716: @end table
8717:
8718:
8719: @c =====================================================================
8720: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
8721: @section The optional Search-Order word set
8722: @c =====================================================================
8723: @cindex system documentation, search-order words
8724: @cindex search-order words, system documentation
8725:
8726: @menu
8727: * search-idef:: Implementation Defined Options
8728: * search-ambcond:: Ambiguous Conditions
8729: @end menu
8730:
8731:
8732: @c ---------------------------------------------------------------------
8733: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
8734: @subsection Implementation Defined Options
8735: @c ---------------------------------------------------------------------
8736: @cindex implementation-defined options, search-order words
8737: @cindex search-order words, implementation-defined options
8738:
8739: @table @i
8740: @item maximum number of word lists in search order:
8741: @cindex maximum number of word lists in search order
8742: @cindex search order, maximum depth
8743: @code{s" wordlists" environment? drop .}. Currently 16.
8744:
8745: @item minimum search order:
8746: @cindex minimum search order
8747: @cindex search order, minimum
8748: @code{root root}.
8749:
8750: @end table
8751:
8752: @c ---------------------------------------------------------------------
8753: @node search-ambcond, , search-idef, The optional Search-Order word set
8754: @subsection Ambiguous conditions
8755: @c ---------------------------------------------------------------------
8756: @cindex search-order words, ambiguous conditions
8757: @cindex ambiguous conditions, search-order words
8758:
8759: @table @i
1.21 crook 8760: @item changing the compilation word list (during compilation):
8761: @cindex changing the compilation word list (during compilation)
8762: @cindex compilation word list, change before definition ends
8763: The word is entered into the word list that was the compilation word list
1.1 anton 8764: at the start of the definition. Any changes to the name field (e.g.,
8765: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
8766: are applied to the latest defined word (as reported by @code{last} or
1.21 crook 8767: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1 anton 8768:
8769: @item search order empty (@code{previous}):
8770: @cindex @code{previous}, search order empty
1.26 ! crook 8771: @cindex vocstack empty, @code{previous}
1.1 anton 8772: @code{abort" Vocstack empty"}.
8773:
8774: @item too many word lists in search order (@code{also}):
8775: @cindex @code{also}, too many word lists in search order
1.26 ! crook 8776: @cindex vocstack full, @code{also}
1.1 anton 8777: @code{abort" Vocstack full"}.
8778:
8779: @end table
8780:
8781: @c ***************************************************************
8782: @node Model, Integrating Gforth, ANS conformance, Top
8783: @chapter Model
8784:
8785: This chapter has yet to be written. It will contain information, on
8786: which internal structures you can rely.
8787:
8788: @c ***************************************************************
8789: @node Integrating Gforth, Emacs and Gforth, Model, Top
8790: @chapter Integrating Gforth into C programs
8791:
8792: This is not yet implemented.
8793:
8794: Several people like to use Forth as scripting language for applications
8795: that are otherwise written in C, C++, or some other language.
8796:
8797: The Forth system ATLAST provides facilities for embedding it into
8798: applications; unfortunately it has several disadvantages: most
8799: importantly, it is not based on ANS Forth, and it is apparently dead
8800: (i.e., not developed further and not supported). The facilities
1.21 crook 8801: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 8802: making the switch should not be hard.
8803:
8804: We also tried to design the interface such that it can easily be
8805: implemented by other Forth systems, so that we may one day arrive at a
8806: standardized interface. Such a standard interface would allow you to
8807: replace the Forth system without having to rewrite C code.
8808:
8809: You embed the Gforth interpreter by linking with the library
8810: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
8811: global symbols in this library that belong to the interface, have the
8812: prefix @code{forth_}. (Global symbols that are used internally have the
8813: prefix @code{gforth_}).
8814:
8815: You can include the declarations of Forth types and the functions and
8816: variables of the interface with @code{#include <forth.h>}.
8817:
8818: Types.
8819:
8820: Variables.
8821:
8822: Data and FP Stack pointer. Area sizes.
8823:
8824: functions.
8825:
8826: forth_init(imagefile)
8827: forth_evaluate(string) exceptions?
8828: forth_goto(address) (or forth_execute(xt)?)
8829: forth_continue() (a corountining mechanism)
8830:
8831: Adding primitives.
8832:
8833: No checking.
8834:
8835: Signals?
8836:
8837: Accessing the Stacks
8838:
1.26 ! crook 8839: @c ******************************************************************
1.1 anton 8840: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
8841: @chapter Emacs and Gforth
8842: @cindex Emacs and Gforth
8843:
8844: @cindex @file{gforth.el}
8845: @cindex @file{forth.el}
8846: @cindex Rydqvist, Goran
8847: @cindex comment editing commands
8848: @cindex @code{\}, editing with Emacs
8849: @cindex debug tracer editing commands
8850: @cindex @code{~~}, removal with Emacs
8851: @cindex Forth mode in Emacs
8852: Gforth comes with @file{gforth.el}, an improved version of
8853: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 ! crook 8854: improvements are:
! 8855:
! 8856: @itemize @bullet
! 8857: @item
! 8858: A better (but still not perfect) handling of indentation.
! 8859: @item
! 8860: Comment paragraph filling (@kbd{M-q})
! 8861: @item
! 8862: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
! 8863: @item
! 8864: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
! 8865: @end itemize
! 8866:
! 8867: I left the stuff I do not use alone, even though some of it only makes
! 8868: sense for TILE. To get a description of these features, enter Forth mode
! 8869: and type @kbd{C-h m}.
1.1 anton 8870:
8871: @cindex source location of error or debugging output in Emacs
8872: @cindex error output, finding the source location in Emacs
8873: @cindex debugging output, finding the source location in Emacs
8874: In addition, Gforth supports Emacs quite well: The source code locations
8875: given in error messages, debugging output (from @code{~~}) and failed
8876: assertion messages are in the right format for Emacs' compilation mode
8877: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
8878: Manual}) so the source location corresponding to an error or other
8879: message is only a few keystrokes away (@kbd{C-x `} for the next error,
8880: @kbd{C-c C-c} for the error under the cursor).
8881:
8882: @cindex @file{TAGS} file
8883: @cindex @file{etags.fs}
8884: @cindex viewing the source of a word in Emacs
1.26 ! crook 8885: Also, if you @code{include} @file{etags.fs}, a new @file{TAGS} file will
! 8886: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 8887: contains the definitions of all words defined afterwards. You can then
8888: find the source for a word using @kbd{M-.}. Note that emacs can use
8889: several tags files at the same time (e.g., one for the Gforth sources
8890: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
8891: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
8892: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
8893: @file{/usr/local/share/gforth/0.2.0/TAGS}).
8894:
8895: @cindex @file{.emacs}
8896: To get all these benefits, add the following lines to your @file{.emacs}
8897: file:
8898:
8899: @example
8900: (autoload 'forth-mode "gforth.el")
8901: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
8902: @end example
8903:
1.26 ! crook 8904: @c ******************************************************************
1.1 anton 8905: @node Image Files, Engine, Emacs and Gforth, Top
8906: @chapter Image Files
1.26 ! crook 8907: @cindex image file
! 8908: @cindex @file{.fi} files
1.1 anton 8909: @cindex precompiled Forth code
8910: @cindex dictionary in persistent form
8911: @cindex persistent form of dictionary
8912:
8913: An image file is a file containing an image of the Forth dictionary,
8914: i.e., compiled Forth code and data residing in the dictionary. By
8915: convention, we use the extension @code{.fi} for image files.
8916:
8917: @menu
1.18 anton 8918: * Image Licensing Issues:: Distribution terms for images.
8919: * Image File Background:: Why have image files?
8920: * Non-Relocatable Image Files:: don't always work.
8921: * Data-Relocatable Image Files:: are better.
1.1 anton 8922: * Fully Relocatable Image Files:: better yet.
1.18 anton 8923: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
8924: * Running Image Files:: @code{gforth -i @var{file}} or @var{file}.
8925: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 8926: @end menu
8927:
1.18 anton 8928: @node Image Licensing Issues, Image File Background, Image Files, Image Files
8929: @section Image Licensing Issues
8930: @cindex license for images
8931: @cindex image license
8932:
8933: An image created with @code{gforthmi} (@pxref{gforthmi}) or
8934: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
8935: original image; i.e., according to copyright law it is a derived work of
8936: the original image.
8937:
8938: Since Gforth is distributed under the GNU GPL, the newly created image
8939: falls under the GNU GPL, too. In particular, this means that if you
8940: distribute the image, you have to make all of the sources for the image
8941: available, including those you wrote. For details see @ref{License, ,
8942: GNU General Public License (Section 3)}.
8943:
8944: If you create an image with @code{cross} (@pxref{cross.fs}), the image
8945: contains only code compiled from the sources you gave it; if none of
8946: these sources is under the GPL, the terms discussed above do not apply
8947: to the image. However, if your image needs an engine (a gforth binary)
8948: that is under the GPL, you should make sure that you distribute both in
8949: a way that is at most a @emph{mere aggregation}, if you don't want the
8950: terms of the GPL to apply to the image.
8951:
8952: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 8953: @section Image File Background
8954: @cindex image file background
8955:
8956: Our Forth system consists not only of primitives, but also of
8957: definitions written in Forth. Since the Forth compiler itself belongs to
8958: those definitions, it is not possible to start the system with the
8959: primitives and the Forth source alone. Therefore we provide the Forth
1.26 ! crook 8960: code as an image file in nearly executable form. When Gforth starts up,
! 8961: a C routine loads the image file into memory, optionally relocates the
! 8962: addresses, then sets up the memory (stacks etc.) according to
! 8963: information in the image file, and (finally) starts executing Forth
! 8964: code.
1.1 anton 8965:
8966: The image file variants represent different compromises between the
8967: goals of making it easy to generate image files and making them
8968: portable.
8969:
8970: @cindex relocation at run-time
1.26 ! crook 8971: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 8972: run-time. This avoids many of the complications discussed below (image
8973: files are data relocatable without further ado), but costs performance
8974: (one addition per memory access).
8975:
8976: @cindex relocation at load-time
1.26 ! crook 8977: By contrast, the Gforth loader performs relocation at image load time. The
! 8978: loader also has to replace tokens that represent primitive calls with the
1.1 anton 8979: appropriate code-field addresses (or code addresses in the case of
8980: direct threading).
8981:
8982: There are three kinds of image files, with different degrees of
8983: relocatability: non-relocatable, data-relocatable, and fully relocatable
8984: image files.
8985:
8986: @cindex image file loader
8987: @cindex relocating loader
8988: @cindex loader for image files
8989: These image file variants have several restrictions in common; they are
8990: caused by the design of the image file loader:
8991:
8992: @itemize @bullet
8993: @item
8994: There is only one segment; in particular, this means, that an image file
8995: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 ! crook 8996: them). The contents of the stacks are not represented, either.
1.1 anton 8997:
8998: @item
8999: The only kinds of relocation supported are: adding the same offset to
9000: all cells that represent data addresses; and replacing special tokens
9001: with code addresses or with pieces of machine code.
9002:
9003: If any complex computations involving addresses are performed, the
9004: results cannot be represented in the image file. Several applications that
9005: use such computations come to mind:
9006: @itemize @minus
9007: @item
9008: Hashing addresses (or data structures which contain addresses) for table
9009: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
9010: purpose, you will have no problem, because the hash tables are
9011: recomputed automatically when the system is started. If you use your own
9012: hash tables, you will have to do something similar.
9013:
9014: @item
9015: There's a cute implementation of doubly-linked lists that uses
9016: @code{XOR}ed addresses. You could represent such lists as singly-linked
9017: in the image file, and restore the doubly-linked representation on
9018: startup.@footnote{In my opinion, though, you should think thrice before
9019: using a doubly-linked list (whatever implementation).}
9020:
9021: @item
9022: The code addresses of run-time routines like @code{docol:} cannot be
9023: represented in the image file (because their tokens would be replaced by
9024: machine code in direct threaded implementations). As a workaround,
9025: compute these addresses at run-time with @code{>code-address} from the
9026: executions tokens of appropriate words (see the definitions of
9027: @code{docol:} and friends in @file{kernel.fs}).
9028:
9029: @item
9030: On many architectures addresses are represented in machine code in some
9031: shifted or mangled form. You cannot put @code{CODE} words that contain
9032: absolute addresses in this form in a relocatable image file. Workarounds
9033: are representing the address in some relative form (e.g., relative to
9034: the CFA, which is present in some register), or loading the address from
9035: a place where it is stored in a non-mangled form.
9036: @end itemize
9037: @end itemize
9038:
9039: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
9040: @section Non-Relocatable Image Files
9041: @cindex non-relocatable image files
1.26 ! crook 9042: @cindex image file, non-relocatable
1.1 anton 9043:
9044: These files are simple memory dumps of the dictionary. They are specific
9045: to the executable (i.e., @file{gforth} file) they were created
9046: with. What's worse, they are specific to the place on which the
9047: dictionary resided when the image was created. Now, there is no
9048: guarantee that the dictionary will reside at the same place the next
9049: time you start Gforth, so there's no guarantee that a non-relocatable
9050: image will work the next time (Gforth will complain instead of crashing,
9051: though).
9052:
9053: You can create a non-relocatable image file with
9054:
9055: doc-savesystem
9056:
9057: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
9058: @section Data-Relocatable Image Files
9059: @cindex data-relocatable image files
1.26 ! crook 9060: @cindex image file, data-relocatable
1.1 anton 9061:
9062: These files contain relocatable data addresses, but fixed code addresses
9063: (instead of tokens). They are specific to the executable (i.e.,
9064: @file{gforth} file) they were created with. For direct threading on some
9065: architectures (e.g., the i386), data-relocatable images do not work. You
9066: get a data-relocatable image, if you use @file{gforthmi} with a
9067: Gforth binary that is not doubly indirect threaded (@pxref{Fully
9068: Relocatable Image Files}).
9069:
9070: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
9071: @section Fully Relocatable Image Files
9072: @cindex fully relocatable image files
1.26 ! crook 9073: @cindex image file, fully relocatable
1.1 anton 9074:
9075: @cindex @file{kern*.fi}, relocatability
9076: @cindex @file{gforth.fi}, relocatability
9077: These image files have relocatable data addresses, and tokens for code
9078: addresses. They can be used with different binaries (e.g., with and
9079: without debugging) on the same machine, and even across machines with
9080: the same data formats (byte order, cell size, floating point
9081: format). However, they are usually specific to the version of Gforth
9082: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
9083: are fully relocatable.
9084:
9085: There are two ways to create a fully relocatable image file:
9086:
9087: @menu
9088: * gforthmi:: The normal way
9089: * cross.fs:: The hard way
9090: @end menu
9091:
9092: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
9093: @subsection @file{gforthmi}
9094: @cindex @file{comp-i.fs}
9095: @cindex @file{gforthmi}
9096:
9097: You will usually use @file{gforthmi}. If you want to create an
9098: image @var{file} that contains everything you would load by invoking
9099: Gforth with @code{gforth @var{options}}, you simply say
9100: @example
9101: gforthmi @var{file} @var{options}
9102: @end example
9103:
9104: E.g., if you want to create an image @file{asm.fi} that has the file
9105: @file{asm.fs} loaded in addition to the usual stuff, you could do it
9106: like this:
9107:
9108: @example
9109: gforthmi asm.fi asm.fs
9110: @end example
9111:
9112: @file{gforthmi} works like this: It produces two non-relocatable
9113: images for different addresses and then compares them. Its output
9114: reflects this: first you see the output (if any) of the two Gforth
9115: invocations that produce the nonrelocatable image files, then you see
9116: the output of the comparing program: It displays the offset used for
9117: data addresses and the offset used for code addresses;
9118: moreover, for each cell that cannot be represented correctly in the
9119: image files, it displays a line like the following one:
9120:
9121: @example
9122: 78DC BFFFFA50 BFFFFA40
9123: @end example
9124:
9125: This means that at offset $78dc from @code{forthstart}, one input image
9126: contains $bffffa50, and the other contains $bffffa40. Since these cells
9127: cannot be represented correctly in the output image, you should examine
9128: these places in the dictionary and verify that these cells are dead
9129: (i.e., not read before they are written).
9130:
9131: @cindex @code{savesystem} during @file{gforthmi}
9132: @cindex @code{bye} during @file{gforthmi}
9133: @cindex doubly indirect threaded code
9134: @cindex environment variable @code{GFORTHD}
9135: @cindex @code{GFORTHD} environment variable
9136: @cindex @code{gforth-ditc}
9137: There are a few wrinkles: After processing the passed @var{options}, the
9138: words @code{savesystem} and @code{bye} must be visible. A special doubly
9139: indirect threaded version of the @file{gforth} executable is used for
9140: creating the nonrelocatable images; you can pass the exact filename of
9141: this executable through the environment variable @code{GFORTHD}
9142: (default: @file{gforth-ditc}); if you pass a version that is not doubly
9143: indirect threaded, you will not get a fully relocatable image, but a
9144: data-relocatable image (because there is no code address offset).
9145:
9146: @node cross.fs, , gforthmi, Fully Relocatable Image Files
9147: @subsection @file{cross.fs}
9148: @cindex @file{cross.fs}
9149: @cindex cross-compiler
9150: @cindex metacompiler
9151:
9152: You can also use @code{cross}, a batch compiler that accepts a Forth-like
9153: programming language. This @code{cross} language has to be documented
9154: yet.
9155:
9156: @cindex target compiler
9157: @code{cross} also allows you to create image files for machines with
9158: different data sizes and data formats than the one used for generating
9159: the image file. You can also use it to create an application image that
9160: does not contain a Forth compiler. These features are bought with
9161: restrictions and inconveniences in programming. E.g., addresses have to
9162: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
9163: order to make the code relocatable.
9164:
9165:
9166: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
9167: @section Stack and Dictionary Sizes
9168: @cindex image file, stack and dictionary sizes
9169: @cindex dictionary size default
9170: @cindex stack size default
9171:
9172: If you invoke Gforth with a command line flag for the size
9173: (@pxref{Invoking Gforth}), the size you specify is stored in the
9174: dictionary. If you save the dictionary with @code{savesystem} or create
9175: an image with @file{gforthmi}, this size will become the default
9176: for the resulting image file. E.g., the following will create a
1.21 crook 9177: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 9178:
9179: @example
9180: gforthmi gforth.fi -m 1M
9181: @end example
9182:
9183: In other words, if you want to set the default size for the dictionary
9184: and the stacks of an image, just invoke @file{gforthmi} with the
9185: appropriate options when creating the image.
9186:
9187: @cindex stack size, cache-friendly
9188: Note: For cache-friendly behaviour (i.e., good performance), you should
9189: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
9190: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
9191: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
9192:
9193: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
9194: @section Running Image Files
9195: @cindex running image files
9196: @cindex invoking image files
9197: @cindex image file invocation
9198:
9199: @cindex -i, invoke image file
9200: @cindex --image file, invoke image file
9201: You can invoke Gforth with an image file @var{image} instead of the
9202: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
9203: @example
9204: gforth -i @var{image}
9205: @end example
9206:
9207: @cindex executable image file
1.26 ! crook 9208: @cindex image file, executable
1.1 anton 9209: If your operating system supports starting scripts with a line of the
9210: form @code{#! ...}, you just have to type the image file name to start
9211: Gforth with this image file (note that the file extension @code{.fi} is
9212: just a convention). I.e., to run Gforth with the image file @var{image},
9213: you can just type @var{image} instead of @code{gforth -i @var{image}}.
9214:
1.26 ! crook 9215: For example, if you place this text in a file:
! 9216:
! 9217: @example
! 9218: #! /usr/local/bin/gforth
! 9219:
! 9220: ." Hello, world" CR
! 9221: bye
! 9222:
! 9223: @end example
! 9224:
! 9225: @noindent
! 9226: And then make the file executable (chmod +x in Unix), you can run it
! 9227: directly from the command line. The sequence @code{#!} is used in two
! 9228: ways; firstly, it is recognised as a ``magic sequence'' by the operating
! 9229: system, secondly it is treated as a comment character by Gforth. Because
! 9230: of the second usage, a space is required between @code{#!} and the path
! 9231: to the executable.
! 9232: @comment TODO describe the #! magic with reference to the Power Tools book.
! 9233:
1.1 anton 9234: doc-#!
9235:
9236: @node Modifying the Startup Sequence, , Running Image Files, Image Files
9237: @section Modifying the Startup Sequence
9238: @cindex startup sequence for image file
9239: @cindex image file initialization sequence
9240: @cindex initialization sequence of image file
9241:
9242: You can add your own initialization to the startup sequence through the
1.26 ! crook 9243: deferred word @code{'cold}. @code{'cold} is invoked just before the
! 9244: image-specific command line processing (by default, loading files and
! 9245: evaluating (@code{-e}) strings) starts.
1.1 anton 9246:
9247: A sequence for adding your initialization usually looks like this:
9248:
9249: @example
9250: :noname
9251: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
9252: ... \ your stuff
9253: ; IS 'cold
9254: @end example
9255:
9256: @cindex turnkey image files
1.26 ! crook 9257: @cindex image file, turnkey applications
1.1 anton 9258: You can make a turnkey image by letting @code{'cold} execute a word
9259: (your turnkey application) that never returns; instead, it exits Gforth
9260: via @code{bye} or @code{throw}.
9261:
9262: @cindex command-line arguments, access
9263: @cindex arguments on the command line, access
9264: You can access the (image-specific) command-line arguments through the
1.26 ! crook 9265: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1 anton 9266: access to @code{argv}.
9267:
1.26 ! crook 9268: If @code{'cold} exits normally, Gforth processes the command-line
! 9269: arguments as files to be loaded and strings to be evaluated. Therefore,
! 9270: @code{'cold} should remove the arguments it has used in this case.
! 9271:
! 9272: doc-'cold
1.1 anton 9273: doc-argc
9274: doc-argv
9275: doc-arg
9276:
9277:
9278: @c ******************************************************************
1.13 pazsan 9279: @node Engine, Binding to System Library, Image Files, Top
1.1 anton 9280: @chapter Engine
9281: @cindex engine
9282: @cindex virtual machine
9283:
1.26 ! crook 9284: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 9285: may be helpful for finding your way in the Gforth sources.
9286:
9287: The ideas in this section have also been published in the papers
9288: @cite{ANS fig/GNU/??? Forth} (in German) by Bernd Paysan, presented at
9289: the Forth-Tagung '93 and @cite{A Portable Forth Engine} by M. Anton
9290: Ertl, presented at EuroForth '93; the latter is available at
9291: @*@url{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z}.
9292:
9293: @menu
9294: * Portability::
9295: * Threading::
9296: * Primitives::
9297: * Performance::
9298: @end menu
9299:
9300: @node Portability, Threading, Engine, Engine
9301: @section Portability
9302: @cindex engine portability
9303:
1.26 ! crook 9304: An important goal of the Gforth Project is availability across a wide
! 9305: range of personal machines. fig-Forth, and, to a lesser extent, F83,
! 9306: achieved this goal by manually coding the engine in assembly language
! 9307: for several then-popular processors. This approach is very
! 9308: labor-intensive and the results are short-lived due to progress in
! 9309: computer architecture.
1.1 anton 9310:
9311: @cindex C, using C for the engine
9312: Others have avoided this problem by coding in C, e.g., Mitch Bradley
9313: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
9314: particularly popular for UNIX-based Forths due to the large variety of
9315: architectures of UNIX machines. Unfortunately an implementation in C
9316: does not mix well with the goals of efficiency and with using
9317: traditional techniques: Indirect or direct threading cannot be expressed
9318: in C, and switch threading, the fastest technique available in C, is
9319: significantly slower. Another problem with C is that it is very
9320: cumbersome to express double integer arithmetic.
9321:
9322: @cindex GNU C for the engine
9323: @cindex long long
9324: Fortunately, there is a portable language that does not have these
9325: limitations: GNU C, the version of C processed by the GNU C compiler
9326: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
9327: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
9328: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
9329: threading possible, its @code{long long} type (@pxref{Long Long, ,
9330: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
9331: double numbers@footnote{Unfortunately, long longs are not implemented
9332: properly on all machines (e.g., on alpha-osf1, long longs are only 64
9333: bits, the same size as longs (and pointers), but they should be twice as
1.4 anton 9334: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1 anton 9335: C Manual}). So, we had to implement doubles in C after all. Still, on
9336: most machines we can use long longs and achieve better performance than
9337: with the emulation package.}. GNU C is available for free on all
9338: important (and many unimportant) UNIX machines, VMS, 80386s running
9339: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
9340: on all these machines.
9341:
9342: Writing in a portable language has the reputation of producing code that
9343: is slower than assembly. For our Forth engine we repeatedly looked at
9344: the code produced by the compiler and eliminated most compiler-induced
9345: inefficiencies by appropriate changes in the source code.
9346:
9347: @cindex explicit register declarations
9348: @cindex --enable-force-reg, configuration flag
9349: @cindex -DFORCE_REG
9350: However, register allocation cannot be portably influenced by the
9351: programmer, leading to some inefficiencies on register-starved
9352: machines. We use explicit register declarations (@pxref{Explicit Reg
9353: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
9354: improve the speed on some machines. They are turned on by using the
9355: configuration flag @code{--enable-force-reg} (@code{gcc} switch
9356: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
9357: machine, but also on the compiler version: On some machines some
9358: compiler versions produce incorrect code when certain explicit register
9359: declarations are used. So by default @code{-DFORCE_REG} is not used.
9360:
9361: @node Threading, Primitives, Portability, Engine
9362: @section Threading
9363: @cindex inner interpreter implementation
9364: @cindex threaded code implementation
9365:
9366: @cindex labels as values
9367: GNU C's labels as values extension (available since @code{gcc-2.0},
9368: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
9369: makes it possible to take the address of @var{label} by writing
9370: @code{&&@var{label}}. This address can then be used in a statement like
9371: @code{goto *@var{address}}. I.e., @code{goto *&&x} is the same as
9372: @code{goto x}.
9373:
1.26 ! crook 9374: @cindex @code{NEXT}, indirect threaded
1.1 anton 9375: @cindex indirect threaded inner interpreter
9376: @cindex inner interpreter, indirect threaded
1.26 ! crook 9377: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 9378: @example
9379: cfa = *ip++;
9380: ca = *cfa;
9381: goto *ca;
9382: @end example
9383: @cindex instruction pointer
9384: For those unfamiliar with the names: @code{ip} is the Forth instruction
9385: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
9386: execution token and points to the code field of the next word to be
9387: executed; The @code{ca} (code address) fetched from there points to some
9388: executable code, e.g., a primitive or the colon definition handler
9389: @code{docol}.
9390:
1.26 ! crook 9391: @cindex @code{NEXT}, direct threaded
1.1 anton 9392: @cindex direct threaded inner interpreter
9393: @cindex inner interpreter, direct threaded
9394: Direct threading is even simpler:
9395: @example
9396: ca = *ip++;
9397: goto *ca;
9398: @end example
9399:
9400: Of course we have packaged the whole thing neatly in macros called
1.26 ! crook 9401: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 9402:
9403: @menu
9404: * Scheduling::
9405: * Direct or Indirect Threaded?::
9406: * DOES>::
9407: @end menu
9408:
9409: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
9410: @subsection Scheduling
9411: @cindex inner interpreter optimization
9412:
9413: There is a little complication: Pipelined and superscalar processors,
9414: i.e., RISC and some modern CISC machines can process independent
9415: instructions while waiting for the results of an instruction. The
9416: compiler usually reorders (schedules) the instructions in a way that
9417: achieves good usage of these delay slots. However, on our first tries
9418: the compiler did not do well on scheduling primitives. E.g., for
9419: @code{+} implemented as
9420: @example
9421: n=sp[0]+sp[1];
9422: sp++;
9423: sp[0]=n;
9424: NEXT;
9425: @end example
1.26 ! crook 9426: the @code{NEXT} comes strictly after the other code, i.e., there is nearly no
1.1 anton 9427: scheduling. After a little thought the problem becomes clear: The
1.21 crook 9428: compiler cannot know that @code{sp} and @code{ip} point to different
9429: addresses (and the version of @code{gcc} we used would not know it even
9430: if it was possible), so it could not move the load of the cfa above the
9431: store to the TOS. Indeed the pointers could be the same, if code on or
9432: very near the top of stack were executed. In the interest of speed we
9433: chose to forbid this probably unused ``feature'' and helped the compiler
1.26 ! crook 9434: in scheduling: @code{NEXT} is divided into the loading part (@code{NEXT_P1})
1.21 crook 9435: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
1.1 anton 9436: @example
9437: n=sp[0]+sp[1];
9438: sp++;
9439: NEXT_P1;
9440: sp[0]=n;
9441: NEXT_P2;
9442: @end example
9443: This can be scheduled optimally by the compiler.
9444:
9445: This division can be turned off with the switch @code{-DCISC_NEXT}. This
9446: switch is on by default on machines that do not profit from scheduling
9447: (e.g., the 80386), in order to preserve registers.
9448:
9449: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
9450: @subsection Direct or Indirect Threaded?
9451: @cindex threading, direct or indirect?
9452:
9453: @cindex -DDIRECT_THREADED
9454: Both! After packaging the nasty details in macro definitions we
9455: realized that we could switch between direct and indirect threading by
9456: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
9457: defining a few machine-specific macros for the direct-threading case.
9458: On the Forth level we also offer access words that hide the
9459: differences between the threading methods (@pxref{Threading Words}).
9460:
9461: Indirect threading is implemented completely machine-independently.
9462: Direct threading needs routines for creating jumps to the executable
1.21 crook 9463: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
9464: machine-dependent, but they do not amount to many source lines. Therefore,
9465: even porting direct threading to a new machine requires little effort.
1.1 anton 9466:
9467: @cindex --enable-indirect-threaded, configuration flag
9468: @cindex --enable-direct-threaded, configuration flag
9469: The default threading method is machine-dependent. You can enforce a
9470: specific threading method when building Gforth with the configuration
9471: flag @code{--enable-direct-threaded} or
9472: @code{--enable-indirect-threaded}. Note that direct threading is not
9473: supported on all machines.
9474:
9475: @node DOES>, , Direct or Indirect Threaded?, Threading
9476: @subsection DOES>
9477: @cindex @code{DOES>} implementation
9478:
1.26 ! crook 9479: @cindex @code{dodoes} routine
! 9480: @cindex @code{DOES>}-code
1.1 anton 9481: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
9482: the chunk of code executed by every word defined by a
9483: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
9484: the Forth code to be executed, i.e. the code after the
1.26 ! crook 9485: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
1.1 anton 9486:
1.21 crook 9487: In fig-Forth the code field points directly to the @code{dodoes} and the
1.26 ! crook 9488: @code{DOES>}code address is stored in the cell after the code address (i.e. at
! 9489: @code{@var{CFA} cell+}). It may seem that this solution is illegal in
1.1 anton 9490: the Forth-79 and all later standards, because in fig-Forth this address
9491: lies in the body (which is illegal in these standards). However, by
9492: making the code field larger for all words this solution becomes legal
9493: again. We use this approach for the indirect threaded version and for
9494: direct threading on some machines. Leaving a cell unused in most words
9495: is a bit wasteful, but on the machines we are targeting this is hardly a
9496: problem. The other reason for having a code field size of two cells is
9497: to avoid having different image files for direct and indirect threaded
9498: systems (direct threaded systems require two-cell code fields on many
9499: machines).
9500:
1.26 ! crook 9501: @cindex @code{DOES>}-handler
1.1 anton 9502: The other approach is that the code field points or jumps to the cell
1.26 ! crook 9503: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
! 9504: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
! 9505: @code{DOES>}-code address by computing the code address, i.e., the address of
1.1 anton 9506: the jump to dodoes, and add the length of that jump field. A variant of
9507: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
9508: return address (which can be found in the return register on RISCs) is
1.26 ! crook 9509: the @code{DOES>}-code address. Since the two cells available in the code field
1.1 anton 9510: are used up by the jump to the code address in direct threading on many
9511: architectures, we use this approach for direct threading on these
9512: architectures. We did not want to add another cell to the code field.
9513:
9514: @node Primitives, Performance, Threading, Engine
9515: @section Primitives
9516: @cindex primitives, implementation
9517: @cindex virtual machine instructions, implementation
9518:
9519: @menu
9520: * Automatic Generation::
9521: * TOS Optimization::
9522: * Produced code::
9523: @end menu
9524:
9525: @node Automatic Generation, TOS Optimization, Primitives, Primitives
9526: @subsection Automatic Generation
9527: @cindex primitives, automatic generation
9528:
9529: @cindex @file{prims2x.fs}
9530: Since the primitives are implemented in a portable language, there is no
9531: longer any need to minimize the number of primitives. On the contrary,
9532: having many primitives has an advantage: speed. In order to reduce the
9533: number of errors in primitives and to make programming them easier, we
9534: provide a tool, the primitive generator (@file{prims2x.fs}), that
9535: automatically generates most (and sometimes all) of the C code for a
9536: primitive from the stack effect notation. The source for a primitive
9537: has the following form:
9538:
9539: @cindex primitive source format
9540: @format
9541: @var{Forth-name} @var{stack-effect} @var{category} [@var{pronounc.}]
9542: [@code{""}@var{glossary entry}@code{""}]
9543: @var{C code}
9544: [@code{:}
9545: @var{Forth code}]
9546: @end format
9547:
9548: The items in brackets are optional. The category and glossary fields
9549: are there for generating the documentation, the Forth code is there
9550: for manual implementations on machines without GNU C. E.g., the source
9551: for the primitive @code{+} is:
9552: @example
9553: + n1 n2 -- n core plus
9554: n = n1+n2;
9555: @end example
9556:
9557: This looks like a specification, but in fact @code{n = n1+n2} is C
9558: code. Our primitive generation tool extracts a lot of information from
9559: the stack effect notations@footnote{We use a one-stack notation, even
9560: though we have separate data and floating-point stacks; The separate
9561: notation can be generated easily from the unified notation.}: The number
9562: of items popped from and pushed on the stack, their type, and by what
9563: name they are referred to in the C code. It then generates a C code
9564: prelude and postlude for each primitive. The final C code for @code{+}
9565: looks like this:
9566:
9567: @example
9568: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
9569: /* */ /* documentation */
9570: @{
9571: DEF_CA /* definition of variable ca (indirect threading) */
9572: Cell n1; /* definitions of variables */
9573: Cell n2;
9574: Cell n;
9575: n1 = (Cell) sp[1]; /* input */
9576: n2 = (Cell) TOS;
9577: sp += 1; /* stack adjustment */
9578: NAME("+") /* debugging output (with -DDEBUG) */
9579: @{
9580: n = n1+n2; /* C code taken from the source */
9581: @}
9582: NEXT_P1; /* NEXT part 1 */
9583: TOS = (Cell)n; /* output */
9584: NEXT_P2; /* NEXT part 2 */
9585: @}
9586: @end example
9587:
9588: This looks long and inefficient, but the GNU C compiler optimizes quite
9589: well and produces optimal code for @code{+} on, e.g., the R3000 and the
9590: HP RISC machines: Defining the @code{n}s does not produce any code, and
9591: using them as intermediate storage also adds no cost.
9592:
1.26 ! crook 9593: There are also other optimizations that are not illustrated by this
! 9594: example: assignments between simple variables are usually for free (copy
1.1 anton 9595: propagation). If one of the stack items is not used by the primitive
9596: (e.g. in @code{drop}), the compiler eliminates the load from the stack
9597: (dead code elimination). On the other hand, there are some things that
9598: the compiler does not do, therefore they are performed by
9599: @file{prims2x.fs}: The compiler does not optimize code away that stores
9600: a stack item to the place where it just came from (e.g., @code{over}).
9601:
9602: While programming a primitive is usually easy, there are a few cases
9603: where the programmer has to take the actions of the generator into
9604: account, most notably @code{?dup}, but also words that do not (always)
1.26 ! crook 9605: fall through to @code{NEXT}.
1.1 anton 9606:
9607: @node TOS Optimization, Produced code, Automatic Generation, Primitives
9608: @subsection TOS Optimization
9609: @cindex TOS optimization for primitives
9610: @cindex primitives, keeping the TOS in a register
9611:
9612: An important optimization for stack machine emulators, e.g., Forth
9613: engines, is keeping one or more of the top stack items in
9614: registers. If a word has the stack effect @var{in1}...@var{inx} @code{--}
9615: @var{out1}...@var{outy}, keeping the top @var{n} items in registers
9616: @itemize @bullet
9617: @item
9618: is better than keeping @var{n-1} items, if @var{x>=n} and @var{y>=n},
9619: due to fewer loads from and stores to the stack.
9620: @item is slower than keeping @var{n-1} items, if @var{x<>y} and @var{x<n} and
9621: @var{y<n}, due to additional moves between registers.
9622: @end itemize
9623:
9624: @cindex -DUSE_TOS
9625: @cindex -DUSE_NO_TOS
9626: In particular, keeping one item in a register is never a disadvantage,
9627: if there are enough registers. Keeping two items in registers is a
9628: disadvantage for frequent words like @code{?branch}, constants,
9629: variables, literals and @code{i}. Therefore our generator only produces
9630: code that keeps zero or one items in registers. The generated C code
9631: covers both cases; the selection between these alternatives is made at
9632: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
9633: code for @code{+} is just a simple variable name in the one-item case,
9634: otherwise it is a macro that expands into @code{sp[0]}. Note that the
9635: GNU C compiler tries to keep simple variables like @code{TOS} in
9636: registers, and it usually succeeds, if there are enough registers.
9637:
9638: @cindex -DUSE_FTOS
9639: @cindex -DUSE_NO_FTOS
9640: The primitive generator performs the TOS optimization for the
9641: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
9642: operations the benefit of this optimization is even larger:
9643: floating-point operations take quite long on most processors, but can be
9644: performed in parallel with other operations as long as their results are
9645: not used. If the FP-TOS is kept in a register, this works. If
9646: it is kept on the stack, i.e., in memory, the store into memory has to
9647: wait for the result of the floating-point operation, lengthening the
9648: execution time of the primitive considerably.
9649:
9650: The TOS optimization makes the automatic generation of primitives a
9651: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
9652: @code{TOS} is not sufficient. There are some special cases to
9653: consider:
9654: @itemize @bullet
9655: @item In the case of @code{dup ( w -- w w )} the generator must not
9656: eliminate the store to the original location of the item on the stack,
9657: if the TOS optimization is turned on.
9658: @item Primitives with stack effects of the form @code{--}
9659: @var{out1}...@var{outy} must store the TOS to the stack at the start.
9660: Likewise, primitives with the stack effect @var{in1}...@var{inx} @code{--}
9661: must load the TOS from the stack at the end. But for the null stack
9662: effect @code{--} no stores or loads should be generated.
9663: @end itemize
9664:
9665: @node Produced code, , TOS Optimization, Primitives
9666: @subsection Produced code
9667: @cindex primitives, assembly code listing
9668:
9669: @cindex @file{engine.s}
9670: To see what assembly code is produced for the primitives on your machine
9671: with your compiler and your flag settings, type @code{make engine.s} and
9672: look at the resulting file @file{engine.s}.
9673:
9674: @node Performance, , Primitives, Engine
9675: @section Performance
9676: @cindex performance of some Forth interpreters
9677: @cindex engine performance
9678: @cindex benchmarking Forth systems
9679: @cindex Gforth performance
9680:
9681: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
9682: impossible to write a significantly faster engine.
9683:
9684: On register-starved machines like the 386 architecture processors
9685: improvements are possible, because @code{gcc} does not utilize the
9686: registers as well as a human, even with explicit register declarations;
9687: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
9688: and hand-tuned it for the 486; this system is 1.19 times faster on the
9689: Sieve benchmark on a 486DX2/66 than Gforth compiled with
9690: @code{gcc-2.6.3} with @code{-DFORCE_REG}.
9691:
9692: @cindex Win32Forth performance
9693: @cindex NT Forth performance
9694: @cindex eforth performance
9695: @cindex ThisForth performance
9696: @cindex PFE performance
9697: @cindex TILE performance
9698: However, this potential advantage of assembly language implementations
9699: is not necessarily realized in complete Forth systems: We compared
9700: Gforth (direct threaded, compiled with @code{gcc-2.6.3} and
9701: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
9702: 1994) and Eforth (with and without peephole (aka pinhole) optimization
9703: of the threaded code); all these systems were written in assembly
9704: language. We also compared Gforth with three systems written in C:
9705: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
9706: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
1.21 crook 9707: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
9708: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
1.1 anton 9709: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
9710: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
9711: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
9712: 486DX2/66 with similar memory performance under Windows NT. Marcel
9713: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
9714: added the peephole optimizer, ran the benchmarks and reported the
9715: results.
9716:
9717: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
9718: matrix multiplication come from the Stanford integer benchmarks and have
9719: been translated into Forth by Martin Fraeman; we used the versions
9720: included in the TILE Forth package, but with bigger data set sizes; and
9721: a recursive Fibonacci number computation for benchmarking calling
9722: performance. The following table shows the time taken for the benchmarks
9723: scaled by the time taken by Gforth (in other words, it shows the speedup
9724: factor that Gforth achieved over the other systems).
9725:
9726: @example
9727: relative Win32- NT eforth This-
9728: time Gforth Forth Forth eforth +opt PFE Forth TILE
9729: sieve 1.00 1.39 1.14 1.39 0.85 1.58 3.18 8.58
9730: bubble 1.00 1.31 1.41 1.48 0.88 1.50 3.88
9731: matmul 1.00 1.47 1.35 1.46 0.74 1.58 4.09
9732: fib 1.00 1.52 1.34 1.22 0.86 1.74 2.99 4.30
9733: @end example
9734:
1.26 ! crook 9735: You may be quite surprised by the good performance of Gforth when
! 9736: compared with systems written in assembly language. One important reason
! 9737: for the disappointing performance of these other systems is probably
! 9738: that they are not written optimally for the 486 (e.g., they use the
! 9739: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
! 9740: but costly method for relocating the Forth image: like @code{cforth}, it
! 9741: computes the actual addresses at run time, resulting in two address
! 9742: computations per @code{NEXT} (@pxref{Image File Background}).
! 9743:
! 9744: Only Eforth with the peephole optimizer has a performance that is
! 9745: comparable to Gforth. The speedups achieved with peephole optimization
! 9746: of threaded code are quite remarkable. Adding a peephole optimizer to
! 9747: Gforth should cause similar speedups.
1.1 anton 9748:
9749: The speedup of Gforth over PFE, ThisForth and TILE can be easily
9750: explained with the self-imposed restriction of the latter systems to
9751: standard C, which makes efficient threading impossible (however, the
1.4 anton 9752: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 9753: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
9754: Moreover, current C compilers have a hard time optimizing other aspects
9755: of the ThisForth and the TILE source.
9756:
1.26 ! crook 9757: The performance of Gforth on 386 architecture processors varies widely
! 9758: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
! 9759: allocate any of the virtual machine registers into real machine
! 9760: registers by itself and would not work correctly with explicit register
! 9761: declarations, giving a 1.3 times slower engine (on a 486DX2/66 running
! 9762: the Sieve) than the one measured above.
1.1 anton 9763:
1.26 ! crook 9764: Note that there have been several releases of Win32Forth since the
! 9765: release presented here, so the results presented above may have little
1.1 anton 9766: predictive value for the performance of Win32Forth today.
9767:
9768: @cindex @file{Benchres}
9769: In @cite{Translating Forth to Efficient C} by M. Anton Ertl and Martin
9770: Maierhofer (presented at EuroForth '95), an indirect threaded version of
9771: Gforth is compared with Win32Forth, NT Forth, PFE, and ThisForth; that
9772: version of Gforth is 2%@minus{}8% slower on a 486 than the direct
9773: threaded version used here. The paper available at
9774: @*@url{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz};
9775: it also contains numbers for some native code systems. You can find a
9776: newer version of these measurements at
9777: @url{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
9778: find numbers for Gforth on various machines in @file{Benchres}.
9779:
1.26 ! crook 9780: @c ******************************************************************
1.13 pazsan 9781: @node Binding to System Library, Cross Compiler, Engine, Top
1.14 pazsan 9782: @chapter Binding to System Library
1.13 pazsan 9783:
9784: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14 pazsan 9785: @chapter Cross Compiler
1.13 pazsan 9786:
9787: Cross Compiler
9788:
9789: @menu
9790: * Using the Cross Compiler::
9791: * How the Cross Compiler Works::
9792: @end menu
9793:
1.21 crook 9794: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 9795: @section Using the Cross Compiler
1.13 pazsan 9796:
1.21 crook 9797: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 9798: @section How the Cross Compiler Works
1.13 pazsan 9799:
9800: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 9801: @appendix Bugs
1.1 anton 9802: @cindex bug reporting
9803:
1.21 crook 9804: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 9805:
9806: If you find a bug, please send a bug report to
1.21 crook 9807: @email{bug-gforth@@gnu.ai.mit.edu}. A bug report should include this
9808: information:
9809:
9810: @itemize @bullet
9811: @item
9812: The Gforth version used (it is announced at the start of an
9813: interactive Gforth session).
9814: @item
9815: The machine and operating system (on Unix
9816: systems @code{uname -a} will report this information).
9817: @item
9818: The installation options (send the file @file{config.status}).
9819: @item
9820: A complete list of changes (if any) you (or your installer) have made to the
9821: Gforth sources.
9822: @item
9823: A program (or a sequence of keyboard commands) that reproduces the bug.
9824: @item
9825: A description of what you think constitutes the buggy behaviour.
9826: @end itemize
1.1 anton 9827:
9828: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
9829: to Report Bugs, gcc.info, GNU C Manual}.
9830:
9831:
1.21 crook 9832: @node Origin, Forth-related information, Bugs, Top
9833: @appendix Authors and Ancestors of Gforth
1.1 anton 9834:
9835: @section Authors and Contributors
9836: @cindex authors of Gforth
9837: @cindex contributors to Gforth
9838:
9839: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
9840: Ertl. The third major author was Jens Wilke. Lennart Benschop (who was
9841: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
9842: with their continuous feedback. Lennart Benshop contributed
9843: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
9844: support for calling C libraries. Helpful comments also came from Paul
9845: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.12 anton 9846: Wavrik, Barrie Stott, Marc de Groot, and Jorge Acerada. Since the
9847: release of Gforth-0.2.1 there were also helpful comments from many
9848: others; thank you all, sorry for not listing you here (but digging
1.23 crook 9849: through my mailbox to extract your names is on my to-do list). Since the
9850: release of Gforth-0.4.0 Neal Crook worked on the manual.
1.1 anton 9851:
9852: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
9853: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 9854: was developed across the Internet, and its authors did not meet
1.20 pazsan 9855: physically for the first 4 years of development.
1.1 anton 9856:
9857: @section Pedigree
1.26 ! crook 9858: @cindex pedigree of Gforth
1.1 anton 9859:
1.20 pazsan 9860: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
1.1 anton 9861: Dirk Zoller) will cross-fertilize each other. Of course, a significant
9862: part of the design of Gforth was prescribed by ANS Forth.
9863:
1.20 pazsan 9864: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 9865: 32 bit native code version of VolksForth for the Atari ST, written
9866: mostly by Dietrich Weineck.
9867:
9868: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
9869: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
9870: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
9871:
9872: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
9873: Forth-83 standard. !! Pedigree? When?
9874:
9875: A team led by Bill Ragsdale implemented fig-Forth on many processors in
9876: 1979. Robert Selzer and Bill Ragsdale developed the original
9877: implementation of fig-Forth for the 6502 based on microForth.
9878:
9879: The principal architect of microForth was Dean Sanderson. microForth was
9880: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
9881: the 1802, and subsequently implemented on the 8080, the 6800 and the
9882: Z80.
9883:
9884: All earlier Forth systems were custom-made, usually by Charles Moore,
9885: who discovered (as he puts it) Forth during the late 60s. The first full
9886: Forth existed in 1971.
9887:
9888: A part of the information in this section comes from @cite{The Evolution
9889: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
9890: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
9891: Notices 28(3), 1993. You can find more historical and genealogical
9892: information about Forth there.
9893:
1.21 crook 9894: @node Forth-related information, Word Index, Origin, Top
9895: @appendix Other Forth-related information
9896: @cindex Forth-related information
9897:
9898: @menu
9899: * Internet resources::
9900: * Books::
9901: * The Forth Interest Group::
9902: * Conferences::
9903: @end menu
9904:
9905:
9906: @node Internet resources, Books, Forth-related information, Forth-related information
9907: @section Internet resources
1.26 ! crook 9908: @cindex internet resources
1.21 crook 9909:
9910: @cindex comp.lang.forth
9911: @cindex frequently asked questions
9912: There is an active newsgroup (comp.lang.forth) discussing Forth and
9913: Forth-related issues. A frequently-asked-questions (FAQ) list
9914: is posted to the newsgroup regulary, and archived at these sites:
9915:
9916: @itemize @bullet
9917: @item
9918: @url{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
9919: @item
9920: @url{ftp://ftp.forth.org/pub/Forth/FAQ/}
9921: @end itemize
9922:
9923: The FAQ list should be considered mandatory reading before posting to
9924: the newsgroup.
9925:
9926: Here are some other web sites holding Forth-related material:
9927:
9928: @itemize @bullet
9929: @item
9930: @url{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
9931: @item
9932: @url{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
9933: @item
9934: @url{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
9935: @item
9936: @url{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
9937: Research page, including links to the Journal of Forth Application and
9938: Research (JFAR) and a searchable Forth bibliography.
9939: @end itemize
9940:
9941:
9942: @node Books, The Forth Interest Group, Internet resources, Forth-related information
9943: @section Books
1.26 ! crook 9944: @cindex books on Forth
1.21 crook 9945:
9946: As the Standard is relatively new, there are not many books out yet. It
9947: is not recommended to learn Forth by using Gforth and a book that is not
9948: written for ANS Forth, as you will not know your mistakes from the
9949: deviations of the book. However, books based on the Forth-83 standard
9950: should be ok, because ANS Forth is primarily an extension of Forth-83.
9951:
9952: @cindex standard document for ANS Forth
9953: @cindex ANS Forth document
9954: The definite reference if you want to write ANS Forth programs is, of
1.26 ! crook 9955: course, the ANS Forth document. It is available in printed form from the
1.21 crook 9956: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
9957: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
9958: $200. You can also get it from Global Engineering Documents (Tel.: USA
9959: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
9960:
9961: @cite{dpANS6}, the last draft of the standard, which was then submitted
9962: to ANSI for publication is available electronically and for free in some
9963: MS Word format, and it has been converted to HTML
9964: (@url{http://www.taygeta.com/forth/dpans.html}; this is my favourite
9965: format); this HTML version also includes the answers to Requests for
9966: Interpretation (RFIs). Some pointers to these versions can be found
9967: through @*@url{http://www.complang.tuwien.ac.at/projects/forth.html}.
9968:
1.26 ! crook 9969: @cindex introductory book on Forth
! 9970: @cindex book on Forth, introductory
1.21 crook 9971: @cindex Woehr, Jack: @cite{Forth: The New Model}
9972: @cindex @cite{Forth: The new model} (book)
9973: @cite{Forth: The New Model} by Jack Woehr (Prentice-Hall, 1993) is an
9974: introductory book based on a draft version of the standard. It does not
9975: cover the whole standard. It also contains interesting background
9976: information (Jack Woehr was in the ANS Forth Technical Committee). It is
9977: not appropriate for complete newbies, but programmers experienced in
9978: other languages should find it ok.
9979:
9980: @cindex Conklin, Edward K., and Elizabeth Rather: @cite{Forth Programmer's Handbook}
9981: @cindex Rather, Elizabeth and Edward K. Conklin: @cite{Forth Programmer's Handbook}
9982: @cindex @cite{Forth Programmer's Handbook} (book)
9983: @cite{Forth Programmer's Handbook} by Edward K. Conklin, Elizabeth
9984: D. Rather and the technical staff of Forth, Inc. (Forth, Inc., 1997;
9985: ISBN 0-9662156-0-5) contains little introductory material. The majority
9986: of the book is similar to @ref{Words}, but the book covers most of the
9987: standard words and some non-standard words (whereas this manual is
9988: quite incomplete). In addition, the book contains a chapter on
9989: programming style. The major drawback of this book is that it usually
9990: does not identify what is standard and what is specific to the Forth
9991: system described in the book (probably one of Forth, Inc.'s systems).
9992: Fortunately, many of the non-standard programming practices described in
9993: the book work in Gforth, too. Still, this drawback makes the book
9994: hardly more useful than a pre-ANS book.
9995:
9996: @node The Forth Interest Group, Conferences, Books, Forth-related information
9997: @section The Forth Interest Group
9998: @cindex Forth interest group (FIG)
9999:
10000: The Forth Interest Group (FIG) is a world-wide, non-profit,
1.26 ! crook 10001: member-supported organisation. It publishes a regular magazine,
! 10002: @var{FORTH Dimensions}, and offers other benefits of membership. You can
! 10003: contact the FIG through their office email address:
! 10004: @email{office@@forth.org} or by visiting their web site at
! 10005: @url{http://www.forth.org/}. This web site also includes links to FIG
! 10006: chapters in other countries and American cities
1.21 crook 10007: (@url{http://www.forth.org/chapters.html}).
10008:
10009: @node Conferences, , The Forth Interest Group, Forth-related information
10010: @section Conferences
10011: @cindex Conferences
10012:
10013: There are several regular conferences related to Forth. They are all
1.26 ! crook 10014: well-publicised in @var{FORTH Dimensions} and on the comp.lang.forth
! 10015: news group:
1.21 crook 10016:
10017: @itemize @bullet
10018: @item
10019: FORML -- the Forth modification laboratory convenes every year near
10020: Monterey, California.
10021: @item
10022: The Rochester Forth Conference -- an annual conference traditionally
10023: held in Rochester, New York.
10024: @item
10025: EuroForth -- this European conference takes place annually.
10026: @end itemize
10027:
10028:
10029: @node Word Index, Concept Index, Forth-related information, Top
1.1 anton 10030: @unnumbered Word Index
10031:
1.26 ! crook 10032: This index is a list of Forth words that have ``glossary'' entries
! 10033: within this manual. Each word is listed with its stack effect and
! 10034: wordset.
1.1 anton 10035:
10036: @printindex fn
10037:
10038: @node Concept Index, , Word Index, Top
10039: @unnumbered Concept and Word Index
10040:
1.26 ! crook 10041: Not all entries listed in this index are present verbatim in the
! 10042: text. This index also duplicates, in abbreviated form, all of the words
! 10043: listed in the Word Index (only the names are listed for the words here).
1.1 anton 10044:
10045: @printindex cp
10046:
10047: @contents
10048: @bye
10049:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>